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 by the Proxy in createCompilerHints at packages/mocker/src/browser/hints.ts:39-49. The _mocker() helper reads globalThis['__vitest_mocker__'] (or a configured key) and, if undefined, returns a Proxy that throws on any property access. This means a vi.* call was made in an environment where the Vitest mocker global was never injected by the transform plugin.

Source

Thrown at packages/mocker/src/browser/hints.ts:43

  unmock: (path: string | Promise<unknown>) => void
  doMock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void
  doUnmock: (path: string | Promise<unknown>) => void
  importActual: <T>(path: string) => Promise<T>
  importMock: <T>(path: string) => Promise<MaybeMockedDeep<T>>
}

export function createCompilerHints(options?: CompilerHintsOptions): ModuleMockerCompilerHints {
  const globalThisAccessor = options?.globalThisKey || '__vitest_mocker__'
  function _mocker(): ModuleMocker {
    // @ts-expect-error injected by the plugin
    return typeof globalThis[globalThisAccessor] !== 'undefined'
      // @ts-expect-error injected by the plugin
      ? globalThis[globalThisAccessor]
      : new Proxy(
          {} as any,
          {
            get(_, name) {
              throw new Error(
                'Vitest mocker was not initialized in this environment. '
                + `vi.${String(name)}() is forbidden.`,
              )
            },
          },
        )
  }

  return {
    hoisted<T>(factory: () => T): T {
      if (typeof factory !== 'function') {
        throw new TypeError(
          `vi.hoisted() expects a function, but received a ${typeof factory}`,
        )
      }
      return factory()
    },

View on GitHub (pinned to d568f8ce37)

Solutions

  1. Run the file through the Vitest CLI (vitest run / vitest) rather than node, so the mocker global is injected.
  2. If using a custom Vite plugin pipeline, ensure @vitest/mocker's plugin (or vitest's plugin) processes the file so globalThis.__vitest_mocker__ is defined.
  3. Avoid importing vi outside of test files executed by Vitest.

Example fix

// before: running directly
// $ node src/setup.test.js  -> throws vi.mock() is forbidden

// after
// $ vitest run src/setup.test.js
Defensive patterns

Strategy: validation

Validate before calling

// Guard vi usage to contexts where the mocker global is initialized.
const mockerKey = '__vitest_mocker__'
function mockerReady(): boolean {
  return typeof (globalThis as any)[mockerKey] !== 'undefined'
}

if (mockerReady()) {
  vi.mock('./logger')
} else {
  console.warn('vi not available here; run via vitest CLI')
}

Try / catch

// Catch the proxy-throw when vi is used outside Vitest, to degrade gracefully.
try {
  vi.mock('./logger')
} catch (e) {
  if (e instanceof Error && /mocker was not initialized/.test(e.message)) {
    // not running under vitest; skip mocking
  } else { throw e }
}

Prevention

When it happens

Trigger: Calling vi.mock/vi.hoisted/vi.fn etc. in a context where globalThis.__vitest_mocker__ is not set: a plain Node REPL, a script run with node rather than vitest, a browser iframe/worker spawned outside the Vitest harness, or a file that bypassed the Vitest Vite plugin transform.

Common situations: Running a test file directly with `node file.test.js`; importing vi from 'vitest' inside a server-side script or build step; using vi in setup files that load before the mocker global is installed; misconfigured environment where the hoistMocks plugin did not run.

Related errors


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