| | |

Vitest 11 🧪 Module Mocking — vi.mock() and factory functions

⏱️ Estimated read: 9 min | |

Module mocking replaces an entire module’s exports for the duration of a test file. vi.mock("./module") is hoisted to the top of the file, the module is replaced with an auto-mock that returns undefined for every export, and a factory function can supply the implementation. The mechanism is the same as Jest’s, with one significant difference: Vitest’s hoisting scoping requires the factory’s external variables to be wrapped in vi.hoisted(), and the factory must return an object with explicit exports rather than the default export alone.

This chapter covers the vi.mock() call, the factory function and its hoisting constraint, and the partial mock pattern that keeps some exports real. The sections that follow walk through the auto-mock, the factory, and the importActual and importMock utilities that the partial mock depends on.

Key point: vi.mock("./module") is hoisted to the top of the file and replaces the module with an auto-mock; a factory function supplies the implementation, variables referenced inside it must be wrapped in vi.hoisted(), and the factory must return an object with the named exports the test uses.


a. The auto-mock and the hoisting

vi.mock(path) replaces the module with an auto-mock. Every exported function becomes a mock that returns undefined, and every exported value becomes a mock’s return. The call is hoisted to the top of the file, which means it runs before any import.

import { vi, test, expect } from "vitest";
import { fetchUser } from "./api";

vi.mock("./api"); // hoisted above the imports

test("auto-mock returns undefined", async () => {
  const user = await fetchUser("1");
  expect(user).toBeUndefined();
  expect(fetchUser).toHaveBeenCalledWith("1");
});

The hoisting is the reason the factory cannot reference a module-level variable directly. The factory is lifted above the variable’s declaration, so the variable is undefined at the time the factory runs. The vi.hoisted() wrapper creates the variable at the same hoisted position, which makes it available.

// WRONG: mockFn is undefined when the factory runs
const mockFn = vi.fn();
vi.mock("./api", () => ({ fetchUser: mockFn }));

// RIGHT: the variable is hoisted with the factory
const mockFn = vi.hoisted(() => vi.fn());
vi.mock("./api", () => ({ fetchUser: mockFn }));

The vi.hoisted() is the migration’s biggest gotcha. A project that migrates from Jest has factories that reference in-scope variables, and those factories work in Jest because Jest’s Babel hoisting handles the reference differently. In Vitest, the reference is undefined until the variable is hoisted.


b. The factory function and the explicit exports

The factory function returns the module’s replacement. The returned object must have the same shape as the module’s exports—the named exports the test imports, and a default property if the module has a default export.

vi.mock("./api", () => ({
  fetchUser: vi.fn().mockResolvedValue({ id: "1", name: "Ana" }),
  fetchPosts: vi.fn().mockResolvedValue([]),
  default: vi.fn(),
}));

The explicit shape is the difference from Jest’s factory, which can return the default export directly. Vitest requires the object to carry the named exports, and a factory that returns () => ({ ... }) for a module with named exports produces a test that fails to import the names.

The factory can be async. An async factory is awaited before the module is used, which is the pattern for a mock that needs to import another module or compute a value.

vi.mock("./api", async () => {
  const actual = await vi.importActual("./api");
  return {
    ...actual,
    fetchUser: vi.fn().mockResolvedValue({ id: "1" }),
  };
});

The vi.importActual(path) imports the real module inside the factory, which is the primitive the partial mock is built on. The spread of the actual module keeps every export real except the one the test replaces.


c. The partial mock and importActual

A partial mock keeps some of the real module’s behavior and replaces only the functions the test needs to control. The factory imports the actual module, spreads its exports, and overrides the specific functions.

vi.mock("./api", async () => {
  const actual = await vi.importActual("./api");
  return {
    ...actual,
    fetchUser: vi.fn().mockResolvedValue({ id: "1", name: "Ana" }),
  };
});

