javascript - 如何测试使用 chai 或 chai-as-promised 为异步函数抛出的错误?
问题描述
我有一个功能如下:
async foo() : Promise<Object> {
if(...) throw new Error
}
我应该如何测试是否引发了错误?目前我正在这样做:
it("testing for error thrown", async function () {
expect(async() => await foo()).to.throw(Error)
})
解决方案
你可以做这样的事情,如果抛出错误,测试将失败。
const foo = async (): Promise<Object> => {
// If you want the test to fail increase x to 11
const x = 0
if (x > 10) {
throw Error('Test will fail')
}
// Add meaningful code this is just an example
return { some: 'object' }
}
it('testing for error thrown', async () => {
const object = await foo()
expect(object).toEqual({ some: 'object' })
})
推荐阅读
- python - 如何在python中计算复杂的联立方程?
- firebase - 生成私钥 firebase admin sdk
- android - 片段的布局字段在初始化时为 NULL
- python - pandas 使用多索引进行条件更新
- javascript - 如何在 Javascript 或 Jquery 中处理具有多个循环的大量数组?
- javascript - 可以从 Web 应用程序获取客户端机器的 MAC 地址
- mysql - 使用 SQL 计算保留
- twitter4j - 如何获取推文总数(仅推文数)
- ios - 用于源文件路径的 podspec 参数是什么?
- jquery - 复选框未根据单选按钮值更改