Testing Components That Use Context + Reducer
You'll learn how to test components that depend on context and reducers by creating custom render wrappers and testing reducer logic separately.
Why Testing Context + Reducer is Different
When your component reads from context created by useReducer, your tests can't just render the component in isolation—it needs the provider wrapping it. Think of it like testing a phone: you can't test the phone app without also providing the cellular network it depends on.
Custom Render Wrapper Pattern
Create a test helper that wraps your component with the necessary provider:
function renderWithContext(ui, { initialState = defaultState } = {}) {
const wrapper = ({ children }) => (
<MyStateContext.Provider value={initialState}>
<MyDispatchContext.Provider value={mockDispatch}>
{children}
</MyDispatchContext.Provider>
</MyStateContext.Provider>
);
return render(ui, { wrapper });
}
test('displays user count from context', () => {
renderWithContext(<UserList />, {
initialState: { users: [{ id: 1, name: 'Alice' }] }
});
expect(screen.getByText(/1 user/i)).toBeInTheDocument();
});
Testing Reducer Logic in Isolation
Your reducer is just a pure function—test it directly without React at all:
test('ADD_USER action adds user to state', () => {
const state = { users: [] };
const action = { type: 'ADD_USER', payload: { id: 1, name: 'Bob' } };
const newState = userReducer(state, action);
expect(newState.users).toHaveLength(1);
expect(newState.users[0].name).toBe('Bob');
});
This separation keeps tests fast and focused: reducer tests verify state logic, component tests verify UI behavior.
Key Takeaway: Use custom render wrappers to provide context in component tests, and test reducer functions directly as pure functions for complete coverage.