【问题标题】:testing angularjs ui-router go() method测试 angularjs ui-router go() 方法
【发布时间】:2013-10-09 20:29:14
【问题描述】:

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

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

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

【问题讨论】:

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


    【解决方案1】:

    这两件事听起来都像是你可以用 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);
            // ...
        }));
    });
    

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

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

    【讨论】:

    • 完美,正是我想要的。
    • 在 Jasmine 2.x 中,将函数调用 .andCallFake 替换为 .and.callFake
    猜你喜欢
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-12
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    相关资源
    最近更新 更多