Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assert an async method throwing Error using toThrow with Jest

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);
});
like image 575
Darlesson Avatar asked Dec 11 '22 03:12

Darlesson


1 Answers

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

Note that toThrow was fixed for promises in PR 4884 and only works in 21.3.0+.

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


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

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

like image 119
Brian Adams Avatar answered Dec 12 '22 16:12

Brian Adams