13

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

1 Answer 1

27

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

5
  • 1
    (just an addition) await expect(throwThis()).rejects.toEqual(expect.any(Error)); works too(I believe even for older jest)
    – skyboyer
    Commented Feb 8, 2019 at 10:30
  • Thank you! I'm using latest (24.1), so the first example worked.
    – Darlesson
    Commented Feb 8, 2019 at 17:41
  • @Darlesson you're welcome, glad to hear it was helpful! Commented Feb 9, 2019 at 2: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. Commented Feb 9, 2019 at 2: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. Commented Dec 27, 2021 at 21:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.