如何测试服务中的$location和.search()
How to test $location and .search() in a service
我有一个简单的服务,它有许多方法从URL检索各种值:
app.service('urlInterpSrv', function($location) {
return {
getCartID : function() {
return $location.search().getCartID;
},
getUserAddress : function() {
return $location.search().getUserAddress;
},
getShippingCountry : function() {
return $location.search().getShippingCountry;
},
getCookie : function() {
return $location.search().getCookie;
},
getUsername : function() {
return $location.search().getUsername;
}
};
});
我在我的控制器中调用它们,只需通过:
app.controller('ShoppingCartController', function($scope, urlInterpSrv, $rootScope) {
$scope.getCartID = urlInterpSrv.getCartID();
$scope.getShippingCountry = urlInterpSrv.getShippingCountry();
});
三个问题吗?我应该显式地测试服务,还是测试控制器,还是两者都测试?
我已经尝试通过:
describe('urlInterpSrv', function(){
var $location;
beforeEach(module('myApp'));
beforeEach(inject(function (_urlInterpSrv_, _$location_) {
this.urlInterpSrv = _urlInterpSrv_;
$location = _$location_;
}));
it('should getCartID from url', function(){
$location.path('/?getCartID=0087598');
expect(this.urlInterpSrv.getCartID).toEqual(0087598);
});
});
但是我得到错误:
Expected Function to equal 87598.
$location.path
不改变url的'search'部分,它改变'path'部分并编码?
字符。
应该避免前导为0的数字,因为它们在JS中可以被视为八进制。
解析参数值中的原语不是$location
的工作,getCartID
等于'0087598'字符串,而不是87598。
it('should getCartID from url', function(){
$location.url('/?getCartID=0087598');
expect(this.urlInterpSrv.getCartID()).toEqual('0087598');
});
您正在断言函数,而不是它的返回值。试一试:
expect(this.urlInterpSrv.getCartID()).toEqual(0087598);
你能试一下吗?您可以先执行函数,然后比较结果
it('should getCartID from url', function(){
$location.path('/?getCartID=0087598');
var cartId = this.urlInterpSrv.getCartID();
expect(cartId).toEqual(0087598);
});
相关文章:
- $location.search() - 如何在 $scope.$watch 函数中使用作用域中的参数
- $location.search() 与外部函数一起使用,重置整个$scope.如何避免它
- 使用 window.location.search 时,URL 中的字符会更改
- JavaScript window.location.search.substr(1)以空字符串形式返回
- Javascript - 获取 location.pathname + location.search - 不占用所有部
- 如果 JavaScript 错过了 Location.Search,则显示警报消息
- Jquery get window.location.search tag in array
- $location.search() 不起作用 - AngularJs 1.5
- 尝试将 href 属性和 location.search 结合起来
- AngularJS $location.search
- window.location.href or window.location.search
- Angular$location.search替换浏览器历史记录
- 如何在不更改$location.search中params值的情况下触发routeUpdate
- javascript使用location.search获取url不起作用
- 将location.pathname和location.search一起设置
- element.click和$location.search的棱角分明的怪异
- 如何在尝试替换$location.search时避免转义
- 为什么window.location.search是空的?
- 当我通过location.search搜索中文时,奇怪的字符
- $location.search在前面加上散列URL时为空