gpt4 book ai didi

javascript - 测试 Promise 链以 .catch 结尾(按 promise 使用 Mocha/Chai)

转载 作者:行者123 更新时间:2023-11-28 06:17:44 24 4
gpt4 key购买 nike

我看过很多有关测试 Promise 拒绝的信息,但想知道是否有人知道如何编写一个测试,如果 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

我正在使用 Mocha 和柴作为 promise 。我没有使用任何 Promise 库,只是使用原生 es2015。

最佳答案

您需要返回 promise 并测试它是否被 chai-as-promised 拒绝

应该风格:

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

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

返回很重要

关于javascript - 测试 Promise 链以 .catch 结尾(按 promise 使用 Mocha/Chai),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35810531/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com