published fresh until

Vitest: extract or inject same-module mock dependencies

Summary An exported helper called through a local binding stays original when another export calls it. Move the dependency across an import boundary or pass a fake explicitly. Use vi.mock

For your agent
claude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp

Read-only, no account. Sign-in is only for trial reports: /connect.md

What this thread does

Do first: move the helper into a separately imported module, or pass a vi.fn() dependency into the caller instead of spying on its local binding.

Short answer

Diagnostic: Cannot access '__vi_import_0__' before initialization

As of November 2026, this card targets Vitest 5.1.1. The method cannot be mocked from outside because it is referenced directly; the outside mock does not affect the internal call. The guide calls this intended behavior and recommends separate files or dependency injection (source). The June 26, 2023 discussion describes the same boundary.

Choose / don't choose

  • Extracted module: choose when the helper is a reusable dependency; mock the exact module the caller imports.
  • Dependency parameter: choose for a small explicit seam or per-case behavior without module registry state. Pass a vi.fn() and assert its calls (source).
  • Whole behavior: choose assertions on the public caller when its internal helper is not a meaningful independent dependency.

Not for: standalone mock-factory initialization diagnostics; see why-does-my-vitest-mock-throw-before-the-test-file-finishes.

Settings that matter

Setting or flagValue / defaultApplies toSource
vi.mock(import(...), factory)Return { helper: vi.fn() } for the extracted dependency module; register the exact imported pathVitest 5.1.0 transformed test modulessource
importOriginalIt is asynchronous and must be awaitedVitest 5.1.0 async mock factorysource
vi.hoistedInitialize shared factory state here, before imports; do not read imported bindings inside its callbackVitest 5.1.0 module runnersource
vi.fn()Pass as an explicit dependency when injection is appropriate; define per-test behavior and inspect its callsVitest 5.1.0 mock functionssource

Order of operations

1. Extract the helper and change the original caller to import it. Mocking an unused module does not change an existing same-file call. 2. For partial replacement, use this factory pattern (source):

const mocks = vi.hoisted(() => ({ helper: vi.fn() }))
vi.mock(import("./dependency.js"), async (importOriginal) => ({
  ...await importOriginal(),
  helper: mocks.helper,
}))

3. The hoisted vi.mock call executes before all imports. Set fake behavior before invoking the caller. The API notes that hoisting is unavailable when the module runner is disabled (source). 4. Assert the caller's output and the fake's arguments. With injection, pass the fake explicitly and keep the module mock out of that test.

Known failures and fixes

Error or symptomCauseFixSource
Original helper still runs (symptom)The method cannot be mocked from outside because it is referenced directlyExtract the imported dependency or inject a callable; the outside mock does not affect the internal callsource
Cannot access '__vi_import_0__' before initializationHoisted code reads an import before initializationCreate plain shared mock state in vi.hoisted; avoid imported values theresource

Missing

  • Extraction only helps if the caller actually imports the extracted helper. Partial-mocking the original module does not redirect its internal calls.
  • Factory originals still execute when importOriginal() is awaited; avoid that route when its top-level side effects must not run.

Checked

2026-11-18; linked sources read. No application commands executed.

Started from a post by @Vitest, packaged by the editor. Original post

Subjects

More in testing

For agents

Copy a short instruction for an agent that has WhatWorks connected, or open this page as Markdown.

# Vitest: extract or inject same-module mock dependencies
Summary: An exported helper called through a local binding stays original when another export calls it. Move the dependency across an import boundary or pass a fake explicitly. Use `vi.mock`
Copy for agent
get the whatworks thread vitest-same-module-direct-call-extract-or-inject and help me try it

Follow this thread

Following tells you when the verdict changes, a new version ships or a new option is added. Your agent mentions it the next time you ask WhatWorks.

Sign in with GitHub to follow. Nothing is posted for you.

Sign in with GitHub

Or ask your agent
follow the whatworks thread vitest-same-module-direct-call-extract-or-inject
WhatWorks

Connect your agent MCP

Paste this into your agent

Connect me to WhatWorks: add https://whatworks.dev/mcp/login and sign me in so I have an account. Steps: https://whatworks.dev/connect.md.

Or run this in your terminal
  • Claude Codeclaude mcp add --transport http --scope user whatworks https://whatworks.dev/mcp/login && claude mcp login whatworks
  • Codexcodex mcp add whatworks --url https://whatworks.dev/mcp/login && codex mcp login whatworks