Testing Error States in Async Components
You'll learn how to verify that your component displays appropriate error messages when asynchronous operations fail.
The Core Idea
Just as you test happy paths where data loads successfully, you need to test what happens when network requests fail. This involves mocking a failed request (using MSW), waiting for the error UI to appear, and verifying the error message is displayed correctly. The key is using findBy queries that automatically wait for the error state to resolve, since the error appears asynchronously after the failed request completes.
Simulating Failure
With MSW, you can configure handlers to return error responses for specific tests:
// In your test
server.use(
http.get('/api/users', () => {
return HttpResponse.json(
{ message: 'Failed to fetch users' },
{ status: 500 }
)
})
)
Waiting for Error UI
After triggering the failed request, use findBy to wait for the error message:
const errorMessage = await screen.findByText(/failed to fetch users/i)
expect(errorMessage).toBeInTheDocument()
The findBy query automatically waits (up to a default timeout) for the element to appear, handling the asynchronous nature of the error state update.
Complete Example
test('displays error message when fetch fails', async () => {
server.use(
http.get('/api/users', () => {
return HttpResponse.json(
{ error: 'Server error' },
{ status: 500 }
)
})
)
render(<UserList />)
const errorMsg = await screen.findByText(/server error/i)
expect(errorMsg).toBeInTheDocument()
})
Key Takeaway: Test error states by mocking failed requests with MSW, use findBy to wait for error UI to appear asynchronously, and verify the error message displays correctly—ensuring users see helpful feedback when things go wrong.