这是我的生产代码:
myApp.run ($rootScope, $location, AuthService, $state) ->
$rootScope.$on '$stateChangeStart', (event, toState, toParams, fromState, fromParams) ->
$rootScope.stateChangeStarthasBeenCalled = true
if toState.authenticate is true
$rootScope.authNecessaryButNotProvided = true
我的路由器的一部分,我设置authenticate
平面
.state('auth.profile',
url : 'someURL'
templateUrl : 'some.html'
controller : 'AuthController'
authenticate: true
)
我这样测试:
it 'should have stateChangeStarthasBeenCalled defined', ->
mockRootScope.$broadcast("$stateChangeStart", "event", "toState:auth.profile", "toParams", "fromState", "fromParams")
expect(mockRootScope.stateChangeStarthasBeenCalled).toBeTruthy()
it 'should have authNecessaryButNotProvided defined', ->
mockRootScope.$broadcast("$stateChangeStart", "event", "toState:auth.profile", "toParams", "fromState", "fromParams")
expect(mockRootScope.authNecessaryButNotProvided).toBeTruthy()
我想查看toState
对象,例如我在路线中定义的toState.authenticate
。
作为先决条件,如何告诉stateChangeStart
我们要改变的状态?
在生产代码中按预期工作,在测试中,而不是。
答案 0 :(得分:3)
您可以手动指定事件的参数,它们将传递给事件处理程序:
mockRootScope.$broadcast(
'$stateChangeStart',
{ name: 'auth.profile', authenticate: true }, // toState
{}, // toParams
{}, // fromState
{} // fromParams
);
它们将以相同的顺序出现,第一个参数将保留给event
对象,但是:
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
// ----------------------------------------^
// first argument "event" is auto-generated
console.log(toState.authenticate); // true
});