| | |

Vitest 31 🧪 Advanced Mocking — vi.hoisted and factory hoisting

⏱️ Estimated read: 17 min | |

vi.mock looks like an ordinary function call, and that is the source of almost every confusion around it. It is not. Before the test file is executed, Vitest’s transform rewrites it and lifts every vi.mock call above the import statements. That rewrite is what makes module mocking possible at all in an ESM graph, where the imports are evaluated before the first line of the file, and it is also the reason a factory that references a variable declared three lines later throws ReferenceError: Cannot access 'x' before initialization.

vi.hoisted is the escape hatch for that ordering. It is a second hoisted call whose only job is to create values inside the same region of the file that the factory runs in, so a mock factory can close over real vi.fn() instances instead of reaching into a temporal dead zone.

This chapter covers what the transform actually does to a test file, why a module-level const is unreachable from a factory, how vi.hoisted repairs the ordering, the importOriginal parameter for partial mocks, and vi.doMock for the case where the mock has to be registered at runtime rather than at load time.

Key point: vi.mock is moved above the imports by the transform, so its factory executes before any top-level const in the file has been initialised; vi.hoisted moves a value-producing callback into the same hoisted region, which makes those values exist by the time the factory is called.


Why hoisting exists

The import-hoisting problem. Static import declarations are not statements in the ordinary sense. The specification resolves and evaluates the entire module graph before the first line of the importing file runs. By the time const sendSpy = vi.fn() on line four executes, the module imported on line one has already been loaded, evaluated, and its exports bound to local names. A mock registration written on line six would therefore always be too late — the real module would already be in place. The transform solves this by moving the registration above line one, where it still has a chance to influence how the module is resolved.

The temporal dead zone. Hoisting the registration above the imports has a consequence the source code does not show. The factory is not called when vi.mock is registered; it is called when the mocked module is first requested, which happens during the evaluation of the import on line one. At that instant the test file’s top-level const bindings have been created but not initialised. Reading one throws. The error points at the factory line, but the cause is the evaluation order produced by the transform.

The factory indirection. A mock factory is a function rather than an object so that Vitest can defer building the module shape until the module is genuinely needed, and so that the factory can be async and call back into the real implementation through importOriginal. That deferral is what makes partial mocks possible. It is also what makes the ordering constraint visible to the user, because a deferred callback that closes over a not-yet-initialised binding is exactly the shape of a TDZ error.

The need for a shared handle. A test rarely just replaces a module — it also asserts on the replacement. expect(mocks.send).toHaveBeenCalledWith(...) only works if the test body and the factory hold the same vi.fn() instance. Without a hoisted region there is no place to declare that instance such that both the factory, which runs before the imports, and the test body, which runs after them, can reach it.

The runtime alternative. Not every mock can be decided before the file executes. A test that wants a different implementation per case, or that needs a value only known at runtime, needs a registration that is deliberately not hoisted. vi.doMock is that path, and it trades the module-graph guarantee for runtime flexibility — it only affects imports that happen after the call, which is why it always appears next to vi.resetModules() and a dynamic await import().

The trade-off. Hoisting is invisible machinery, and invisible machinery produces errors that point at the wrong line. The cost of the design is a small class of confusing failures; the benefit is that module mocking works at all under ESM’s evaluation order. vi.hoisted is the price of admission, made explicit.


a. What the transform does to vi.mock

The mental model that fixes everything is: read the file twice, once as you wrote it and once as the transform rewrites it. Written plainly, this looks reasonable.

import { vi } from "vitest";
import { send } from "./mailer";

// created after the import statement, in source order
const sendSpy = vi.fn();

vi.mock("./mailer", () => ({
  send: sendSpy, // ReferenceError: Cannot access 'sendSpy' before initialization
}));

After the transform, the call order is different from the source order. Everything above is rewritten into something equivalent to the following, with the mock registration lifted to the very top.

// what the transform produces (simplified)
vi.mock("./mailer", () => ({ send: sendSpy })); // lifted above the import

import { send } from "./mailer"; // evaluating this calls the factory
const sendSpy = vi.fn();          // still not initialised at that moment

The import on the second line triggers the mock factory, the factory reads sendSpy, and sendSpy is in its temporal dead zone because its declaration has not been reached. The ReferenceError is accurate — it is just describing code you did not write.

Reordering the source does not help. Putting the const before the vi.mock call changes nothing, because the transform lifts the registration above the declaration as well as above the imports. The only thing that moves the initialisation is vi.hoisted.

