测试angularjs UI路由器go()方法 [英] testing angularjs ui-router go() method
问题描述
我有一个控制器从 $范围
获取一个值,并将其发送到不同的状态:
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);
};
}]);
我不知道该如何去单元测试该搜索方法。我如何可以验证该走方法被调用或做某种时($ state.go('搜索',$ stateParams)),那么(称为= TRUE)的;
与噶/ AngularJS?
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?
推荐答案
这两种声音喜欢的东西,你可以用茉莉花间谍做的。
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);
// ...
}));
});
这是一个很好的间谍的cheatsheet这里<一个href=\"http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/\">http://tobyho.com/2011/12/15/jasmine-spy-cheatsheet/或实际茉莉花文档这里 http://pivotal.github.io/jasmine/ 。
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/.
有关使用间谍的好处是,它可以让你避免实际执行的状态转换,除非你明确告诉它。如果它改变了URL的状态转换将会失败单元测试中得分。
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.
这篇关于测试angularjs UI路由器go()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!