首页 > 解决方案 > 如何使用 Chai 确保 Promise 抛出错误?

问题描述

目前,当我有一个引发错误的承诺时,为了测试是否引发了正确的错误,我正在做类似以下的事情。

let result, error;
try {
    result = await myFunction();
} catch (e) {
    error = e;
}

expect(result).to.not.exist;
expect(error).to.eql(new Error("You must pass in a parameter."));

然而,如果myFunction不是 promise 或 async 函数,我可以执行以下操作。

expect(() => myFunction()).to.throw(new Error("You must pass in a parameter."));

有没有更好的方法来检查在使用 Mocha/Chai 时是否为 promise/async 函数抛出错误?

标签: javascriptnode.jsmocha.jschai

解决方案


你可以使用chai-as-promised

您的代码将是这样的(未经测试):

return expect(myFunction()).be.rejectedWith(Error, 'You must pass in a parameter.');

推荐阅读