import { vi } from "vitest";

// lifted into the same region as vi.mock
const mocks = vi.hoisted(() => ({ send: vi.fn() }));

vi.mock("./mailer", () => ({ send: mocks.send }));

import { send } from "./mailer"; // the factory now reads an initialised object

The vi.hoisted call returns the object it builds, and the transform places that call above the imports alongside the mock registration. When the import on the last line evaluates the factory, mocks.send already exists. The same vi.fn() instance is also visible to the test body, so assertions work.


b. vi.hoisted in depth

The signature is vi.hoisted<T>(factory: () => T): T. It takes a synchronous callback, runs it at the top of the file, and returns whatever the callback returned, with the type preserved. That means mocks.send is typed as Mock<...> and the usual mock methods are available on it without a cast.

import { vi, beforeEach, test, expect } from "vitest";

// the callback runs once, before any import in this file
const mocks = vi.hoisted(() => {
  return {
    fetchUser: vi.fn(),
    fetchPosts: vi.fn(),
  };
});

vi.mock("./api", () => ({
  fetchUser: mocks.fetchUser, // initialised before "./api" is evaluated
  fetchPosts: mocks.fetchPosts,
}));

beforeEach(() => {
  vi.resetAllMocks(); // clears call history on the hoisted spies
  mocks.fetchUser.mockResolvedValue({ id: 1, name: "Alice" });
});

The second use is less obvious but equally common: setting state that the real module reads at import time. A module that evaluates process.env.API_BASE at the top level will read whatever is set before its import statement runs, and vi.hoisted is the only place in the test file that runs early enough.

const apiBase = vi.hoisted(() => {
  // the real client module reads this during its own evaluation
  process.env.API_BASE = "https://api.test";
  return process.env.API_BASE;
});

vi.mock("./client", () => ({
  client: { baseUrl: apiBase, get: vi.fn() },
}));

The rule about what is safe inside the callback follows directly from when it runs. Treat it as if it executes before the file exists, because functionally it does. vi itself is safe — Vitest injects the binding for hoisted code — and inline literals are safe. Anything else imported at the top of the test file is not initialised yet and will throw for exactly the reason a top-level const throws.

Keep the callback synchronous and free of per-test logic. It runs once, at load time, and has no access to test context. Setup that changes between cases belongs in beforeEach, not in vi.hoisted.


c. Partial mocks with importOriginal

Wholesale mocks are easy; the common real case is replacing one export and keeping the rest. The factory receives an argument — conventionally named importOriginal — that returns the real module. Because it is a parameter supplied by Vitest at call time, it is available inside a hoisted factory without any of the ordering problems a top-level import would have.

vi.mock("./config", async (importOriginal) => {
  // call the real module loader for the mocked path
  const actual = await importOriginal<typeof import("./config")>();

  // spread the real exports, then override the single field
  return { ...actual, apiUrl: "http://localhost:3000" };
});

The order of the spread matters. Spreading actual first and placing the override after it means the override wins; reversing the two silently discards the mock. importOriginal is the same function as vi.importActual, pre-bound to the path being mocked, so there is no need to repeat the specifier.

The typed form replaces the string argument with an import expression. TypeScript then infers the module shape from the specifier itself, and the factory’s return value is checked against it, which removes most of the as unknown as typeof import(...) casts that older code needed.

vi.mock(import("./config"), async (importOriginal) => {
  const actual = await importOriginal(); // already typed from the expression
  return { ...actual, apiUrl: "http://localhost:3000" };
});

A third form sits between full automock and a hand-written factory. Passing { spy: true } automocks the module but keeps every original implementation, wrapped in a spy, so the module behaves normally while calls are recorded.

vi.mock("./math", { spy: true });

test("still adds", async () => {
  const { add } = await import("./math");
  expect(add(1, 2)).toBe(3);              // real implementation ran
  expect(add).toHaveBeenCalledWith(1, 2); // and the call was recorded
});

d. vi.doMock — registering at runtime

Every call described so far is hoisted. vi.doMock is the deliberate exception: it takes effect where it is written and applies only to modules imported after the call. Static imports have already been evaluated by then, so they keep whatever they received. The pattern therefore always pairs a module-cache reset with a dynamic import.

