11

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);
});
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Darlesson
  • 5,742
  • 2
  • 21
  • 26

1 Answers1

25

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].

Brian Adams
  • 43,011
  • 9
  • 113
  • 111
  • 1
    (just an addition) `await expect(throwThis()).rejects.toEqual(expect.any(Error));` works too(I believe even for older `jest`) – skyboyer Feb 08 '19 at 10:30
  • Thank you! I'm using latest (24.1), so the first example worked. – Darlesson Feb 08 '19 at 17:41
  • @Darlesson you're welcome, glad to hear it was helpful! – Brian Adams Feb 09 '19 at 02:39
  • @skyboyer nice, that's really clean. As long as you don't need to check for any details about the `Error` that is a nice way to do it and I just verified that it works back to at least version 20.0.4. – Brian Adams Feb 09 '19 at 02:43
  • For some reason the first example always gave me a "correct" test. It never failed, even when it should. I opted for the second one and it worked. – Alexander Santos Dec 27 '21 at 21:54