{"record":{"id":"7830c7e76a0d09dc","repo":"vitest-dev/vitest","slug":"vitest-mocker-was-not-initialized-in-this-environm-7830c7","errorCode":null,"errorMessage":"Vitest mocker was not initialized in this environment. vi.${String(name)}() is forbidden.","messagePattern":"Vitest mocker was not initialized in this environment\\. vi\\.(.+?)\\(\\) is forbidden\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"packages/vitest/src/integrations/vi.ts","lineNumber":859,"sourceCode":"    },\n  }\n\n  return utils\n}\n\nexport const vitest: VitestUtils = createVitest()\nexport const vi: VitestUtils = vitest\n\nfunction _mocker(): VitestMocker {\n  // @ts-expect-error injected by vite-nide\n  return typeof __vitest_mocker__ !== 'undefined'\n  // @ts-expect-error injected by vite-nide\n    ? __vitest_mocker__\n    : new Proxy(\n        {} as any,\n        {\n          get(_, name) {\n            throw new Error(\n              'Vitest mocker was not initialized in this environment. '\n              + `vi.${String(name)}() is forbidden.`,\n            )\n          },\n        },\n      )\n}\n\nfunction getImporter(name: string) {\n  const stackTrace = createSimpleStackTrace({ stackTraceLimit: 5 })\n  const stackArray = stackTrace.split('\\n')\n  // if there is no message in a stack trace, use the item - 1\n  const importerStackIndex = stackArray.findLastIndex((stack) => {\n    return stack.includes(` at Object.${name}`) || stack.includes(`${name}@`) || stack.includes(` at ${name} (`)\n  })\n  const stack = parseSingleStack(stackArray[importerStackIndex + 1])\n  return stack?.file || ''\n}","sourceCodeStart":841,"sourceCodeEnd":877,"githubUrl":"https://github.com/vitest-dev/vitest/blob/1fa9837ec26533512fdcad8baebf249771bd340a/packages/vitest/src/integrations/vi.ts#L841-L877","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Run the file through the Vitest runner: `npx vitest path/to/test.ts` (or `pnpm test`) so vite-node injects `__vitest_mocker__`.","Move any `vi.mock`/`vi.fn` calls out of shared library modules into actual `*.test.ts` files executed by Vitest.","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`.","Confirm the file matches your `include` glob and is not being executed by a different test runner."],"exampleFix":"// before (run with `node`/`tsx` — mocker global absent)\nimport { vi } from 'vitest'\nvi.mock('fs')\n\n// after (run with the Vitest CLI)\n// package.json scripts: \"test\": \"vitest\"\n// $ npx vitest run src/fs.test.ts","handlingStrategy":"validation","validationCode":"// Only call vi.* when running under Vitest.\nfunction isVitestEnv(): boolean {\n  // vite-node injects this global when the mocker is active\n  return typeof (globalThis as any).__vitest_mocker__ !== 'undefined'\n    || typeof (globalThis as any).__vitest_worker__ !== 'undefined'\n    || process.env.VITEST === 'true'\n}\n\nif (isVitestEnv()) {\n  vi.mock('fs')\n}","typeGuard":"// Guard the vi object before touching mocker methods.\nfunction canUseViMocker(vi: unknown): vi is { mock: (...a: any[]) => unknown } {\n  return typeof vi === 'object' && vi !== null\n    && typeof (globalThis as any).__vitest_mocker__ !== 'undefined'\n}","tryCatchPattern":null,"preventionTips":["Run spec files only through the Vitest CLI or programmatic Vitest API.","Keep `vi` imports inside `*.test.ts` files, never in shared runtime modules.","Tag shared utilities with a clear comment that they must not reference `vi`."],"tags":["mocker","vi","runtime-context","vite-node","environment"],"backgroundTag":null,"analyzedSha":"1fa9837ec26533512fdcad8baebf249771bd340a","analyzedAt":"2026-08-11T16:11:39.638Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}