【问题标题】:Angular Unit Test Factory .catch()Angular 单元测试工厂 .catch()
【发布时间】:2017-07-18 18:23:30
【问题描述】:

我正在对工厂进行单元测试以获取 400 响应,但我不明白为什么测试用例中的 .catch() 响应未定义。当 promise 与 .catch() 链接时,测试失败,因为响应未定义,但如果使用 .then() 则成功。为什么这个 $q.reject() 响应没有传递给 .catch() 函数?我看到工厂中的 .catch() 块正在接收 $.reject() 但是当在单元测试中返回响应时 .catch 是未定义的。

工厂

function resetTempPassword(data) {
  return $http.post('/reset_temp_password', data)
  .then(function(response) {
    console.log('inside then');
    console.log(response);
    return response;
  })
  .catch(function(response) {
    console.log('inside catch');
    console.log(response);
    return response;
  });
}

测试

describe('resetTempPassword()', function() { 变量结果;

beforeEach(function() {
  // init local result
  result = {};
  ...

it('should return 400 when called with invalid temp password', function() {
  $httpBackend.expectPOST('/reset_temp_password', RESET_TEMP_INVALID).respond(400, RESET_TEMP_ERROR);
  $httpBackend.whenPOST(API, RESET_TEMP_INVALID).respond(400, $q.reject(RESET_TEMP_ERROR));

  expect(idmAdminFactory.resetTempPassword).not.toHaveBeenCalled();
  expect(result).toEqual({});

  idmAdminFactory.resetTempPassword(RESET_TEMP_INVALID)
  .catch(function(response) {
    result = response;
  });
  // flush pending HTTP requests
  $httpBackend.flush();

  expect(idmAdminFactory.resetTempPassword).toHaveBeenCalledWith(RESET_TEMP_INVALID);
  expect(result.data.code).toEqual(40008); // result.data is undefined

【问题讨论】:

    标签: angularjs unit-testing


    【解决方案1】:

    我不认为 catch 是标准 $http 对象的一部分。然后可以有第二个函数参数,当 $http 调用失败时调用该参数。我认为这就是你应该在这里使用的:

    function resetTempPassword(data) {
      return $http.post('/reset_temp_password', data)
      .then(function(response) {
        console.log('inside then');
        console.log(response);
        return response;
      },
      function(response) {
        console.log('inside catch');
        console.log(response);
        return response;
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-07-06
      • 1970-01-01
      • 2011-08-03
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 1970-01-01
      相关资源
      最近更新 更多