在Angular + Jasmine中测试事件链和module.run() [英] Testing event chains and module.run() in Angular + Jasmine
问题描述
我正在尝试测试具有以下代码的模块:
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);
});
}
});
]);
我的测试如下:
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');
});
我遇到的问题是第二个期望值返回false.我认为问题在于该模块未使用相同的$ rootScope初始化.
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
推荐答案
在运行块中,您预订$rootScope
上的$stateChangeStart
并从$rootScope
广播$stateChangeSuccess
事件.
In your run block, you subscribe a $stateChangeStart
on $rootScope
and also broadcast a $stateChangeSuccess
event from $rootScope
.
在测试中,您必须使用$rootscope
进行相同的操作.可以更改此行:
In your test, you have to do the same, using the $rootscope
. May be change this line:
$scope = _$rootScope_.$new();
仅此:
$scope = _$rootScope_;
此外,您还必须删除$scope.$broadcast.reset()
,这将清除所有已记住的呼叫.
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');
});
希望这会有所帮助.
这篇关于在Angular + Jasmine中测试事件链和module.run()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!