角度单位测试工厂.catch()

时间:2017-07-18 18:23:31

标签: angularjs unit-testing

我正在为一个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(){     var result;

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

1 个答案:

答案 0 :(得分:0)

我认为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;
  });
}
相关问题