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

Mocking Custom Hooks

Strategies for mocking your own custom hooks and controlling their return values in tests.

Mocking Custom Hooks

What you'll learn: How to mock your own custom hooks in tests and control what they return, just like you do with library hooks.

The Core Idea

Custom hooks are just functions that return values. When testing components that use your custom hooks, you often want to isolate the component's behavior from the hook's complex logic (like API calls, state management, or calculations). Mocking custom hooks lets you control their return values, making your tests predictable and focused.

How It Works

Use vi.mock() to intercept your custom hook module, then use vi.fn() to create controllable mock functions:

// MyComponent.tsx
import { useUserData } from './hooks/useUserData';

function MyComponent() {
  const { user, loading } = useUserData();
  if (loading) return <div>Loading...</div>;
  return <div>Welcome, {user.name}</div>;
}
// MyComponent.test.tsx
import { vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';

vi.mock('./hooks/useUserData');
import { useUserData } from './hooks/useUserData';

test('shows loading state', () => {
  vi.mocked(useUserData).mockReturnValue({
    user: null,
    loading: true
  });

  render(<MyComponent />);
  expect(screen.getByText('Loading...')).toBeInTheDocument();
});

test('shows user name when loaded', () => {
  vi.mocked(useUserData).mockReturnValue({
    user: { name: 'Alice' },
    loading: false
  });

  render(<MyComponent />);
  expect(screen.getByText('Welcome, Alice')).toBeInTheDocument();
});

The Strategy

  1. Mock the module containing your hook
  2. Import the hook after the mock declaration
  3. Use vi.mocked() to get TypeScript-safe access
  4. Call mockReturnValue() before each render to set what the hook returns

Key Takeaway: Mocking custom hooks is identical to mocking library hooks—mock the module path, then use mockReturnValue() to control what your component receives, letting you test all scenarios without running the hook's real logic.