-1

In jest, If I run the following code:

    await expect(async () => {
      const asyncFunc = async () => {
        return Promise.reject(new Error('Foo'))
      };
      await asyncFunc();
    }).toThrow();

I would expect this pass as the promise rejects with an error, but this passes. Is there a way to assert the async function throws a the error?

therealcobb
  • 147
  • 7

2 Answers2

2

An async function does not throw an exception. It always returns a promise, which might get rejected.

So you'll need to test that promise:

const asyncFunc = async () => {
  return Promise.reject(new Error('Foo'))
};
await expect(asyncFunc()).rejects.toEqual('Foo');

See also How do I properly test for a rejected promise using Jest? and Best Way to Test Promises in Jest.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

I think you want .rejects.

await expect(asyncFunc()).rejects.toThrow();

Note that the test needs to be async as well.

TrueWill
  • 25,132
  • 10
  • 101
  • 150