Testing Error Boundary Behavior
You'll learn how to write tests that intentionally trigger errors in components to verify your Error Boundaries catch them and render the correct fallback UI.
Why Test Error Boundaries?
You've built Error Boundaries to catch component failures gracefully. But how do you know they actually work? Testing verifies that when a component throws an error, your boundary catches it, displays the fallback UI, and logs appropriately—before users encounter broken screens in production.
Think of it like testing a safety net: you need to deliberately drop something to confirm it catches properly.
Simulating Component Errors
To test Error Boundaries, you need a component that throws an error on demand. Create a test component that throws when it receives a specific prop:
// Test helper component
function BrokenComponent({ shouldThrow }) {
if (shouldThrow) {
throw new Error('Test error');
}
return <div>Working</div>;
}
Then wrap it in your Error Boundary and test both states:
// Normal rendering (no error)
render(
<ErrorBoundary fallback={<div>Error occurred</div>}>
<BrokenComponent shouldThrow={false} />
</ErrorBoundary>
);
// Verify normal content appears
// Error state
render(
<ErrorBoundary fallback={<div>Error occurred</div>}>
<BrokenComponent shouldThrow={true} />
</ErrorBoundary>
);
// Verify fallback UI appears instead
What to Verify
Your tests should confirm:
- Fallback UI renders when an error occurs
- Normal content is hidden after error
- Error logging functions are called with correct error objects
- Reset mechanisms work if implemented
Key Takeaway: Test Error Boundaries by creating components that throw on command, then asserting that fallback UI appears and error handling logic executes correctly—proving your safety net catches failures before users see them.