$http 是否对 params 对象进行排序?

Does $http sort the params object?

我正在为我的 angularjs 应用编写一些单元测试。对于测试,我使用内部 $httpBackend 模拟 $http 请求。

在测试期间我使用了 $httpBackend.expectGET,因为我想要我的应用程序请求的确切行为。

例如我有一个参数对象:

parameters = {
        name : 'Monkey',
        crazy : false,
        desc : 'Nobody',
      };

我的应用程序中的 Http-Get 请求是:

return $http.get(this.uri + '/' + id, {params : parameters});

在我的单元测试中,我期望这样:

$httpBackend.expectGET(instance.uri + '/' + returnValues.id + '?' + query).respond(200, object);

"query"只是用'='和'&'连接的对象的元素。 所以我 期望 URL:

 www.example.com/api/v1/object/1?name=Monkey&crazy=false&desc=Nobody

但是我得到了这个:

www.example.com/api/v1/object/1?crazy=false&desc=Nobody&name=Monkey

$http 是否根据 "params" 对象中的键进行排序?

是的,$http 在将参数发送到服务器之前根据 source code

对参数进行排序
forEachSorted(params, function(value, key) {
    ...
});

因此您的测试应该期望有序的键,或者您可以通过将其发送到 $http 提供商来编写您自己的 paramSerializer:

paramSerializer - {string|function(Object):string} - A function used to prepare string representation of request parameters (specified as an object). Is specified as string, it is interpreted as function registered in with the {$injector}.