测试承诺链以 .catch 结尾(按照承诺使用 Mocha / Chai)

Test Promise chain ends in .catch (using Mocha / Chai as promised)

本文关键字:承诺 Mocha Chai catch 结尾 测试      更新时间:2023-09-26

我已经看到了很多关于测试 Promise 拒绝的信息,但想知道是否有人知道如何编写一个如果承诺链不以".catch"结尾就会失败的测试?我正在尝试防止吞咽错误。

例如,这将通过测试:

doSomething()                            // returns a Promise
.then(doSomethingElse)                   // returns a Promise
.then(handleResult)
.catch((err) => { console.log(err); });  // logs errors from any rejections

这将失败:

doSomething()                            // returns a Promise
.then(doSomethingElse)                   // returns a Promise
.then(handleResult);                     // no catch = swallowed errors

我正在使用摩卡和柴如承诺的那样。我没有使用任何承诺库,只是原生 es2015。

您需要返回承诺并测试它被拒绝

在应该的风格:

return doSomething()                            
.then(doSomethingElse)                   
.then(handleResult).should.be.rejectedWith(Error);  

return doSomething()                            
.then(doSomethingElse)                   
.then(handleResult).should.be.rejected; 

return很重要