Categories
JavaScript Answers

How to write async tests that expect toThrow with Jest?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *