测试ui-router和stateChangeStart

时间:2015-07-22 08:59:29

标签: angularjs jasmine angular-ui-router

这是我的生产代码:

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我们要改变的状态?

在生产代码中按预期工作,在测试中,而不是。

1 个答案:

答案 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
});