Course contentsShow
← React
Lesson 2101 of 2,39646. Testing React with RTLFree lesson

Testing Hooks with Context Dependencies

Wrapping renderHook with a custom wrapper to provide Context, Router, or other providers.

Testing Hooks with Context Dependencies

What You'll Learn

You'll learn how to test custom hooks that rely on React Context by wrapping renderHook with custom providers—the same pattern you used with component render.

The Problem: Hooks That Need Context

Many custom hooks read from Context (like useAuth, useTheme, or useRouter). When you try to test them in isolation with renderHook, they'll crash because the Context provider isn't present—just like components would.

The Solution: Custom Wrapper

The renderHook function accepts a wrapper option, just like the custom render function you've already built. This wrapper is a component that wraps the hook during testing, providing necessary Context:

const wrapper = ({ children }: { children: React.ReactNode }) => (
  <AuthContext.Provider value={{ user: mockUser, login: vi.fn() }}>
    {children}
  </AuthContext.Provider>
);

const { result } = renderHook(() => useAuth(), { wrapper });

expect(result.current.user).toEqual(mockUser);

Multiple Providers

When your hook needs multiple Contexts or Router, nest them in the wrapper:

const wrapper = ({ children }: { children: React.ReactNode }) => (
  <MemoryRouter>
    <AuthContext.Provider value={mockAuthValue}>
      <ThemeContext.Provider value={mockTheme}>
        {children}
      </ThemeContext.Provider>
    </AuthContext.Provider>
  </MemoryRouter>
);

const { result } = renderHook(() => useNavigateWithAuth(), { wrapper });

Testing Different Context Values

Create wrapper factories for different test scenarios:

const createWrapper = (authValue: AuthContextValue) => {
  return ({ children }: { children: React.ReactNode }) => (
    <AuthContext.Provider value={authValue}>
      {children}
    </AuthContext.Provider>
  );
};

const { result } = renderHook(() => useAuth(), { 
  wrapper: createWrapper({ user: null, login: vi.fn() }) 
});

Key Takeaway: Use the wrapper option in renderHook to provide Context, Router, or any other providers your hook depends on—enabling true isolation testing without integration complexity.