skip to content

In Vitest 5, why does a vi.mock factory that reads a top-level const fail with 'Cannot access before initialization', and how does vi.hoisted fix it?

level: seniorimportance: must knowfreq 55%

answer

  1. moved above the imports
  2. factory runs on first import
  3. temporal dead zone
  4. a hoisted block of your own
  5. doMock is not hoisted

basics

~20 s

Vitest hoists vi.mock above the imports, so its factory runs when the mocked module is first imported, before the file's top-level const lines run. vi.hoisted creates those values in a block hoisted with it, so the factory can read them.

solid answer

~50 s

Vitest rewrites a test file that contains `vi.mock`: the call moves to the top and the static imports become dynamic imports that run after it. The factory is called when the mocked module is first imported, which now happens before the file's own top-level code. A `const` the factory reads is still in its temporal dead zone, so the engine throws `Cannot access 'x' before initialization`, wrapped in Vitest's 'There was an error when mocking a module' message. Changing `const` to `let`, moving the line above the imports, or renaming it with a `mock` prefix does not help. The fix is `const { x } = vi.hoisted(() => ({ x: vi.fn() }))` before `vi.mock`; that callback is hoisted too and runs first. Alternatives: read the variable lazily inside a returned function, or use `vi.doMock` with a dynamic import. Vitest 5 also throws if `vi.mock` or `vi.hoisted` is nested inside a function or block.

code

typescript · 13 lines
typescript
import { expect, test, vi } from 'vitest'
import { registerUser } from '@/register'

const { sendWelcome } = vi.hoisted(() => ({
  sendWelcome: vi.fn(async () => true),
}))

vi.mock('@/mailer', () => ({ sendWelcome }))

test('registering sends one welcome mail', async () => {
  await expect(registerUser('[email protected]')).resolves.toBe('[email protected]')
  expect(sendWelcome).toHaveBeenCalledWith('[email protected]')
})

go deeper

for a junior

Recall that vi.mock is moved above the imports and that its factory cannot read ordinary top-level variables; vi.hoisted is the tool that makes values available to it.

for a middle

Walk through the execution order after the rewrite and explain why the temporal dead zone, not the declaration keyword, causes the reference error.

for a senior

Diagnose the variants: nested calls failing in Vitest 5, factories returning a bare value, modules cached by setup files, and when vi.doMock with a dynamic import is the better tool.

for a principal

Decide how the team writes module mocks: vi.hoisted plus top-level vi.mock as the house pattern, partial mocks via importOriginal, and review rules that keep factories small.

