Wrapping Components: Custom Render
You'll learn how to create a reusable custom render function that automatically wraps your components in providers, eliminating repetitive boilerplate in every test.
The Problem with Provider Hell
When testing components that depend on context providers (like React Router's BrowserRouter or a theme provider), you need to wrap them in those providers during every single test. This gets tedious fast:
render(
<BrowserRouter>
<ThemeProvider>
<MyComponent />
</ThemeProvider>
</BrowserRouter>
);
Writing this wrapper pyramid in 50 tests is exhausting and error-prone.
Creating Your Custom Render
The solution is creating a custom render function that wraps the standard RTL render with your common providers:
// test-utils.jsx
import { render } from '@testing-library/react';
import { BrowserRouter } from 'react-router-dom';
function customRender(ui, options) {
return render(ui, {
wrapper: ({ children }) => (
<BrowserRouter>
{children}
</BrowserRouter>
),
...options
});
}
export * from '@testing-library/react';
export { customRender as render };
Now import render from your custom test-utils file instead of RTL directly. Every component automatically gets wrapped in your providers without repeating the boilerplate.
Why the Re-export Pattern Matters
Notice we re-export everything from RTL (export * from '@testing-library/react') so you can still import screen, waitFor, etc. from the same place. This makes your test-utils file a drop-in replacement.
Key Takeaway: A custom render function with a wrapper option centralizes provider setup, making tests cleaner and ensuring consistent test environment configuration across your entire suite.