vitest-dev/vitest · error · Error

Vitest mocker was not initialized in this environment. vi.${

Error message

Vitest mocker was not initialized in this environment. vi.${String(name)}() is forbidden.

What it means

Thrown when any vi mocking method (mock, doMock, unmock, importActual, importMock, etc.) is accessed in a context where the Vitest mocker was never injected. The `_mocker()` helper returns a Proxy that throws on every property access whenever the global `__vitest_mocker__` symbol (injected by vite-node into the test runtime) is absent. This guards against silently using mocks outside a real Vitest worker.

Source

Thrown at packages/vitest/src/integrations/vi.ts:859

    },
  }

  return utils
}

export const vitest: VitestUtils = createVitest()
export const vi: VitestUtils = vitest

function _mocker(): VitestMocker {
  // @ts-expect-error injected by vite-nide
  return typeof __vitest_mocker__ !== 'undefined'
  // @ts-expect-error injected by vite-nide
    ? __vitest_mocker__
    : new Proxy(
        {} as any,
        {
          get(_, name) {
            throw new Error(
              'Vitest mocker was not initialized in this environment. '
              + `vi.${String(name)}() is forbidden.`,
            )
          },
        },
      )
}

function getImporter(name: string) {
  const stackTrace = createSimpleStackTrace({ stackTraceLimit: 5 })
  const stackArray = stackTrace.split('\n')
  // if there is no message in a stack trace, use the item - 1
  const importerStackIndex = stackArray.findLastIndex((stack) => {
    return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`) || stack.includes(` at ${name} (`)
  })
  const stack = parseSingleStack(stackArray[importerStackIndex + 1])
  return stack?.file || ''
}

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Move the vi.mock/doMock call into an actual test file executed by the Vitest runner, not into globalSetup/globalTeardown.
  2. If you need mocking in a setup file, use the `--setupFiles` runner path (which runs inside vite-node) rather than globalSetup.
  3. Run the file through `vitest run` / `vitest` instead of `node` or `tsx`.
  4. If writing a custom runner/integration, ensure the vite-node mocker plugin is registered so `__vitest_mocker__` is defined.

Example fix

// before (in vitest.config.ts globalSetup)
import { vi } from 'vitest'
export default function () { vi.mock('fs') }
// after (in a test file run by vitest)
import { vi, test } from 'vitest'
vi.mock('fs')
test('uses mocked fs', () => { /* ... */ })
Defensive patterns

Strategy: validation

Validate before calling

function isMockerAvailable(): boolean {
  // @ts-expect-error injected by vite-node
  return typeof globalThis.__vitest_mocker__ !== 'undefined'
}
if (!isMockerAvailable()) {
  throw new Error('vi mocking is only available inside the Vitest test runtime')
}

Try / catch

try {
  vi.mock('fs')
} catch (e) {
  if (e instanceof Error && e.message.includes('mocker was not initialized')) {
    // skip mock setup outside the test runtime
  } else { throw e }
}

Prevention

When it happens

Trigger: Importing and calling `vi` from a plain Node script, a REPL, a globalSetup/globalTeardown hook (which run in the main Node process, not in the vite-node test runtime), a Storybook preview, or any environment where Vite's transform pipeline and the mocker plugin have not run. Also triggered by custom runners that do not register the mocker global.

Common situations: Sharing a helper module between tests and a setup/teardown script that imports vi; running a file with `node` instead of `vitest`; using vi inside a worker pool that bypasses vite-node; upgrading Vitest and a setup file now runs in a context without mocker injection.


AI-assisted analysis of vitest-dev/vitest@d568f8ce37 (2026-08-03). Data as JSON: /data/errors/7830c7e76a0d09dc.json. Report an issue: GitHub.