为抛出错误的异步函数编写Jest测试失败

时间:2019-11-29 17:53:20

标签: promise jestjs

我正在尝试测试一个会异步引发错误的函数,但是开玩笑没有抓住它

    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 |     };

1 个答案:

答案 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');