Chai-As-Promised:当 promise 抛出错误时处理错误

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

我有以下代码需要测试:

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,grunt-mocha 会正常退出。有没有更好的方法来测试这种情况?

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