The partial mock is the pattern for a module with a mix of pure functions and network calls. The pure functions stay real, and the network call is replaced with a deterministic value. The test does not need to mock the pure functions because they have no side effects.

The vi.importMock(path) utility is the other direction: it imports the module’s auto-mock. It is the way to access a mocked function from inside a test without importing the mock directly.

import { fetchUser } from "./api";

vi.mock("./api");

test("accesses the mock", async () => {
  const { fetchUser: mockedFetchUser } = await vi.importMock("./api");
  mockedFetchUser.mockResolvedValue({ id: "2" });
  // ...
});

The vi.mocked() helper is the type-level companion. It casts an imported function to its mocked type, so the mock methods (mockResolvedValue, mockReturnValue) are available without a type assertion.

import { fetchUser } from "./api";

vi.mock("./api");

const mockedFetchUser = vi.mocked(fetchUser);
mockedFetchUser.mockResolvedValue({ id: "1" });

The vi.mocked() call is the recommended form in a TypeScript project. Without it, the imported function has its original type, and the mock methods are a type error.


Complete Example Session

// ============================================
// PART 1: THE MODULE UNDER TEST
// ============================================
// src/api.ts
export async function fetchUser(id: string) {
  const res = await fetch(`/api/users/${id}`);
  return res.json();
}

export function formatName(name: string) {
  return name.trim();
}

// ============================================
// PART 2: THE AUTO-MOCK
// ============================================
import { vi, test, expect } from "vitest";
import { fetchUser } from "./api";

vi.mock("./api");

test("auto-mock", async () => {
  const user = await fetchUser("1");
  expect(user).toBeUndefined();
});

// ============================================
// PART 3: THE FACTORY
// ============================================
vi.mock("./api", () => ({
  fetchUser: vi.fn().mockResolvedValue({ id: "1", name: "Ana" }),
  formatName: vi.fn((n: string) => n.trim()),
}));

// ============================================
// PART 4: THE HOISTED VARIABLE
// ============================================
const mockFetch = vi.hoisted(() => vi.fn().mockResolvedValue({ id: "1" }));
vi.mock("./api", () => ({ fetchUser: mockFetch }));

// ============================================
// PART 5: THE PARTIAL MOCK
// ============================================
vi.mock("./api", async () => {
  const actual = await vi.importActual("./api");
  return {
    ...actual,
    fetchUser: vi.fn().mockResolvedValue({ id: "1" }),
  };
});

The parts covered the auto-mock, the factory, the hoisted variable, and the partial mock.


Quick Reference

Mock API

CallEffect
vi.mock(path)Auto-mock the module
vi.mock(path, factory)Replace with factory
vi.hoisted(fn)Hoist a variable for the factory
vi.importActual(path)Import the real module
vi.importMock(path)Import the auto-mock
vi.mocked(fn)Type-cast to mocked

Factory Rules

RuleDetail
Return shapeObject with named exports
External variablesWrap in vi.hoisted()
Async factoryAllowed and awaited
Default exportInclude default key

Reset Options

OptionEffect
restoreMocks: truevi.restoreAllMocks() before each test
clearMocks: truevi.clearAllMocks() before each test
mockReset()Clear history and implementation

Best Practices

✅ Do This:

// Hoist variables used in the factory
const mockFn = vi.hoisted(() => vi.fn());                     // ✅

// Return the explicit export shape
vi.mock("./api", () => ({ fetchUser: mockFn }));               // ✅

// Use vi.mocked for type safety
vi.mocked(fetchUser).mockResolvedValue({ id: "1" });           // ✅

❌ Don’t Do This:

// Reference a module-level variable in the factory
const mockFn = vi.fn();
vi.mock("./api", () => ({ fetchUser: mockFn })); // undefined   // ❌

// Return the default export directly
vi.mock("./api", () => () => "mocked"); // wrong shape         // ❌

// Forget the default export
vi.mock("./api", () => ({ fetchUser: mockFn })); // no default  // ❌

Common Pitfalls

