Chai正如承诺:当承诺抛出错误时,处理错误

Chai-As-Promised: Handle errors when promise throws error

本文关键字:承诺 错误 处理 出错 Chai      更新时间:2023-09-26

我有以下代码需要测试:

function A(param){
  // Process param
  return B(param)
     .catch(function(err){
      //Process err
      throw new customError(err); // throw a custom Error
     })
     .then(function(response){
       // Handle response and return
       return {status: 'Success'}
     })
}

为了测试它,我使用了以下片段:

return expect(A(param))
             .to.eventually.have.property('status', 'Success');

当代码没有在函数A或B中中断时,这很好,但当它中断时,测试用例失败,grunt-mocha无法退出,我认为这是因为它仍在等待A解决。

如果我在catch块中添加return语句而不是throw,那么咕哝的摩卡就可以退出了。有没有更好的方法来测试这种情况?

Catch的目的是捕获并更正任何错误,而不是重新抛出它们。因此,返回错误或被拒绝的承诺是处理此问题的正确方法。