Sub topic 12
Custom render helpers for providers
This chapter assumes you can write component tests with render, screen, and user-event. It also assumes you know React context, and that you have used a provider such as a router, a theme, a store, or a data-fetching client. You should also know how the wrapper option of render fits into a test file.
Why components need providers
Many components do not work alone. A component that calls useTheme() reads a value from a context provider higher in the tree. A component that renders a <Link> needs a router. A component that calls useQuery() needs a query client.
If you render such a component without its provider, one of two things happens. React throws an error, or the hook silently returns a default value that does not match production. Both make the test useless.
You could wrap the component by hand in every test:
render(
<ThemeProvider>
<MemoryRouter>
<Profile />
</MemoryRouter>
</ThemeProvider>
);This works, but it repeats the same setup in every test. When the provider list changes, you edit every test file. A custom render helper moves the setup to one place.
The wrapper option
render accepts a wrapper option. It is a component that receives children and returns them inside whatever providers you need. Testing Library renders your ui as the children of that component.
Here is a theme provider and a component that reads it:
// ThemeProvider.jsx
import { createContext, useContext } from 'react';
const ThemeContext = createContext('light');
export function ThemeProvider({ children, theme = 'light' }) {
return <ThemeContext.Provider value={theme}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
return useContext(ThemeContext);
}
// ThemedButton.jsx
import { useTheme } from './ThemeProvider';
export function ThemedButton({ children }) {
const theme = useTheme();
return <button className={`btn-${theme}`}>{children}</button>;
}ThemeProvider takes only children and has a default theme. It can therefore be passed directly as the wrapper:
// test-utils.jsx
import { render } from '@testing-library/react';
import { ThemeProvider } from './ThemeProvider';
export function renderWithTheme(ui, options) {
return render(ui, { wrapper: ThemeProvider, ...options });
}Spreading ...options last lets a test still pass its own render options, such as container. Note that a test-supplied wrapper would replace yours.
// ThemedButton.test.jsx
import { screen } from '@testing-library/react';
import { renderWithTheme } from './test-utils';
import { ThemedButton } from './ThemedButton';
test('uses the default light theme', () => {
renderWithTheme(<ThemedButton>Save</ThemedButton>);
expect(screen.getByRole('button', { name: 'Save' })).toHaveClass('btn-light');
});The test still uses screen from the library. The helper only changes how the component is mounted.
Passing options to the providers
A fixed wrapper cannot vary per test. If one test needs the dark theme and another needs a specific URL, make the helper take its own options. The helper builds a wrapper component that closes over those values.
// test-utils.jsx
import { render } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MemoryRouter } from 'react-router-dom';
import { ThemeProvider } from './ThemeProvider';
export function renderWithProviders(
ui,
{ theme = 'light', route = '/', ...renderOptions } = {}
) {
function Wrapper({ children }) {
return (
<MemoryRouter initialEntries={[route]}>
<ThemeProvider theme={theme}>{children}</ThemeProvider>
</MemoryRouter>
);
}
return {
user: userEvent.setup(),
...render(ui, { wrapper: Wrapper, ...renderOptions }),
};
}This helper does four things:
- It picks out the options that belong to your providers (
theme,route) and passes the rest torender. - It uses
MemoryRouterso that tests do not depend on the browser URL. - It defines
Wrapperinside the function. Each call gets its own wrapper with its own values. - It returns a
userobject created byuserEvent.setup()next to everythingrenderreturns. Tests then writeconst { user } = renderWithProviders(...).
A test using it:
import { screen } from '@testing-library/react';
import { renderWithProviders } from './test-utils';
import { ThemedButton } from './ThemedButton';
test('uses the dark theme when asked', () => {
renderWithProviders(<ThemedButton>Save</ThemedButton>, { theme: 'dark' });
expect(screen.getByRole('button', { name: 'Save' })).toHaveClass('btn-dark');
});Fresh state for every test
Some providers hold state: a Redux store, a query client, a mock service. If you create that state at module level, it is shared by every test in the file. One test then affects the next, and failures depend on test order.
Create the stateful object inside the helper, so each call gets a new one. A query client is the standard example. Retries are on by default, so a failed request retries with delays and the test seems to hang. Turn them off in tests.
// test-utils.jsx (query client version)
import { render } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
export function renderWithQueryClient(ui, options) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
function Wrapper({ children }) {
return <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>;
}
return { queryClient, ...render(ui, { wrapper: Wrapper, ...options }) };
}Returning queryClient lets a test inspect or clear the cache. The same pattern applies to a Redux store. Accept an optional preloadedState, build a new store from it inside the helper, and return the store.
Replacing the default render
Many projects re-export everything from Testing Library, so tests import from one file and never need to remember which render to use:
// test-utils.jsx
import { render } from '@testing-library/react';
import { AllProviders } from './AllProviders';
function customRender(ui, options) {
return render(ui, { wrapper: AllProviders, ...options });
}
export * from '@testing-library/react';
export { customRender as render };In ES modules, an explicit named export takes precedence over the same name from export *. Tests now write import { render, screen } from './test-utils'.
This convenience has a cost. It hides which providers a test uses, and every test pays for providers it may not need. If you prefer explicit code, keep a distinct name such as renderWithProviders. Importing the default render then still means "no providers", and the helper's name says what it adds.
Rerendering and wrappers
render returns a rerender function. It reuses the wrapper you passed to render, so you rerender only the ui:
const { rerender } = renderWithProviders(<ThemedButton>Save</ThemedButton>);
rerender(<ThemedButton>Save changes</ThemedButton>);If you wrapped the component by hand instead of using wrapper, you would need to wrap it again inside rerender. Otherwise the providers disappear and the component remounts without them. This is a good reason to prefer the wrapper option.
Wrappers for hooks
renderHook accepts the same wrapper option. Use it for hooks that read from context:
// useTheme.test.jsx
import { renderHook } from '@testing-library/react';
import { ThemeProvider, useTheme } from './ThemeProvider';
test('reads the theme from the provider', () => {
const wrapper = ({ children }) => (
<ThemeProvider theme="dark">{children}</ThemeProvider>
);
const { result } = renderHook(() => useTheme(), { wrapper });
expect(result.current).toBe('dark');
});Without a wrapper, the same hook returns the context default, 'light'. The test file uses the .jsx extension because it contains JSX.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Creating a store or query client at module level | State leaks between tests | Create it inside the helper |
| Leaving query retries on | Failing requests make tests slow or time out | Set `retry: false` in the test client |
| Wrapping `ui` by hand, then calling `rerender` | The rerendered tree has no providers | Use the `wrapper` option |
| Defining `Wrapper` outside the helper but reading test options | Options cannot reach the providers | Define `Wrapper` inside the helper as a closure |
| Adding every provider to every test | Slow tests, hidden dependencies | Provide only what the component needs |
| Putting the helper in a file the runner treats as a test | The runner reports a suite with no tests | Name it `test-utils.jsx`, not `*.test.jsx` |
Design guidelines
- Keep helpers thin. They set up the environment and should contain no assertions.
- Mirror production. Use the real provider where you can, and use a test-friendly variant such as
MemoryRouteronly where the real one needs a browser. - Do not mock a context to avoid a provider unless the test is about that boundary. A real provider keeps the test close to what users get.
- Return what tests will need, such as
user,store, orqueryClient. Do not return internal details of the wrapper. - Keep one helper for the common case and a second small one for unusual cases, rather than one helper with many flags.
Exercise
A test calls renderWithProviders(<Cart />), and the helper creates one QueryClient at the top of test-utils.jsx shared by all calls. The first test passes. The second test shows data cached by the first. What is the cause, and how do you fix it?
Show answer
The shared module-level QueryClient keeps its cache between tests, so the second test reads data the first one stored. Create the QueryClient inside the helper function, so each call gets a new client, and set retry: false in its default options. Return the client if tests need to inspect it.
Exercise
You wrote render(<Wrapper><Profile /></Wrapper>) and later call rerender(<Profile name="Ada" />). Why do the providers disappear, and what should you change?
Show answer
rerender only knows about the ui you pass it. Since you wrapped by hand, the new ui has no providers around it. Pass the providers through render(ui, { wrapper: Wrapper }) instead, because rerender reuses that wrapper.