如何测试角度ui-router $ stateChangeStart监听器?

时间:2014-08-29 19:14:55

标签: angularjs unit-testing jasmine angular-ui-router

这是我在角度中使用的基本身份验证方案。我试图对这个监听状态变化的小块进行单元测试,并检查它们是否需要身份验证以及用户是否经过身份验证。如果他们未经过身份验证,则会阻止状态更改。

angular.module('app').run(function ($rootScope, $state, auth) {

    // enable authenticated states
    $rootScope.$on('$stateChangeStart', function (event, toState) {
        if (toState.authenticate && !auth.isAuthenticated()) {
            // prevent state change
            event.preventDefault();
        }
    });

});

到目前为止,这是我的单元测试。

describe('events', function () {

// setup ------------------------------------------------------------------

    // init app module
    beforeEach(module('app'));

    // inject dependencies
    beforeEach(angular.mock.inject(function (_$rootScope_, _$state_, _auth_) {
        $rootScope = _$rootScope_;
        $state     = _$state_;
        auth       = _auth_;
    }));

// tests ------------------------------------------------------------------

    // prevent state transition when unauthorized
    it('check if a user can view a given state', function () {
        $state.go('user');
        expect(auth.isAuthenticated).toHaveBeenCalled();
        expect(event.preventDefault()).toHaveBeenCalled();
    });

});

我目前正在收到一个错误,它预计会有间谍,但是第一个期望得到了一个功能,并且在第二个期望中事件未定义。我试过像这样设立一个间谍。

beforeEach(function () {
    spyOn(auth, 'isAuthenticated').andCallThrough();
});

这个包含在设置中我得到一个错误预期间谍isAuthenticated被调用。我理解为什么事件是未定义的但不确定如何解决它因为它是匿名函数的参数。我还想测试是否正在调用toState.authenticate,但期望遇到同样的问题。

我从哪里开始?

0 个答案:

没有答案
相关问题