我正在尝试测试以下代码:
$rootScope.$on('$routeChangeError', function(event, current, previous, rejection) {
if(rejection === 'Unauthenticated') {
$location.path('/');
}
});
这是测试:
it('should catch unauthorised route changes and route to log in', function() {
spyOn(this.$location, 'path');
this.$rootScope.$emit('$routeChangeError', { event: null, current: null, previous: null, rejection: 'Unauthenticated' });
expect(this.$location.path).toBe('/');
});
但是,由于 Angular 控制此事件,所以我传递给 $emit 的任何参数都无法到达另一端。事实上,除了“事件”之外,一切都是未定义的,它填充了实际事件。
路线是这样的:
.when('/welcome', {
controller: 'main.controller',
templateUrl: '/welcome.html',
resolve: { 'authFilter': 'oauthFilter.factory' }
});
authFilter 看起来像这样:
(function(mainModule) {
'use strict';
mainModule.factory('oauthFilter.factory',
['$location', '$q', 'authentication.service',
function($location, $q, authenticationService) {
if(authenticationService.isAuthenticated()) {
return true;
}
return $q.reject('Unauthenticated');
}
]);
})(angular.module('main'));
我也尝试过创建 Controller 并使用 $q.reject('Unauthenticated') 注入(inject)它,应用范围但这根本不会引发事件。
我错过了什么?提前致谢。
最佳答案
参数需要单独传递到 $emit 中,而不是作为单个对象传递,即:
this.$rootScope.$emit('$routeChangeError', null, null, null, 'Unauthenticated');
关于javascript - 测试 $routeChangeError 无法设置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23296199/