The problem:
- using AngularJs
- given an implemented a service
- trying to test it with Jasmine
Here is how my service looks like:
angular.module('app.common').service('StateInterceptor',['$state','$rootScope',function($state,$rootScope){
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams){/*stuffs*/}
}
and here is how I'm trying to test whether the $rootScope.$on
has been called:
describe("Testing StateInterceptor service", function(){
var $state, $rootScope, $scope, StateInterceptor;
beforeEach(module('app.common'));
beforeEach(inject(function($injector) {
$rootScope = $injector.get("$rootScope");
spyOn($rootScope, "$on");
$state = $injector.get("$state");
StateInterceptor = $injector.get("StateInterceptor");
}));
it("WHEN created THEN it should call '$rootScope.$on' event listener", function(){
//expect($rootScope.$on).toHaveBeenCalled(); //not working neither
expect($rootScope.$on).toHaveBeenCalledWith("$stateChangeStart", jasmine.any(Function));
});
What I've got is an error message, saying:
Expected spy $on to have been called with... (blabla) but it was never called.
I've tried almost everything like:
- creating rootscope in this was: $rootScope = $rootScope.$new();
- spying $rootScope.$on
like in this way: spyOn($rootScope.prototype, "$on")
but neither was working. Do anybody know how to test it in the right way?
Edit1:
the original code seems to working so I've pasted here the exactly code that I have. So my service looks like exactly that:
angular.module('app.common').service('StateInterceptor',['$state','$rootScope',function($state,$rootScope){
var self = this;
self.bootstrapped = false;
self.changeStart = [];
self.init = function(){
if(!self.bootstrapped){
$rootScope.$on('$stateChangeStart',
function(event, toState, toParams, fromState, fromParams){
/*staffs*/
}
);
}
}
self.bootstrapped = true;
self.init();
return self;
}]);
Edit2:
I've put a few console.log to see how the code executed:
beforeEach(inject(function($injector) {
$rootScope = $injector.get("$rootScope");
spyOn($rootScope, "$on");
$state = $injector.get("$state");
StateInterceptor = $injector.get("StateInterceptor");
}));
And for the code for the first line within self.init function:
console.log("init runs");
And the result is: 'init runs' 'before' 'after'
Strange! Any idea why is that?