Triggering Errors with Throwing Components
What you'll learn: How to create test components that throw errors on demand to verify error boundary behavior.
In the previous lesson, you learned to silence expected console errors. Now you need to actually trigger those errors in a controlled way. The technique is simple: create a component specifically for testing that throws an error when a certain condition is met.
The Core Technique
You'll define a component inside your test file that throws an error conditionally. This lets you control exactly when the error occurs—simulating real runtime failures without breaking your actual application components.
Here's the pattern:
function ThrowError({ shouldThrow }) {
if (shouldThrow) {
throw new Error('Test error');
}
return <div>Everything is fine</div>;
}
test('error boundary catches thrown errors', () => {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
render(
<ErrorBoundary fallback={<div>Something went wrong</div>}>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
consoleError.mockRestore();
});
Why This Works
Your ThrowError component acts like a controlled explosion. By passing shouldThrow={true}, you simulate what happens when a real component encounters a critical error—maybe a null reference or failed data transformation. The error boundary catches it just like it would in production.
Think of it like a fire drill: you're not setting your building on fire, but you're simulating the emergency to verify your safety systems work.
Combining Both Techniques
Notice how this pairs with the console mock from the previous lesson—you silence React's error logging while proving your boundary actually catches and handles the error through its rendered fallback UI.
Key Takeaway: Create simple throwing components in your tests to safely trigger errors and verify error boundaries catch them without polluting console output or breaking your test suite.