test("swaps the config at runtime", async () => {
  vi.resetModules();                                  // drop the cached module instance
  vi.doMock("./config", () => ({ apiUrl: "http://stub" })); // not hoisted

  const { apiUrl } = await import("./config");        // resolved after the mock
  expect(apiUrl).toBe("http://stub");
});

The teardown counterpart is vi.doUnmock, which is also not hoisted, and is usually placed in afterEach alongside a second vi.resetModules() so the next test starts from a clean module graph.

vi.unmock is the hoisted sibling that undoes a vi.mock registration for a path — useful when a shared setup file mocks a module and one test file wants the real thing back.

vi.unmock("./config"); // hoisted, restores the real module for this file

The distinction is the whole point of having both APIs. Use vi.mock when the replacement is a fixed, file-wide decision, and use vi.doMock when the replacement depends on state that only exists during a particular test.


Complete Example Session

// ============================================
// PART 1: THE FAILING HOIST
// ============================================
import { describe, test, expect, beforeEach, afterEach, vi } from "vitest";
import { send } from "./mailer";

// declared in source order, but evaluated after the factory already ran
const sendSpy = vi.fn();

vi.mock("./mailer", () => ({
  send: sendSpy, // ReferenceError: Cannot access 'sendSpy' before initialization
}));

// ============================================
// PART 2: THE HOISTED FIX
// ============================================
const mocks = vi.hoisted(() => ({
  send: vi.fn(),
}));

vi.mock("./mailer", () => ({
  send: mocks.send, // mocks exists before "./mailer" is evaluated
}));

// ============================================
// PART 3: THE TYPED FACTORY
// ============================================
vi.mock(import("./config"), async (importOriginal) => {
  const actual = await importOriginal(); // typed from the import expression
  return { ...actual, apiUrl: "http://localhost:3000" };
});

// ============================================
// PART 4: THE ENVIRONMENT HOIST
// ============================================
const apiBase = vi.hoisted(() => {
  process.env.API_BASE = "https://api.test"; // read by the real client at import
  return process.env.API_BASE;
});

vi.mock("./client", () => ({
  client: { baseUrl: apiBase, get: vi.fn() },
}));

// ============================================
// PART 5: THE SHARED SPY RESET
// ============================================
beforeEach(() => {
  vi.resetAllMocks();                          // clear history on the hoisted spies
  mocks.send.mockResolvedValue({ ok: true });   // re-arm the default behaviour
});

// ============================================
// PART 6: THE ASSERTION
// ============================================
test("sends the welcome mail", async () => {
  await send({ to: "alice@example.test" });

  expect(mocks.send).toHaveBeenCalledTimes(1);
  expect(mocks.send).toHaveBeenCalledWith({ to: "alice@example.test" });
});

// ============================================
// PART 7: THE SPY AUTOMOCK
// ============================================
vi.mock("./math", { spy: true }); // real code, wrapped in spies

// ============================================
// PART 8: THE RUNTIME REGISTRATION
// ============================================
test("swaps the config at runtime", async () => {
  vi.resetModules();                                     // drop the cached instance
  vi.doMock("./config", () => ({ apiUrl: "http://stub" })); // not hoisted
  const { apiUrl } = await import("./config");           // resolved after the mock
  expect(apiUrl).toBe("http://stub");
});

// ============================================
// PART 9: THE TEARDOWN
// ============================================
afterEach(() => {
  vi.doUnmock("./config"); // undo the runtime registration
  vi.resetModules();       // start the next test from a clean module graph
});

// ============================================
// PART 10: THE CONFIG
// ============================================
// vitest.config.ts
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    clearMocks: true,    // wipe call history before every test
    mockReset: false,    // keep the implementations you set up
    restoreMocks: false, // do not restore original implementations
  },
});

The ten parts covered the failing hoist, the vi.hoisted fix, the typed factory, the environment hoist, the shared spy reset, the assertion, the spy automock, the runtime registration, the teardown, and the config that keeps call history clean.


Quick Reference

Hoisted and Not Hoisted

CallHoistedAffects
vi.mockyesstatic and dynamic imports
vi.hoistedyesnothing; returns a value
vi.unmockyesstatic and dynamic imports
vi.doMocknodynamic imports after the call
vi.doUnmocknodynamic imports after the call

The vi.mock Forms

FormBehaviour
vi.mock(path)automock; every function becomes vi.fn()
vi.mock(path, factory)the factory result replaces the module
vi.mock(path, { spy: true })real code wrapped in spies
vi.mock(import(path), factory)same, with the module type inferred

Inside a Factory

