Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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?

share|improve this question

1 Answer 1

up vote 10 down vote accepted

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 http://pivotal.github.io/jasmine/.

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.

share|improve this answer
    
Perfect, just what I was looking for. –  shmish111 Oct 10 '13 at 12:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.