Angular-Karma控制器测试:UI-Router持久化$ stateParams依赖

时间:2015-10-09 00:37:17

标签: angularjs testing angular-ui-router mocha karma-runner

我正在尝试围绕控制器构建一些测试。我正在使用$ stateParams注入一个测试,然后两次导航到同一个状态。第一个测试通过,但第二个测试失败,因为它认为creationId仍为1。

NSLineBreakByTruncatingTail

为什么会这样?有没有什么我需要在之前或之后运行以清除状态?

1 个答案:

答案 0 :(得分:3)

正如对问题的评论中所提到的,为了使测试对控制器进行测试,$state应该用某种方式来模拟状态转换是否已经发生。

这是我们在one of our open source projects中使用的内容:

state-mock.js

angular.module('stateMock', []);
angular.module('stateMock').service('stateMock', function($q) {
    'use strict';

    this.expectedTransitions = [];

    this.transitionTo = function(stateName, params) {
        if (this.expectedTransitions.length > 0) {
            var expectedState = this.expectedTransitions.shift();
            if (expectedState.stateName !== stateName) {
                throw Error('Expected transition to state: ' + expectedState.stateName + ' but transitioned to ' + stateName);
            }
            if (!angular.equals(expectedState.params, params)) {
                throw Error('Expected params to be ' + JSON.stringify(expectedState.params) + ' but received ' + JSON.stringify(params));
            }
        } else {
            throw Error('No more transitions were expected! Tried to transition to ' + stateName);
        }
        // console.log('Mock transition to: ' + stateName + ' with params: ' + JSON.stringify(params));
        return $q.when();
    };

    this.go = this.transitionTo;

    this.expectTransitionTo = function(stateName, params) {
        this.expectedTransitions.push({
            stateName: stateName,
            params: params
        });
    };

    this.ensureAllTransitionsHappened = function() {
        if (this.expectedTransitions.length > 0) {
            throw Error('Not all transitions happened!');
        }
    };
});

来自规范的these lines应该让您对如何使用它有一个很好的了解。

describe('state', function() {

    it('should transition correctly on invoking previous', function() {
        state.expectTransitionTo('month', {
            year: 2015,
            month: 7
        });
        $scope.previous();
        state.ensureAllTransitionsHappened();
    });

    it('should transition correctly on invoking next', function() {
        state.expectTransitionTo('month', {
            year: 2015,
            month: 9
        });
        $scope.next();
        state.ensureAllTransitionsHappened();
    });

    it('should transition correctly on month change', function() {
        state.expectTransitionTo('month', {
            year: 2015,
            month: 1
        });
        calendar.month = 1;
        $scope.$digest();
        state.ensureAllTransitionsHappened();
    });

    it('should transition correctly on year change', function() {
        state.expectTransitionTo('month', {
            year: 1979,
            month: 8
        });
        calendar.year = 1979;
        $scope.$digest();
        state.ensureAllTransitionsHappened();
    });

});