如何使用 toThrow 和 Jest 断言抛出错误的异步方法

Dar*_*son 2 javascript testing jestjs

我见过这个问题,它希望 aPromise起作用。在我的情况下Error,在 a 之前和之外抛出Promise

在这种情况下如何断言错误?我已经尝试了以下选项。

test('Method should throw Error', async () => {

    let throwThis = async () => {
        throw new Error();
    };

    await expect(throwThis).toThrow(Error);
    await expect(throwThis).rejects.toThrow(Error);
});
Run Code Online (Sandbox Code Playgroud)

Bri*_*ams 9

调用throwThis返回一个Promise应该拒绝的Error所以语法应该是:

test('Method should throw Error', async () => {

  let throwThis = async () => {
    throw new Error();
  };

  await expect(throwThis()).rejects.toThrow(Error);  // SUCCESS
});
Run Code Online (Sandbox Code Playgroud)

请注意,toThrow已针对PR 4884 中的承诺进行了修复并且仅适用于 21.3.0+

所以这只会起作用在您使用Jest22.0.0 或更高版本时才有效。


如果您使用的是早期版本,则Jest可以传递spycatch

test('Method should throw Error', async () => {

  let throwThis = async () => {
    throw new Error();
  };

  const spy = jest.fn();
  await throwThis().catch(spy);
  expect(spy).toHaveBeenCalled();  // SUCCESS
});
Run Code Online (Sandbox Code Playgroud)

...并可选择通过检查来检查Error抛出spy.mock.calls[0][0]