I have search around a few places to get ideas on this.
How do I unit test $scope.broadcast, $scope.$on using Jasmine
$scope.$on not working in Jasmine SpecRunner
It has helped I think but seems I am still missing something. I am trying to test a controller that has a $rootScope.$on in the code. So in the unit test I am trying to trigger the $broadcast so the $on gets it and the code runs. But my current code is not working.
Here is 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);
}
});
}
Here is my test:
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 get 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 say they are never called. What do I have missed aligned?