如何使用带有Jest的toThrow断言引发Error的异步方法

如何使用带有Jest的toThrow断言引发Error的异步方法

问题描述:

我看过这个问题,期望得到一个Promise上班.在我的情况下,Error抛出在Promise之前和之外.

I have seen this question which expects a Promise to work. In my case the Error is thrown before and outside a Promise.

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

How can I assert the error in this case? I have tried the options below.

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

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

    await expect(throwThis).toThrow(Error);
    await expect(throwThis).rejects.toThrow(Error);
});

调用throwThis会返回Promise,应以Error拒绝,因此语法应为:

Calling throwThis returns a Promise that should reject with an Error so the syntax should be:

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

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

  await expect(throwThis()).rejects.toThrow(Error);  // SUCCESS
});

请注意,toThrow PR 4884 仅适用于21.3.0+ .

因此,这仅在您使用Jest 22.0.0或更高版本时有效.

So this will only work if you are using Jest version 22.0.0 or higher.

如果使用的是早期版本的Jest,则可以将spy传递给catch:

If you are using an earlier version of Jest you can pass a spy to catch:

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

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

  const spy = jest.fn();
  await throwThis().catch(spy);
  expect(spy).toHaveBeenCalled();  // SUCCESS
});

...并通过检查Error抛出的 > .

...and optionally check the Error thrown by checking spy.mock.calls[0][0].