Error State Testing
Problem
Components only get tested with happy-path data, so error states, loading failures, and edge cases crash in production. Network errors show blank screens, validation failures break forms, and null data causes uncaught exceptions because these scenarios were never tested.
Solution
Simulate error conditions in tests to verify components handle failures gracefully. This ensures error states are implemented and displayed correctly before users encounter them in production.
Example
This example demonstrates testing a component’s error state by mocking a failed fetch request and verifying the error message is displayed.
test('shows error when fetch fails', async () => {
// Mock fetch to simulate a network error
fetch.mockRejectedValue(new Error('Network error'));
// Render component that will attempt to fetch data
render(<UserProfile userId="123" />);
// Verify error message is shown to the user
expect(await screen.findByText(/failed to load/i)).toBeInTheDocument();
});
Benefits
- Ensures error handling code is actually implemented and works.
- Catches missing error states before users encounter them.
- Verifies error messages are helpful and actionable.
- Tests edge cases that are hard to reproduce manually.
- Increases confidence that failures won’t crash the application.
Tradeoffs
- Requires mocking or simulating error conditions which adds complexity.
- May not perfectly replicate real error scenarios.
- Can give false confidence if mocks don’t match reality.
- Takes time to write tests for various error scenarios.
- Requires creativity to think through all possible failure modes.