javascript - 如何使用 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 函数抛出错误?
解决方案
你可以使用chai-as-promised
您的代码将是这样的(未经测试):
return expect(myFunction()).be.rejectedWith(Error, 'You must pass in a parameter.');
推荐阅读
- kotlin - 如何确定 FlowCollector 是否关闭?
- java - 如何使用多个 yaml 文件生成 openAPI 代码
- javascript - 如何在发布我的自定义 vscode 扩展时修复“拒绝访问以执行此操作:查看资源的用户权限”
- javascript - 加速动画anime.js
- python - 使用 numpy 数组作为循环蒙特卡洛的测试用例
- python - 根据来的人数,你预计在披萨上花多少钱
- c# - Linq 查询返回 coumn 值空句柄
- higher-kinded-types - 更高种类的商业案例
- java - 对象[] arr = {1,2,[3,4,[5]],6}; 这是可能的吗
- signal-processing - CWT 幅度是什么意思?