在Angular + Jasmine中测试事件链和module.run()

时间:2014-08-18 15:31:45

标签: angularjs 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进行初始化。

任何帮助将不胜感激! 感谢

1 个答案:

答案 0 :(得分:2)

在您的运行版块中,您在$stateChangeStart上订阅$rootScope,并从$stateChangeSuccess广播$rootScope个活动。

在测试中,您必须使用$rootscope执行相同的操作。可能会改变这一行:

$scope = _$rootScope_.$new();

就是这样:

$scope = _$rootScope_;

而且你必须删除$scope.$broadcast.reset(),这将清除所有记住的电话。

要测试同一方法的第二次调用,您可以这样做:

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');
});

希望这有帮助。