我通过装饰$controller服务装饰了一个控制器“originalCtrl”:
//module declaration angular.module('decorationModule',[ 'originalModule','ExternalService' ]) //decoration .decorator('$controller',function ($delegate,ExternalService) { return function () { //check when the OriginalCtrl is instantiated if (arguments[0] === 'OriginalCtrl') { return function () { const ctrl = $delegate.apply($delegate,arguments)(); //memorize the original close function const delegatedCloseFn = ctrl.closefn; ctrl.close = function close() { alert('bye bye before closing'); ExternalService.fn(); delegatedCloseFn(); alert('bye bye After closing'); }; return ctrl; } } else { return $delegate.apply($delegate,arguments); } } });
它运作良好.
但是,尝试对其进行单元测试:
beforeEach(angular.mock.module('decorationModule',($controller,$q,ExternalService) => { scope = $rootScope.$new(); createController = () => { return $controller('OriginalCtrl',{$scope: scope}); }; spyOn(ExternalService,'fn').and.returnValue(); })); it('should call decorated close function',inject((ExternalService) => { //given const ctrl = createController(); expect(ExternalService.fn).not.toHaveBeenCalled(); //when ctrl.close(); //then expect(ExternalService.fn).toHaveBeenCalled(); }));
我收到一个错误:
forEach@/home/…/bower_components/angular/angular.js:322:24
loadModules@/home/…/bower_components/angular/angular.js:4548:12
createInjector@/home/…/bower_components/angular/angular.js:4470:30
workFn@/home/…/bower_components/angular-mocks/angular-mocks.js:2954:60
解决方法
在我的业力配置文件中添加以下行帮助我解决了这个错误
files: [ '../node_modules/angular/angular.js','../www/lib/ionic/js/ionic.bundle.js','../node_modules/angular-mocks/angular-mocks.js','../www/js/*.js','test.js' ],
这里test.js是我编写测试用例的文件.
并尝试更换线
angular.mock.module('decorationModule' ......
有了这个
module('decorationModule' ......
顺便说一下,我正在使用离子,所以我添加了ionic.bundle.js文件,如果这不是你的情况,请提供配置文件来帮助你.并确保angular.js和angular-mocks.js的版本相同.希望能帮助到你.