【发布时间】: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
【问题讨论】: