日本語

Using Vitest’s vi.mock in React Tests

​​React​React Testing Library,TypeScript,Vitest

With Vitest's vi.mock, you can replace a module that a component imports with a mock (a fake version) for the duration of a test. Typical uses include replacing a function that calls an API with a mock so you can check the UI without a server, fixing the date that a function returns, and removing a chart component that draws on a canvas, which does not work in jsdom.

I replaced these three in turn and checked the errors you are likely to hit and how to fix them.

Note

I tested on Ubuntu 24.04 with Node.js 22.23.4. The versions were vitest 5.1.0, jsdom 31.0.0, @testing-library/react 16.3.3, @testing-library/jest-dom 7.0.1, react and react-dom 19.3.1, and typescript 7.0.2. In the Vitest config I set environment: 'jsdom', and the setup file loads @testing-library/jest-dom/vitest. I did not try replacing modules with __mocks__ folders, Vitest's browser mode, or Jest.

Replacing an API-calling function with a factory

The component under test takes a user's name from an API and displays it.

ts
// src/api.ts
export type User = { id: number; name: string };

export async function fetchUser(id: number): Promise<User> {
  const res = await fetch(`https://api.example.com/users/${id}`);
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
  return res.json();
}
tsx
// src/UserCard.tsx
import { useEffect, useState } from 'react';
import { fetchUser, type User } from './api';

export function UserCard({ id }: { id: number }) {
  const [user, setUser] = useState<User | null>(null);
  const [error, setError] = useState(false);

  useEffect(() => {
    fetchUser(id).then(setUser, () => setError(true));
  }, [id]);

  if (error) return <p role="alert">読み込めませんでした</p>;
  if (!user) return <p>読み込み中…</p>;
  return <p>こんにちは、{user.name}さん</p>;
}

In the test, you pass a function (a factory) as the second argument to vi.mock. The factory returns the replacement module. Here, fetchUser is set to vi.fn(), and each test sets its return value through vi.mocked(). vi.mocked tells TypeScript that the value is a mock. It returns the value it receives unchanged.

tsx
// src/UserCard.test.tsx
import { render, screen } from '@testing-library/react';
import { expect, test, vi } from 'vitest';
import { fetchUser } from './api';
import { UserCard } from './UserCard';

vi.mock('./api', () => ({
  fetchUser: vi.fn(),
}));

test('名前を表示する', async () => {
  vi.mocked(fetchUser).mockResolvedValue({ id: 1, name: 'たま' });
  render(<UserCard id={1} />);
  expect(await screen.findByText('こんにちは、たまさん')).toBeInTheDocument();
  expect(fetchUser).toHaveBeenCalledWith(1);
});

test('失敗したらエラーを表示する', async () => {
  vi.mocked(fetchUser).mockRejectedValue(new Error('HTTP 500'));
  render(<UserCard id={2} />);
  expect(await screen.findByRole('alert')).toHaveTextContent('読み込めませんでした');
});

Both tests passed. The vi.mock call is written below the imports, but ./api, which UserCard loads, is still replaced by the mock.

Using an outer variable in the factory causes a ReferenceError

You may want to store the mock in a variable and use it inside the factory.

tsx
const fetchUserMock = vi.fn();

vi.mock('./api', () => ({
  fetchUser: fetchUserMock,
}));

With this code, the whole file failed before any test ran.

text
 FAIL  src/pitfall-outer-var.test.tsx [ src/pitfall-outer-var.test.tsx ]
Error: [vitest] There was an error when mocking a module. If you are using "vi.mock" factory, make sure there are no top level variables inside, since this call is hoisted to top of the file. Read more: https://vitest.dev/api/vi.html#vi-mock
Caused by: ReferenceError: Cannot access 'fetchUserMock' before initialization

As the vi.mock documentation explains, vi.mock is moved to the top of the file and runs before any import. So the factory runs when UserCard loads ./api, and the const fetchUserMock line has not run yet.

To use an outer variable, create it inside vi.hoisted. vi.hoisted is also moved to the top of the file, so the factory can use the variable.

