Can you write async tests that expect toThrow?
Your guide to expect().rejects.toThrow()
in Jest for testing async exceptions. This handy method tests whether async functions fail with specific errors for concise and effective error handling.
Making sense of async error testing
Ensuring your asynchronous functions behave as intended when errors appear is crucial. The async/await
syntax is the key to properly executing the tests and handling outcome.
Wrap it up
The trick to capturing async errors is to wrap async calls in an arrow function or define an async function :
Eyes on the error
Make your tests robust: are they throwing just Errors or custom error classes:
And why settle for only the class? Go for the error message or instances:
Number of assertions to track
Enter expect.assertions(n)
where n
is how many assertions you expect in the test. So, no stealthy assertions go unnoticed.
No false positives
Ensure promises don't go to the resolve side causing false positives:
Testing multiple errors simultaneously
Why stop at one? Have multiple checks in a single test:
Don't forget using regular expression for a more flexible match:
Using .catch()
without async/await
Using promise with .catch()
? No problem, we got you:
Was this article helpful?