我装饰了一个控制器" originalCtrl"通过装饰$ controller服务:
//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 @ /家庭/.../ bower_components /角度/ angular.js:322:24 loadModules @ /家庭/.../ bower_components /角度/ angular.js:4548:12 createInjector @ /家/.../ bower_components /角/ angular.js:4470:30 workFn @ /家庭/.../ bower_components /角嘲笑/角mocks.js:2954:60
答案 0 :(得分:0)
在我的业力配置文件中添加以下行,帮助我解决了此错误
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的合作方式,我添加了ionic.bundle.js文件,如果不是这种情况,请提供配置文件来帮助您。 并确保angular.js和angular-mocks.js的版本相同。 希望对您有所帮助。