I have been searching in various places for ideas on this topic.
How can I unit test $scope.broadcast and $scope.$on using Jasmine?
$scope.$on is not working in Jasmine SpecRunner
Although the information I found has been helpful, it seems like there's still something missing. I am attempting to test a controller that includes a $rootScope.$on in its code. In my unit test, I'm trying to trigger the $broadcast so that the $on function captures it and executes the code. However, my current code is not functioning as intended.
Below is the snippet of my controller:
constructor($state: ng.ui.IStateService, store: angular.a0.storage.IStoreService, jwtHelper: angular.jwt.IJwtHelper, $rootScope: any) {
this.currentDate = new Date();
this.state = $state;
this.store = store;
this.jwtHelper = jwtHelper;
this.userFullname = '';
$rootScope.$on('$stateChangeStart',
(event: any, toState: any, toParams: any, fromState: any, fromParams: any, error: any) => {
var jwtToken = this.store.get('token');
if (jwtToken != null) {
var decodedToken: any = this.jwtHelper.decodeToken(jwtToken);
}
});
}
And here is my testing script:
beforeEach(angular.mock.inject(($compile: ng.ICompileService, $rootScope: any, $controller: any, $state: ng.ui.IStateService, jwtHelper: angular.jwt.IJwtHelper) => {
controllerScope = $rootScope.$new();
navbarController = $controller('NavbarController', { $scope: controllerScope });
currentDate = new Date();
rootScope = $rootScope;
state = $state;
jwt = jwtHelper;
}
it('should receive broadcast for user token', () => {
spyOn(controllerScope, '$on');
spyOn(jwt, 'decodeToken');
//state.go('home'); Was trying a different way to trigger the event
rootScope.$broadcast('$stateChangeStart', [{ toState: 'home' }]);
expect(controllerScope.$on).toHaveBeenCalled();
expect(jwt.decodeToken).toHaveBeenCalled();
});
Both spies indicate they are never being called. What could be misaligned in my setup?