testing angularjs ui-router go() method

前端 未结 1 1669
礼貌的吻别
礼貌的吻别 2020-12-28 19:25

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

controllers.controller(\'SearchController\', [\'$scope\',          


        
相关标签:
1条回答
  • 2020-12-28 20:00

    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.

    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.

    0 讨论(0)
提交回复
热议问题