## What hoisting means for vi.mock In an ES module, every static `import` is evaluated before any other line of the file runs. A mock has to be registered before the module it replaces is loaded, so Vitest rewrites any test file that contains `vi.mock`: - It **moves** each `vi.mock` call, and each `vi.hoisted` call, to the top of the file. - It turns the static imports into **dynamic imports** placed after those calls, keeping live bindings, so the mock is registered first. - It finds the calls by static analysis, so `vi` must be imported from `vitest` or provided through `globals`. A `vi` re-exported from a helper file is not recognised. Only `vi.mock`, `vi.unmock` and `vi.hoisted` are hoisted. `vi.doMock` and `vi.doUnmock` stay where they are written and affect only modules imported after them. ## Why the factory sees an uninitialised variable Take a test file that declares `const sendWelcome = vi.fn()` and then calls `vi.mock('@/mailer', () => ({ sendWelcome }))`. After the rewrite, execution goes like this: 1. The hoisted `vi.mock` registers the factory but does not call it. 2. The rewritten import of the module under test runs, and that module imports `@/mailer`. 3. Vitest calls the factory now, to build the mocked `@/mailer`. 4. The factory reads `sendWelcome`, whose `const` line has not run yet. The binding is in its **temporal dead zone**, so the engine throws `ReferenceError: Cannot access 'sendWelcome' before initialization`. 5. Vitest reports it as "There was an error when mocking a module", reminding you that the factory is hoisted to the top of the file, with the reference error as the cause. Switching `const` to `let` changes nothing, since `let` has the same dead zone. Moving the declaration above the import lines changes nothing either, because the imports no longer sit where the source shows them. Renaming the variable with a `mock` prefix has no effect in Vitest. ## The fixes - **`vi.hoisted`**: `const { sendWelcome } = vi.hoisted(() => ({ sendWelcome: vi.fn() }))` runs its callback in the hoisted block, ahead of the imports, and returns its value. Declare it before `vi.mock` and the factory can use it. The callback itself cannot read imported bindings, because they do not exist yet. - **Read late**: a factory that returns a function which reads the variable only when called, such as `() => ({ sendWelcome: (email) => spy(email) })`, works, because the read happens after the file has finished running. It is fragile and harder to read than `vi.hoisted`. - **`vi.doMock` with a dynamic import**: it is not hoisted, so it can use any variable, but only modules imported after the call are mocked. - **Partial mocks**: the factory may be `async`. Take the real module from its `importOriginal` argument, or with `await vi.importActual(path)`, and override one export. ## Rules Vitest 5 enforces - `vi.mock`, `vi.unmock` and `vi.hoisted` must sit at the **top level**. Vitest 4 only warned about a call inside a function, a block or a `describe` or `test` callback; Vitest 5 fails the file, listing every offending call with its location and explaining that it would run before anything else in the file. - A factory must return an **object of exports**, with a default export under a `default` key. A bare value fails with "is not returning an object. Did you mean to return an object with a "default" key?" - The factory runs once per module, and its result is cached until `vi.unmock` or `vi.doUnmock`. - A module already imported by a setup file is cached and is not replaced by a later `vi.mock`. ## How this differs from Jest | Topic | Jest | Vitest 5 | |---|---|---| | Factory return | the return value is the default export | an object of exports, `default` included | | Async factory | not supported | supported | | Getting the real module | `jest.requireActual` | `vi.importActual` or `importOriginal` | | `__mocks__` in the root | applied automatically | used only when `vi.mock` names the module | | `require()` calls | mockable | not mockable with `vi.mock` | The hoisting itself is not new: Jest's default transform also lifts `jest.mock` calls to the top. What changes is the rule set around it and the shape the factory must return.

  • Why does Vitest 5 fail a file that calls vi.mock inside a describe block?
    The call is hoisted to the top of the file whatever its position, so a nested `vi.mock` reads as scoped to that block while it actually applies to the whole file before anything runs. Vitest 4 only warned; Vitest 5 fails the file and lists each offending call with its location. `vi.doMock` and `vi.doUnmock` are not hoisted and may still be called anywhere.
  • How do you replace one export of a module and keep the rest real?
    Use an async factory: `vi.mock(import('./mailer'), async (importOriginal) => ({ ...(await importOriginal()), sendWelcome: vi.fn() }))`, or `await vi.importActual('./mailer')` inside it. Passing `{ spy: true }` instead of a factory keeps every real implementation while recording calls, which suits asserting how an export was used.
  • Why doesn't a vi.mock in the test file replace a module that a setup file already imported?
    Setup files run before the test file, and the modules they import are already cached when the test file's mocks are registered, so the cached real module is reused. Either avoid importing that module in setup, or call `vi.resetModules()` inside `vi.hoisted` to clear the module cache before the test file's imports run.

A hoisted vi.mock factory is like a recipe card handed to the kitchen before the shopping is done: the cook follows it the moment the first order comes in, so an ingredient bought later in the day is not there yet. vi.hoisted is doing that shopping first thing, before the kitchen opens.

  • vi.mock runs where it is written, so a const declared above it is ready.
  • Prefixing the variable name with mock lets the Vitest factory read it.
  • Writing vi.mock inside a describe block scopes the mock to that block.
  • A vi.mock factory can return a bare function to stand in for the default export.
  • vi.doMock also replaces modules that were statically imported at the top.
  • Declaring the variable with let instead of const avoids the error.

Assumes Vitest 5; since 5.0 a vi.mock, vi.unmock or vi.hoisted call that is not at the top level fails the file instead of logging a warning.