如何单元测试与angularjs $位置服务控制器 [英] How to unit test angularjs controller with $location service
本文介绍了如何单元测试与angularjs $位置服务控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图创建一个简单的单元测试,测试我的节目的功能。
我收到以下错误:
类型错误:对象#<对象>没有方法秀
好像$ rootScope不是控制器的范围有多大?
下面是我的控制器:
函数OpponentsCtrl($范围,$位置){
$ scope.show =功能(URL){
$ location.path(URL);
}
}
。OpponentsCtrl $注射='$范围,$位置'];
下面是我的控制器单元测试:
描述('OpponentsCtrl',函数(){
beforeEach(模块(函数($提供){
$ provide.factory('OpponentsCtrl',函数($位置){
//无论它...
});
})); 它('通过展示功能设置时,它应改变位置,注入(函数($位置$ rootScope,OpponentsCtrl){
$ location.path('/新/路径);
$ rootScope $适用()。
期待($ location.path())TOBE('/新/路径)。 $ rootScope.show('/测试');
期待($ location.path())TOBE('/测试')。
}));
});
解决方案
为什么不这样做简单的使用功能spyOn?
描述('OpponentsCtrl',函数(){ VAR位置; beforeEach(模块(函数($提供){
$ provide.factory('OpponentsCtrl',函数($位置){
位置= $位置;
});
})); 它('通过展示功能设置时,它应改变位置,注入(函数(){
spyOn(位置,'通路');
期待(location.path).toHaveBeenCalledWith('/新/路径);
}));
});
希望这有助于!
干杯
I'm trying to create a simple unittest that tests my show function. I get the following error:
TypeError: Object #<Object> has no method 'show'
It seems like $rootScope isn't the scope of the controller?
Here's my controller:
function OpponentsCtrl($scope, $location) {
$scope.show = function(url) {
$location.path(url);
}
}
OpponentsCtrl.$inject = ['$scope', '$location'];
Here's my controller unittest:
describe('OpponentsCtrl', function() {
beforeEach(module(function($provide) {
$provide.factory('OpponentsCtrl', function($location){
// whatever it does...
});
}));
it('should change location when setting it via show function', inject(function($location, $rootScope, OpponentsCtrl) {
$location.path('/new/path');
$rootScope.$apply();
expect($location.path()).toBe('/new/path');
$rootScope.show('/test');
expect($location.path()).toBe('/test');
}));
});
解决方案
Why you don't simple use a spyOn function?
describe('OpponentsCtrl', function() {
var location;
beforeEach(module(function($provide) {
$provide.factory('OpponentsCtrl', function($location){
location = $location;
});
}));
it('should change location when setting it via show function', inject(function() {
spyOn(location, 'path');
expect(location.path).toHaveBeenCalledWith('/new/path');
}));
});
Hope this helps! Cheers
这篇关于如何单元测试与angularjs $位置服务控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文