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

In the browser environment, `vi.*` calls are routed through a global mocker object injected by the Vitest plugin. If that object was never set (e.g. the plugin did not transform this file or the environment is not a Vitest browser test), the code returns a Proxy that throws on any property access, producing this message naming the attempted `vi.<name>()`.

Solutions

  1. Run the file through `vitest` (browser mode) so the mocker global is injected.
  2. Ensure `@vitest/browser` is configured and the project uses the browser environment.
  3. Move `vi.*` calls so they only execute during a test, not at module import time.
  4. Guard code that may run outside tests behind a `if (import.meta.env?.MODE === 'test')` check.

Example fix

// before: module calls vi.mock at top level and is imported by a Node script
vi.mock('./db')

// after: keep vi usage inside test files only
// test.spec.ts
import { test } from 'vitest'
test('x', () => { /* vi.mock in test setup */ })
Defensive patterns

Strategy: validation

Validate before calling

if (typeof (globalThis as any).__vitest_mocker__ === 'undefined') {
  throw new Error('run this file under vitest browser mode')
}

Prevention

When it happens

Trigger: Calling `vi.mock`, `vi.fn`, etc. in a script that runs outside the Vitest browser test harness; importing a module that calls `vi.*` at load time in a non-test context; running code in Node that was built for the browser mocker.

Common situations: Execucting a test file with `node`/`tsx` directly instead of `vitest`; the Vitest browser plugin was not enabled in the Vite config; importing shared code that invokes `vi.*` outside of a test run.

Understand the failure class

Related errors


AI-assisted analysis of vitest-dev/vitest@1fa9837ec2 (2026-08-11). Data as JSON: /api/errors/8fc388d0474e4caf. Report an issue: GitHub.

Appendix: 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 1fa9837ec2)