问题
I am trying to test a module that has the following code:
angular.module('angularEnterpriseAuthorization').run(['$rootScope', '$state', 'AppConfig',
function($rootScope, $state, AppConfig) {
// On every time the user changes state check to see if the user has permissions to go to the new state
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams) {
// If the state is not one of the public states as defined in the modules config
if (AppConfig.publicStates.indexOf(toState.name) < 0) {
event.preventDefault();
$state.go(toState, toParams, {notify: false}).then(function() {
$rootScope.$broadcast('$stateChangeSuccess', toState, toParams, fromState, fromParams);
});
}
});
]);
My test looks like this:
beforeEach(module('angularEnterpriseAuthorization', 'coreConfiguration'));
beforeEach(inject(function(_$rootScope_, _$httpBackend_, _AppConfig_) {
$scope = _$rootScope_.$new();
$httpBackend = _$httpBackend_;
AppConfig = _AppConfig_
spyOn($scope, '$broadcast').andCallThrough();
}));
it('should allow navigation to public states', function() {
$scope.$broadcast('$stateChangeStart', [{},{name:AppConfig.publicStates[0]}]);
expect($scope.$broadcast).toHaveBeenCalledWith('$stateChangeStart', [{}, {name: AppConfig.publicStates[0]}]);
$scope.$broadcast.reset();
expect($scope.$broadcast).toHaveBeenCalledWith('$stateChangeSuccess');
});
The problem I am having is that the second expect is returning false. I think the issues is that the module is not being initialized with the same $rootScope.
Any help would be appreciated! Thanks
回答1:
In your run block, you subscribe a $stateChangeStart
on $rootScope
and also broadcast a $stateChangeSuccess
event from $rootScope
.
In your test, you have to do the same, using the $rootscope
. May be change this line:
$scope = _$rootScope_.$new();
to just this:
$scope = _$rootScope_;
And also you have to remove the $scope.$broadcast.reset()
, that will clear all the remembered calls.
To test the second call of the same method, you could do it like this:
it('should allow navigation to public states', function() {
$scope.$broadcast('$stateChangeStart', [{},{name:AppConfig.publicStates[0]}]);
expect($scope.$broadcast).toHaveBeenCalledWith('$stateChangeStart', [{}, {name: AppConfig.publicStates[0]}]);
$scope.$apply();
expect($scope.$broadcast.calls[1].args[0]).toEqual('$stateChangeSuccess');
});
Hope this helps.
来源:https://stackoverflow.com/questions/25366933/testing-event-chains-and-module-run-in-angular-jasmine