tsx
const { fetchUserMock } = vi.hoisted(() => ({
  fetchUserMock: vi.fn(),
}));

vi.mock('./api', () => ({
  fetchUser: fetchUserMock,
}));

test('vi.hoisted で作ったモックを使う', async () => {
  fetchUserMock.mockResolvedValue({ id: 1, name: 'たま' });
  render(<UserCard id={1} />);
  expect(await screen.findByText('こんにちは、たまさん')).toBeInTheDocument();
  expect(fetchUserMock).toHaveBeenCalledWith(1);
});

This test passed. To confirm the execution order, I added console.log calls inside vi.hoisted, inside the factory, below the imports, and inside the test. The output appeared in this order: vi.hoisted, the factory, the line below the imports, and then the test.

The order the test file is written and the order it actually runs. Even if you write import, vi.hoisted, vi.mock, then test, the code actually runs in this order: the contents of vi.hoisted, loading the imports (where the vi.mock factory runs), the body of the file, then the contents of test. A plain const is created in the file body, so the factory cannot use it.
The order the test file is written and the order it actually runs

Replacing only today's date and using the real other functions

Next, I fix only today(), which returns today's date, from a date module. formatDate(), which formats dates, stays real.

ts
// src/date.ts
export function today(): Date {
  return new Date();
}

export function formatDate(d: Date): string {
  return `${d.getFullYear()}年${d.getMonth() + 1}月${d.getDate()}日`;
}

// Calls today() within the same file
export function todayLabel(): string {
  return `今日は${formatDate(today())}です`;
}
tsx
// src/TodayBanner.tsx
import { formatDate, today } from './date';

export function TodayBanner() {
  return <p>今日は{formatDate(today())}です</p>;
}

When the factory returned only today, the test failed as soon as it called formatDate. This is because the factory's return value becomes the entire module.

text
Error: [vitest] No "formatDate" export is defined on the "./date" mock. Did you forget to return it from "vi.mock"?
If you need to partially mock a module, you can use "importOriginal" helper inside:
...

As the error message suggests, you can load the real module with importOriginal, which the factory receives, spread it with ...original, and then override only today. If you pass the path in the form import('./date'), the return type of importOriginal() is typed as the ./date module.

tsx
// src/TodayBanner.test.tsx
import { render, screen } from '@testing-library/react';
import { expect, test, vi } from 'vitest';
import { TodayBanner } from './TodayBanner';

vi.mock(import('./date'), async (importOriginal) => {
  const original = await importOriginal();
  return {
    ...original,
    today: vi.fn(() => new Date(2030, 0, 1)),
  };
});

test('today() だけを差し替え、formatDate() は本物を使う', () => {
  render(<TodayBanner />);
  expect(screen.getByText('今日は2030年1月1日です')).toBeInTheDocument();
});

This test passed.

Functions called from within the same file are not replaced

I tested the following component, which displays the result of todayLabel(), with the same replacement method. The test failed.

tsx
// src/TodayLabel.tsx
import { todayLabel } from './date';

export function TodayLabel() {
  return <p>{todayLabel()}</p>;
}

The page showed the date of the test run (November 12, 2026).

text
表示: 今日は2026年11月12日です

todayLabel() calls today() directly within the same date.ts file. vi.mock replaces today only for the files that import it. The Vitest guide on module mocking pitfalls says that calls within the same file cannot be mocked, and recommends either moving the function to another file or passing the function as an argument.

Replacing a default-exported chart component that uses canvas

Last, I tested a Dashboard that totals sales and draws a bar chart with a SalesChart component. SalesChart draws on a canvas and is a default export.

tsx
// src/SalesChart.tsx
import { useEffect, useRef } from 'react';

