Reputation: 41
I have decorated a controller "originalCtrl" by decorating the $controller service:
//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);
}
}
});
it is working well.
But, trying to make a Unit test on it:
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();
}));
I got an error:
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
Upvotes: 4
Views: 744
Reputation: 609
Adding below lines in my karma configuration file helped me to solve this error
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'
],
Here test.js is the file where I have written my test cases. And try by replacing the line
angular.mock.module('decorationModule' ......
With this
module('decorationModule' ......
By the way I'm working with ionic so I have added ionic.bundle.js file and if this is not your case provide me configuration file to help you. And make sure versions of angular.js and angular-mocks.js are same. Hope it helps.
Upvotes: 0