角httpBackend美元.expectGET -响应409状态&自定义statusText

Angular $httpBackend.expectGET - respond with 409 status & custom statusText

本文关键字:状态 自定义 statusText 响应 httpBackend 美元 expectGET      更新时间:2023-09-26

尝试创建一个$httpBackend。在单元测试中使用expectGET返回状态409和自定义statusText 'TestPhrase'。

查看Angular文档(https://docs.angularjs.org/api/ngMock/service/$httpBackend),它给出了以下返回的示例:

{function([status,] data[, headers, statusText]) |Function (Function (method, url, data, headers)}

理解如何解释上面的例子有困难。

我当前的代码是:

      $httpBackend
        .expectGET('/example/url')
        .respond(function () {
          return ['409', ['TestPhrase'], {}];
        });

我要测试的代码是:

  $http.get('/example/url').then(function (response) {
      console.log('success, status ' + response.status);
      console.log('success, statusText ' + response.statusText);
  }, function(response) {
      console.log('error, status ' + response.status);
      console.log('error, statusText ' + response.statusText);
    }
  });
我从这个测试中接收到的控制台输出是:
'error, status 409'
'error, statusText '

期望输出:

'error, status 409'
'error, statusText TestPhrase'

文档说:

response - {function([status,] data[, headers, statusText]) | function(function(method, url, data, headers)} - response方法接受一组要返回的静态数据或一个函数,该函数可以返回一个数组,其中包含响应状态(数字)、响应数据(字符串)、响应头(对象)和状态(字符串)的文本。

你正在做第二个选择,传递一个返回数组的函数。以下是可行的方法。状态文本是第4项。(为了清晰起见,我包含了可选的函数参数。)

$httpBackend
.expectGET('/example/url')
.respond(function (method, url, data, headers) {
    return [409, 'response body', {}, 'TestPhrase'];
});