// Draws a bar chart on a canvas (canvas does not work in jsdom)
export default function SalesChart({ values }: { values: number[] }) {
  const ref = useRef<HTMLCanvasElement>(null);
  useEffect(() => {
    const ctx = ref.current!.getContext('2d')!;
    values.forEach((v, i) => ctx.fillRect(i * 20, 100 - v, 16, v));
  }, [values]);
  return <canvas ref={ref} width={300} height={100} />;
}
tsx
// src/Dashboard.tsx
import SalesChart from './SalesChart';

export function Dashboard({ values }: { values: number[] }) {
  const total = values.reduce((a, b) => a + b, 0);
  return (
    <section>
      <h2>今週の売上</h2>
      <p>合計 {total} 件</p>
      <SalesChart values={values} />
    </section>
  );
}

When I rendered Dashboard with the real SalesChart, jsdom's getContext() returned null, and the test failed.

text
Not implemented: HTMLCanvasElement's getContext() method: without installing the @napi-rs/canvas npm package
...
TypeError: Cannot read properties of null (reading 'fillRect')

So I replaced ./SalesChart. When the factory returned it by name, as { SalesChart: ... }, I got the following error.

text
Error: [vitest] No "default" export is defined on the "./SalesChart" mock. Did you forget to return it from "vi.mock"?

For a default export, the factory must return the value under the key default. The vi.mock documentation also says a module with a default export needs a default key. Wrapping the fake component in vi.fn() also lets you check the props it receives.

tsx
// src/Dashboard.test.tsx
import { render, screen } from '@testing-library/react';
import { expect, test, vi } from 'vitest';
import { Dashboard } from './Dashboard';
import SalesChart from './SalesChart';

vi.mock('./SalesChart', () => ({
  default: vi.fn(({ values }: { values: number[] }) => (
    <div data-testid="sales-chart">{values.join(',')}</div>
  )),
}));

test('合計を表示し、グラフに数を渡す', () => {
  render(<Dashboard values={[3, 5, 2]} />);
  expect(screen.getByText('合計 10 件')).toBeInTheDocument();
  expect(screen.getByTestId('sales-chart')).toHaveTextContent('3,5,2');
  expect(SalesChart).toHaveBeenCalledTimes(1);
  expect(vi.mocked(SalesChart).mock.calls[0][0]).toEqual({ values: [3, 5, 2] });
});

This test passed.

Return values set in one test persist into the next

A return value set with vi.mocked(...).mockResolvedValue() is not cleared when its test ends. In my test, the first test set the mock to return a user named Tama. In the second test, I called fetchUser(2) without setting anything. The output was:

text
呼び出し回数: 0
返す値: { id: 1, name: 'たま' }

The call records were cleared, but the return value was still the one from the first test. In Vitest 5.1.0, the clearMocks option is true by default. It clears call records before each test. However, the contents of a mock, such as its return values and implementation, remain.

If you set mockReset to true, the contents are also restored before each test. With the same two tests, the second return value became undefined.

ts
// vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    environment: 'jsdom',
    setupFiles: ['./src/setup.ts'],
    mockReset: true,
  },
});

According to the documentation for mockReset() on mock functions, a mock created with an implementation, such as vi.fn(impl), returns to that impl rather than to an empty function. In the date example, I changed the factory's vi.fn(() => new Date(2030, 0, 1)) so that only the first test uses mockReturnValue() to set July 7. (I omit the imports and the factory that sets today to January 1, 2030.)

tsx
test('1つ目:このテストだけ別の日にする', () => {
  vi.mocked(today).mockReturnValue(new Date(2030, 6, 7));
  render(<TodayBanner />);
  expect(screen.getByText('今日は2030年7月7日です')).toBeInTheDocument();
});

test('2つ目:何も決めない', () => {
  render(<TodayBanner />);
  console.log('表示:', screen.getByRole('paragraph').textContent);
});

In the second test, which sets nothing before rendering, the default settings kept the value from the first test, so the page showed "Today is July 7, 2030." With mockReset: true, it returned to "Today is January 1, 2030."

Point

Put the default behavior that every test should share into the implementation passed to the factory's vi.fn(). Set values that should differ for each test inside that test, using mockReturnValue() or similar methods.

​Posted by 86