Testing a component that consumes React Context
Knowing context needs a Provider in tests.
Render inside the Context.Provider with a value, or omit it to exercise the default; use a custom render wrapper for reuse.
WHAT THIS TESTS Your understanding that a context consumer is only as testable as the value it receives, and that React Testing Library lets you inject that value through a wrapper rather than mocking React internals.
A GOOD ANSWER COVERS A component calling useContext reads whatever the nearest matching Provider supplies, or the default passed to createContext if there is none. So to test a specific state you render the component inside MyContext.Provider value=... with the value you want, and to test the default state you render it with no Provider at all, exercising the fallback. With React Testing Library you pass a wrapper option to render, or better, define a custom render that wires up the Provider once so every test reuses it. This keeps tests behavioral: you set the value, render, then assert on the visible output rather than on internal hooks.
COMMON WRONG ANSWERS Mocking useContext or the whole react module, which couples tests to implementation. Forgetting the Provider and being surprised by undefined when no default was supplied. Asserting on context internals instead of rendered output. Re-wrapping in every test instead of a shared helper.
LIKELY FOLLOW-UPS How would you test a component that also dispatches into context? How do you reset between tests? When is mocking the context module justified? How does the custom render wrapper option work?
ONE CONCRETE EXAMPLE Given a ThemeContext, you write test('uses provided theme', () => render(<ThemeContext.Provider value={{ mode: 'dark' }}><Toolbar /></ThemeContext.Provider>)) and assert the toolbar shows dark styling. Then test('falls back to default', () => render(<Toolbar />)) with createContext({ mode: 'light' }) supplying the default, asserting light styling. To stay DRY you extract function renderWithTheme(ui, value) { return render(ui, { wrapper: ({children}) => <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider> }) } and reuse it across the suite.
Read the original → testing-library.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.