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

Vitest's vi.mock() Basics

Using vi.mock() to replace entire modules with test doubles before imports are resolved.

Vitest's vi.mock() Basics

You'll learn how to replace entire modules with test doubles before they're imported, giving you control over external dependencies.

The Core Idea

When your React component imports an external module—like an API client, a complex library, or even another component—you often don't want the real version running during tests. vi.mock() lets you intercept the import statement itself and substitute a fake module before your test code even runs.

Think of it like swapping out ingredients before cooking: you call vi.mock() at the top of your test file, and when your component tries to import that module, Vitest secretly hands it your test double instead.

The Basic Pattern

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

// Replace the entire module BEFORE imports resolve
vi.mock('./api/client');

test('component uses mocked API', () => {
  render(<MyComponent />);
  // Now MyComponent's import of './api/client' got the mock, not the real thing
});

Why It Happens Before Imports

JavaScript modules are resolved at parse time, not runtime. By the time your component's code executes, imports are already locked in. vi.mock() hooks into Vitest's module system to intercept this process—it must be called before the module you're testing imports the dependency.

This is powerful for isolating components from external systems like databases, network requests, or heavy computations you want to simulate.

Key Takeaway: vi.mock('module-path') replaces an entire module with automatic mocks before any imports resolve, letting you control external dependencies without touching your component's code.