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.*` mocker method (e.g. `vi.mock`, `vi.spyOn`, `vi.fn`) is called outside of a running Vitest test context. The `_mocker()` helper reads the global `__vitest_mocker__` symbol that vite-node injects into the test runtime; when that symbol is absent it returns a Proxy whose `get` trap throws on every property access. This means the `vi` object is structurally usable but its mocking surface is gated on the Vitest transform pipeline being active.

Solutions

  1. Run the file through the Vitest runner: `npx vitest path/to/test.ts` (or `pnpm test`) so vite-node injects `__vitest_mocker__`.
  2. Move any `vi.mock`/`vi.fn` calls out of shared library modules into actual `*.test.ts` files executed by Vitest.
  3. If you need Vitest's API programmatically outside a test, use `vitest/node` and start a `Vitest` instance via `createVitest`/`startVitest` rather than importing the user-facing `vi`.
  4. Confirm the file matches your `include` glob and is not being executed by a different test runner.

Example fix

// before (run with `node`/`tsx` — mocker global absent)
import { vi } from 'vitest'
vi.mock('fs')

// after (run with the Vitest CLI)
// package.json scripts: "test": "vitest"
// $ npx vitest run src/fs.test.ts
Defensive patterns

Strategy: validation

Validate before calling

// Only call vi.* when running under Vitest.
function isVitestEnv(): boolean {
  // vite-node injects this global when the mocker is active
  return typeof (globalThis as any).__vitest_mocker__ !== 'undefined'
    || typeof (globalThis as any).__vitest_worker__ !== 'undefined'
    || process.env.VITEST === 'true'
}

if (isVitestEnv()) {
  vi.mock('fs')
}

Type guard

// Guard the vi object before touching mocker methods.
function canUseViMocker(vi: unknown): vi is { mock: (...a: any[]) => unknown } {
  return typeof vi === 'object' && vi !== null
    && typeof (globalThis as any).__vitest_mocker__ !== 'undefined'
}

Prevention

When it happens

Trigger: Importing `vi` from `vitest` and calling `vi.mock(...)`, `vi.fn()`, `vi.spyOn(...)`, `vi.hoisted()` etc. in: (a) a plain Node script executed with `node`, (b) an integration test run through Jest/Mocha instead of Vitest, (c) a Vitest test file whose transform was bypassed (e.g. loaded via raw `require`/`import` in a worker not spawned by Vitest), or (d) top-level code in a module that gets imported by non-test tooling.

Common situations: Running a spec file directly with `node path/to/test.ts` instead of the `vitest` CLI; a shared utility module that imports `vi` and is consumed by both runtime code and tests; using `tsx`/`ts-node` to execute a file that references `vi`; Vitest 4 changes where mocker injection happens that surfaces previously-silent misuse.

Understand the failure class

Related errors


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

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