2013-10-09 15 views
13

Ho un controller che ottiene un valore da $scope e lo invia ad uno stato diverso:test angularjs go ui-router() Metodo

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

non sono sicuro di come fare per unità di testare questo metodo di ricerca. Come posso verificare che il metodo go sia stato chiamato o effettuare una sorta di when($state.go('search', $stateParams)).then(called = true); con Karma/AngularJS?

risposta

31

Entrambi sembrano cose che puoi fare con le spie di 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); 
     // ... 
    })); 
}); 

C'è un buon bigino spia qui http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/ o la documentazione Jasmine effettivi here.

La cosa bella dell'utilizzo di spie è che ti consente di evitare di eseguire effettivamente la transizione di stato a meno che non lo dici esplicitamente. Una transizione di stato fallirà il tuo test unitario in Karma se cambia l'URL.

+0

Perfetto, proprio quello che stavo cercando. – shmish111

+8

Con Jasmine 2.x, sostituire la funzione chiamata '.andCallFake' con'. And.callFake'. – satJ

Problemi correlati