javascript 测试 angularjs ui-router go() 方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19282006/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:59:01  来源:igfitidea点击:

testing angularjs ui-router go() method

javascriptangularjstestingangular-ui-routerkarma-runner

提问by shmish111

I have a controller which gets a value from $scopeand sends it to a different state:

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

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

I am unsure how to go about unit testing this search method. How can I either verify that the go method has been called or do some sort of when($state.go('search', $stateParams)).then(called = true);with Karma/AngularJS?

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

回答by Andyrooger

Both of these sound like things you can do with Jasmine spies.

这两个听起来像是你可以用茉莉花间谍做的事情。

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);
        // ...
    }));
});

There is a good spy cheatsheet here http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/or the actual Jasmine docs here.

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

The nice thing about using spies is that it will let you avoid actually performing the state transition unless you explicitly tell it to. A state transition will fail your unit test in Karma if it changes the URL.

使用 spies 的好处是它可以让你避免实际执行状态转换,除非你明确告诉它。如果更改 URL,状态转换将使 Karma 中的单元测试失败。