如何使$ httpBackend对URL查询参数的顺序不敏感? [英] How can I make $httpBackend insensitive to the order of URL query parameters?
问题描述
我正在使用Angular.js $httpBackend
测试一些包装$http
调用的服务(这是在ngMock中,而不是 ngMockE2E中).
I am using the Angular.js $httpBackend
to test some services that wrap $http
calls (this is in ngMock, not ngMockE2E).
似乎expect
和when
之类的东西对URL查询参数的顺序敏感.例如.如果我执行$httpBackend.when('POST','/apiCall?X=1&Y=2').respond(/* ... */)
或$httpBackend.expectPOST('/apiCall?X=1&Y=2')
,如果URL中包含 Y = 2& X = 1 而不是 X = 1& Y = 2 ,则会收到URL不匹配的情况>.
It seems that things like expect
and when
are sensitive to the order of URL query parameters. E.g. if I do $httpBackend.when('POST','/apiCall?X=1&Y=2').respond(/* ... */)
or $httpBackend.expectPOST('/apiCall?X=1&Y=2')
, I get URL mismatches if I have Y=2&X=1 in the URL instead of X=1&Y=2.
我想以这样的方式编写测试:被测试的服务可以自由更改URL查询字符串参数的顺序,而不会破坏测试.我无法在$ httpBackend文档中找到任何解决方法.正确的方法是什么?
I want to write my tests in such a way that the service being tested will be free to change the order of URL query string parameters without breaking the tests. I haven't been able to find anything to solve this in the $httpBackend documentation. What's the right way to do this?
推荐答案
angular将对与$ http结合使用的params
对象的键进行排序.
angular will sort the keys of the params
object used in conjunction with $http.
$http({
url:"/myurl",
method:"GET",
params:{
Y:1
X:2
}});
Angular将有效地执行以下操作:Object.keys(myParams).sort()
并按此顺序附加键.
最终是'/myurl?X=2&Y=1'
Angular will do the following effectively: Object.keys(myParams).sort()
and append the keys in that order.
which ends up being '/myurl?X=2&Y=1'
我建议不要在URL中直接使用查询参数,而要在角度params:
中使用该参数,然后角度将进行处理.
I would suggest consistently using query parameters not directly in the url, but instead in the parameter params:
that angular will then process.
另一种解决方案是在测试中使用正则表达式,例如
Another solution would be to use Regular Expressions in your tests, something like
$httpBackend.expectPOST(/\/myurl\?((X|Y)=\d{1,}&?){2}/)
自从文档重新设计以来,您很难使用RegExp,因为颜色不会混合.
The fact that you can use RegExp's is really hard to spot since the documentation redesign, as the colors do not blend.
这篇关于如何使$ httpBackend对URL查询参数的顺序不敏感?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!