13

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);
    };
}]);

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?

4

1 回答 1

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

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

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

于 2013-10-10T01:33:39.513 回答