AvailableNot Available
importOriginal()top-level const bindings
viother imported bindings
inline literalstest-file helper functions
awaitper-test state

Hoisting Failures

MessageCauseFix
Cannot access 'x' before initializationfactory closes over a top-level constcreate it in vi.hoisted
Mock silently ignoredvi.doMock used for a static importuse vi.mock or await import()
x is not a functionfactory returned a value for a function exportreturn vi.fn()
Real module loadedimportOriginal called outside the factorycall it inside the callback

Best Practices

✅ Do This:

// Create the shared spies inside vi.hoisted
const mocks = vi.hoisted(() => ({ send: vi.fn() }));            // ✅

// Reference only the hoisted object in the factory
vi.mock("./mailer", () => ({ send: mocks.send }));              // ✅

// Delegate to the real module and override one field
vi.mock("./config", async (o) => ({ ...(await o()), apiUrl: "x" })); // ✅

// Let TypeScript infer the shape from an import expression
vi.mock(import("./config"), async (o) => ({ ...(await o()) })); // ✅

// Pair vi.doMock with resetModules and a dynamic import
vi.resetModules(); await import("./config");                    // ✅

// Clear the hoisted spies between tests
beforeEach(() => { vi.resetAllMocks(); });                      // ✅

❌ Don’t Do This:

// Reference a top-level const from the factory
const spy = vi.fn(); vi.mock("./m", () => ({ f: spy }));        // ❌

// Assume source order protects the binding
vi.mock("./m", () => ({ f: spy })); const spy = vi.fn();        // ❌

// Call vi.hoisted inside a test body
test("x", () => { const m = vi.hoisted(() => ({})); });         // ❌

// Use doMock expecting a static import to change
vi.doMock("./m", () => ({})); import { f } from "./m";          // ❌

// Return a plain value where a function is exported
vi.mock("./m", () => ({ fn: 42 }));                             // ❌

// Assume call history clears itself
expect(mocks.send).not.toHaveBeenCalled();                      // ❌

Common Pitfalls

PitfallWhy It HappensFix
TDZ error in the factoryfactory reads an uninitialised top-level constcreate the value in vi.hoisted
Mock never appliedvi.doMock used while a static import already ranuse vi.mock, or await import() after a reset
Override discardedspread order puts actual last{ ...actual, field: value }
undefined is not a functionfactory omitted a function exportreturn the full shape or spread actual
Spy not callablevi.fn() created outside the hoisted regionmove the creation into vi.hoisted
State leaks between testsspies keep call historyvi.resetAllMocks() in beforeEach
Type error on the factory resultpartial object without a typeuse vi.mock(import(path), ...)
Env var ignoredset after the module was importedset it inside vi.hoisted

Real-World Examples

1. Shared spy handle

const mocks = vi.hoisted(() => ({ send: vi.fn() }));
vi.mock("./mailer", () => ({ send: mocks.send }));

2. Environment set before import

const base = vi.hoisted(() => {
  process.env.API_BASE = "https://api.test";
  return process.env.API_BASE;
});

3. Partial override with the original

vi.mock("./config", async (importOriginal) => {
  const actual = await importOriginal();
  return { ...actual, apiUrl: "http://localhost:3000" };
});

4. Typed factory via import expression

vi.mock(import("./config"), async (importOriginal) => {
  const actual = await importOriginal();
  return { ...actual, apiUrl: "http://localhost:3000" };
});

5. Spy automock keeping the implementation

vi.mock("./math", { spy: true });

expect(add(1, 2)).toBe(3);
expect(add).toHaveBeenCalledWith(1, 2);

6. Runtime mock swap

vi.resetModules();
vi.doMock("./config", () => ({ apiUrl: "http://stub" }));
const config = await import("./config");

7. Asserting on a hoisted spy

expect(mocks.send).toHaveBeenCalledTimes(1);
expect(mocks.send).toHaveBeenCalledWith({ to: "a@b.test" });

8. Resetting between tests

beforeEach(() => {
  vi.resetAllMocks(); // clears the hoisted spies too
});

9. Mocking a package

vi.mock("axios", () => ({
  default: { get: vi.fn().mockResolvedValue({ data: [] }) },
}));

10. Restoring a real module

vi.unmock("./config"); // hoisted, restores the real module for this file

Visual

The Hoisting Transform

