测试 angularjs ui-router go() 方法 [英] testing angularjs ui-router go() method

查看:21
本文介绍了测试 angularjs ui-router go() 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

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?

推荐答案

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

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

这里有一个很好的间谍备忘单 http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/ 或实际的 Jasmine 文档这里.

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

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

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.

这篇关于测试 angularjs ui-router go() 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