How to write async tests that expect toThrow with Jest?

Sometimes, we want to write async tests that expect toThrow with Jest.

In this article, we’ll look at how to write async tests that expect toThrow with Jest.

How to write async tests that expect toThrow with Jest?

To write async tests that expect toThrow with Jest, we can put await before expect and call toThrow.

For instance, we write

it('should test async errors', async () => {
  await expect(failingAsyncTest())
    .rejects
    .toThrow('I should fail');
});

to call failingAsyncTest in the test function.

We use await and rejects to get the rejected value if any and call thThrow to check what error message is given with the promise rejection.

Conclusion

To write async tests that expect toThrow with Jest, we can put await before expect and call toThrow.