Testing Async Functions That Throw
You'll learn how to verify that async functions throw specific errors using await and assertion helpers.
The Core Challenge
When an async function throws an error, it doesn't behave like a synchronous throw—it returns a rejected promise. This means your test framework needs to await the error to catch it. Simply wrapping an async call in a regular exception assertion won't work because the promise rejection happens asynchronously.
The Solution Pattern
Most test frameworks provide specialized assertion helpers for async throws. The pattern looks like this:
// The async function we're testing
async function fetchUser(id) {
if (!id) {
throw new Error('User ID is required');
}
// ... fetch logic
}
// Testing that it throws
it('should throw when ID is missing', async () => {
await expect(fetchUser()).rejects.toThrow('User ID is required');
});
Notice the rejects matcher—this tells the assertion library to wait for the promise and check that it rejected with the expected error.
Alternative Approaches
You can also use try-catch with async/await:
it('should throw when ID is missing', async () => {
try {
await fetchUser();
throw new Error('Should have thrown');
} catch (error) {
expect(error.message).toBe('User ID is required');
}
});
This manual approach gives you finer control but requires the "fail guard" line to ensure the test fails if no error occurs.
Key Takeaway: Testing async functions that throw requires either specialized assertion matchers like rejects.toThrow() or manual try-catch blocks with await, because async errors become promise rejections that must be explicitly awaited and handled.