PitfallWhy It HappensFix
Mock function is undefinedFactory references unhoisted variablevi.hoisted()
Import failsFactory missing named exportReturn the full shape
Mock methods are a type errorNo vi.mocked()Cast the import
Real behavior lostFull mock instead of partialvi.importActual()

Real-World Examples

1. Auto-mock

vi.mock("./api");

2. Factory

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

3. Hoisted variable

const mock = vi.hoisted(() => vi.fn());

4. Partial mock

vi.mock("./api", async () => ({ ...(await vi.importActual("./api")), fetchUser: vi.fn() }));

5. Import actual

const actual = await vi.importActual("./api");

6. Import mock

const mocked = await vi.importMock("./api");

7. vi.mocked

vi.mocked(fetchUser).mockResolvedValue({ id: "1" });

8. Async factory

vi.mock("./api", async () => { ... });

9. Default export

vi.mock("./api", () => ({ default: vi.fn() }));

10. Restore

test: { restoreMocks: true }

Visual

Hoisting

┌─────────────────────────────────────────────────────────┐
│  vi.mock("./api", () => ({ fetchUser: mockFn }))        │
│         │                                               │
│         ▼                                               │
│  Hoisted above the imports                              │
│         │                                               │
│         ▼                                               │
│  Factory runs before `const mockFn = vi.fn()`           │
│         │                                               │
│         ▼                                               │
│  mockFn is undefined → fix with vi.hoisted              │
└─────────────────────────────────────────────────────────┘

The Partial Mock

┌─────────────────────────────────────────────────────────┐
│  vi.mock("./api", async () => {                         │
│    const actual = await vi.importActual("./api");       │
│    return {                                             │
│      ...actual,         ◄── real functions kept         │
│      fetchUser: vi.fn() ◄── one function replaced       │
│    };                                                   │
│  });                                                    │
└─────────────────────────────────────────────────────────┘

Factory Shape

┌─────────────────────────────────────────────────────────┐
│  Module exports:                                        │
│    fetchUser, fetchPosts, default                       │
│                                                         │
│  Factory must return:                                   │
│    {                                                    │
│      fetchUser: vi.fn(),                                │
│      fetchPosts: vi.fn(),                               │
│      default: vi.fn(),                                  │
│    }                                                    │
└─────────────────────────────────────────────────────────┘

Auto-Mock vs Factory

┌─────────────────────────────────────────────────────────┐
│  vi.mock("./api")                                       │
│    → every export is a mock returning undefined         │
│                                                         │
│  vi.mock("./api", () => ({ fetchUser: vi.fn() }))       │
│    → the factory's shape replaces the module            │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Auto-mockvi.mock("./module")
Factoryvi.mock("./module", () => ({ ... }))
Hoisted variablevi.hoisted(() => vi.fn())
Partial mockvi.importActual() + spread
Type castvi.mocked(fn)
ResetrestoreMocks: true

Key takeaways:

  • vi.mock() is hoisted to the top of the file. It replaces the module with an auto-mock before any import, and a factory function supplies the implementation.
  • The factory cannot reference a module-level variable directly. The hoisting runs the factory before the variable’s declaration, so the variable is undefined. vi.hoisted() creates the variable at the same hoisted position .
  • The factory must return the explicit export shape. The object has the named exports the test imports, and a default property if the module has a default export.
  • The partial mock keeps the real functions. vi.importActual() imports the real module, and the spread keeps every export except the one the test replaces.
  • vi.mocked() is the type-level companion. It casts the imported function to its mocked type, so the mock methods are available without a type assertion .

Remember: Module mocking replaces the whole module, and the factory is the replacement. The hoisting is the constraint: the factory runs before the file’s own declarations, so any variable it uses must be hoisted with it. Use the auto-mock when the test does not care about the implementation, the factory when it does, and the partial mock when only one function needs to be replaced. The shape of the returned object is the module’s shape; a missing export is an import that fails.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!