┌────────────────────────────────────────────────────────────┐
│  SOURCE                                                    │
│    import { getUser } from "./api";                        │
│    const mocks = vi.hoisted(() => ({ fn: vi.fn() }));      │
│    vi.mock("./api", () => ({ getUser: mocks.fn }));        │
│                                                            │
│  AFTER THE TRANSFORM                                       │
│    const mocks = vi.hoisted(() => ({ fn: vi.fn() }));      │
│    vi.mock("./api", () => ({ getUser: mocks.fn }));        │
│    import { getUser } from "./api";                        │
│                                                            │
│  The two vitest calls are lifted above the import, so      │
│  mocks exists before "./api" is evaluated.                 │
└────────────────────────────────────────────────────────────┘

The Evaluation Order

┌────────────────────────────────────────────────────────────┐
│  WITH vi.hoisted                                           │
│                                                            │
│  1. const mocks = vi.hoisted(...)      runs first          │
│  2. vi.mock registers the factory      for "./api"         │
│  3. import "./api"                     factory is called   │
│  4. factory reads mocks.fn             initialised   OK    │
│  5. the rest of the test file runs                         │
│                                                            │
│  WITHOUT vi.hoisted                                        │
│                                                            │
│  3. import "./api"                     factory is called   │
│  4. factory reads the const            not set       TDZ   │
└────────────────────────────────────────────────────────────┘

Hoisted and Runtime Registration

┌────────────────────────────────────────────────────────────┐
│  HOISTED: vi.mock                                          │
│    moved above every import                                │
│    applies to static and dynamic imports                   │
│    the factory runs while the module graph is built        │
│                                                            │
│  RUNTIME: vi.doMock                                        │
│    stays exactly where it is written                       │
│    applies only to imports after the call                  │
│    needs vi.resetModules() plus await import()             │
└────────────────────────────────────────────────────────────┘

The Partial Mock Merge

┌────────────────────────────────────────────────────────────┐
│  PARTIAL MOCK MERGE                                        │
│                                                            │
│  ACTUAL EXPORT        FACTORY RETURN        RESULT         │
│  ─────────────────────────────────────────────────────     │
│  apiUrl               "http://localhost"    overridden     │
│  timeout              (spread)              kept           │
│  fetchUser            (spread)              kept           │
│                                                            │
│  return { ...actual, apiUrl: "http://localhost" };         │
└────────────────────────────────────────────────────────────┘

Summary

ItemValue
What is hoistedvi.mock, vi.hoisted, vi.unmock
What is not hoistedvi.doMock, vi.doUnmock
Signaturevi.hoisted<T>(fn: () => T): T
Runs whenonce, before any import in the file
SolvesCannot access 'x' before initialization
Factory argumentimportOriginal
Partial mock{ ...actual, field: value }
Typed formvi.mock(import(path), factory)
Spy automockvi.mock(path, { spy: true })
Runtime formvi.doMock plus vi.resetModules()
Assertion targetthe spy created in vi.hoisted

Key takeaways:

  • vi.mock is lifted above the imports. The registration has to happen before the module graph is evaluated, otherwise the real module would already be in place. The lifting is what makes mocking work under ESM, and it is also what makes the source order of the file a lie.
  • The factory runs during the import, not at registration. That is the mechanism behind the TDZ error. The call to vi.mock is cheap; the factory is invoked later, when the mocked module is first requested, which is before any top-level const in the test file has been initialised.
  • vi.hoisted moves the initialisation into the same region. It returns the value it builds, so the same object is available to the factory and to the test body. That shared identity is what makes expect(mocks.send).toHaveBeenCalled() work at all.
  • importOriginal is a parameter, not an import. Because it is supplied by Vitest at call time, it is immune to the hoisting problem and is the correct way to keep the real module while overriding a single export. Put the override after the spread, never before.
  • vi.doMock is the runtime escape hatch. It is not hoisted, it only affects imports that happen after it, and it must be paired with vi.resetModules() and a dynamic await import() to do anything useful.
  • Only vi and inline literals are safe inside vi.hoisted. Everything else imported at the top of the file is in the same temporal dead zone the hoisted call is trying to avoid.

Remember: The transform reads the file in a different order than you wrote it. vi.mock and vi.hoisted are lifted above the imports, everything else is not, and the factory is called at the moment the mocked module is first requested — that single fact explains the TDZ error, the need for vi.hoisted, the safety of importOriginal, and the existence of the unhoisted vi.doMock. When a mock fails, ask which side of the lift your value lives on.

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!