我正在尝试测试一个会异步引发错误的函数,但是开玩笑没有抓住它
async function fn() {
await new Promise(async (res, rej) => {
await new Promise(res => setTimeout(res, 1000))
throw new Error('some error')
})
};
await expect(fn()).rejects.toThrowError('some error');
开玩笑的错误
● execSeries › throws error and terminates early if a command errors
some error
68 | await new Promise(async (res, rej) => {
69 | await new Promise(res => setTimeout(res, 1000))
> 70 | throw new Error('some error')
| ^
71 | })
72 | };
答案 0 :(得分:0)
我不知道如何使它与throw
语法一起使用,但是如果我更改它以拒绝诺言,它将起作用...
async function fn() {
await new Promise(async (res, rej) => {
await new Promise(res => setTimeout(res, 1000))
rej('some error')
})
};
await expect(fn()).rejects.toThrowError('some error');
缺点是,如果子函数内部存在throw,除非我将其顶住并重新抛出
async function fn() {
await new Promise(async (res, rej) => {
try {
await somethingThatThrowsError;
} catch (e) {
rej(e)
}
})
};
await expect(fn()).rejects.toThrowError('some error');