测试angularjs ui-router go()方法

shm*_*111 13 javascript testing angularjs karma-runner angular-ui-router

我有一个控制器从中获取值$scope并将其发送到不同的状态:

controllers.controller('SearchController', ['$scope', '$state', '$stateParams',
function($scope, $state, $stateParams) {
    $scope.search = function() {
        $stateParams.query = $scope.keyword;
        $state.go('search', $stateParams);
    };
}]);
Run Code Online (Sandbox Code Playgroud)

我不确定如何对这种搜索方法进行单元测试.我怎样才能验证是否已调用go方法或when($state.go('search', $stateParams)).then(called = true);使用Karma/AngularJS进行某种操作?

And*_*ger 34

这两个听起来都像你可以用Jasmine间谍做的事情.

describe('my unit tests', function() {
    beforeEach(inject(function($state) {
        spyOn($state, 'go');
        // or
        spyOn($state, 'go').andCallFake(function(state, params) {
            // This replaces the 'go' functionality for the duration of your test
        });
    }));

    it('should test something', inject(function($state){
        // Call something that eventually hits $state.go
        expect($state.go).toHaveBeenCalled();
        expect($state.go).toHaveBeenCalledWith(expectedState, expectedParams);
        // ...
    }));
});
Run Code Online (Sandbox Code Playgroud)

这里有一个很好的间谍的cheatsheet http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/或实际茉莉花文档在这里.

使用间谍的好处是它可以让你避免实际执行状态转换,除非你明确告诉它.如果更改URL,状态转换将无法在Karma中进行单元测试.

  • 使用Jasmine 2.x,将函数调用`.andCallFake`替换为`.and.callFake`. (9认同)