Course contentsShow
← React
Lesson 2133 of 2,39647. Testing Patterns and Best PracticesFree lesson

Mocking Custom Hooks: When It's Justified

Learn rare cases where mocking your own custom hooks makes sense, like complex data-fetching logic.

Mocking Custom Hooks: When It's Justified

You'll learn when mocking your own custom hooks makes sense, despite the general rule against mocking internal code.

The Rare Exception

We just learned not to mock React's built-in hooks like useState. But what about your own custom hooks? The rule is still "avoid mocking internal code," but there's a narrow exception: when a custom hook contains complex, expensive, or difficult-to-reproduce logic that's orthogonal to what you're testing.

When It's Justified

Think of it like testing a car's dashboard. If the speedometer depends on a custom useEngineData() hook that reads sensor telemetry, and you're testing whether the dashboard displays the speed correctly, you don't need the entire engine running. You just need predictable data.

Common justified scenarios:

  • Complex data-fetching hooks with intricate retry logic, authentication, or caching
  • WebSocket or real-time connection hooks that are hard to simulate
  • Geolocation or browser API hooks that require special permissions
  • Heavy computation hooks that slow down your test suite

The key criterion: Is this hook testing a different concern than my component?

The Test

import { vi } from 'vitest';
import { render, screen } from '@testing-library/react';

vi.mock('../hooks/useComplexDataFetch', () => ({
  useComplexDataFetch: vi.fn(() => ({
    data: { name: 'Test User' },
    loading: false,
    error: null
  }))
}));

test('displays user name from complex hook', () => {
  render(<UserProfile userId={123} />);
  expect(screen.getByText('Test User')).toBeInTheDocument();
});

You're testing the component's rendering logic, not the hook's fetching logic. The hook should have its own isolated tests with renderHook.

Key Takeaway: Mock your custom hooks only when they handle concerns separate from what you're testing—like complex data fetching—and always test those hooks independently.