{"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/d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09/packages/vitest/src/integrations/vi.ts#L841-L877","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Move the vi.mock/doMock call into an actual test file executed by the Vitest runner, not into globalSetup/globalTeardown.","If you need mocking in a setup file, use the `--setupFiles` runner path (which runs inside vite-node) rather than globalSetup.","Run the file through `vitest run` / `vitest` instead of `node` or `tsx`.","If writing a custom runner/integration, ensure the vite-node mocker plugin is registered so `__vitest_mocker__` is defined."],"exampleFix":"// before (in vitest.config.ts globalSetup)\nimport { vi } from 'vitest'\nexport default function () { vi.mock('fs') }\n// after (in a test file run by vitest)\nimport { vi, test } from 'vitest'\nvi.mock('fs')\ntest('uses mocked fs', () => { /* ... */ })","handlingStrategy":"validation","validationCode":"function isMockerAvailable(): boolean {\n  // @ts-expect-error injected by vite-node\n  return typeof globalThis.__vitest_mocker__ !== 'undefined'\n}\nif (!isMockerAvailable()) {\n  throw new Error('vi mocking is only available inside the Vitest test runtime')\n}","typeGuard":null,"tryCatchPattern":"try {\n  vi.mock('fs')\n} catch (e) {\n  if (e instanceof Error && e.message.includes('mocker was not initialized')) {\n    // skip mock setup outside the test runtime\n  } else { throw e }\n}","preventionTips":["Keep vi.mock/doMock calls inside test files executed by the Vitest runner.","Do not import vi in globalSetup/globalTeardown or plain Node scripts.","Run files via `vitest`, not `node`/`tsx`."],"tags":[],"analyzedSha":"d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09","analyzedAt":"2026-08-03T20:23:56.861Z","schemaVersion":2}