{"id":"8fc388d0474e4caf","repo":"vitest-dev/vitest","slug":"vitest-mocker-was-not-initialized-in-this-environm","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/mocker/src/browser/hints.ts","lineNumber":43,"sourceCode":"  unmock: (path: string | Promise<unknown>) => void\n  doMock: (path: string | Promise<unknown>, factory?: ModuleMockOptions | ModuleMockFactoryWithHelper) => void\n  doUnmock: (path: string | Promise<unknown>) => void\n  importActual: <T>(path: string) => Promise<T>\n  importMock: <T>(path: string) => Promise<MaybeMockedDeep<T>>\n}\n\nexport function createCompilerHints(options?: CompilerHintsOptions): ModuleMockerCompilerHints {\n  const globalThisAccessor = options?.globalThisKey || '__vitest_mocker__'\n  function _mocker(): ModuleMocker {\n    // @ts-expect-error injected by the plugin\n    return typeof globalThis[globalThisAccessor] !== 'undefined'\n      // @ts-expect-error injected by the plugin\n      ? globalThis[globalThisAccessor]\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\n  return {\n    hoisted<T>(factory: () => T): T {\n      if (typeof factory !== 'function') {\n        throw new TypeError(\n          `vi.hoisted() expects a function, but received a ${typeof factory}`,\n        )\n      }\n      return factory()\n    },\n","sourceCodeStart":25,"sourceCodeEnd":61,"githubUrl":"https://github.com/vitest-dev/vitest/blob/d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09/packages/mocker/src/browser/hints.ts#L25-L61","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Run the file through the Vitest CLI (vitest run / vitest) rather than node, so the mocker global is injected.","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.","Avoid importing vi outside of test files executed by Vitest."],"exampleFix":"// before: running directly\n// $ node src/setup.test.js  -> throws vi.mock() is forbidden\n\n// after\n// $ vitest run src/setup.test.js","handlingStrategy":"validation","validationCode":"// Guard vi usage to contexts where the mocker global is initialized.\nconst mockerKey = '__vitest_mocker__'\nfunction mockerReady(): boolean {\n  return typeof (globalThis as any)[mockerKey] !== 'undefined'\n}\n\nif (mockerReady()) {\n  vi.mock('./logger')\n} else {\n  console.warn('vi not available here; run via vitest CLI')\n}","typeGuard":null,"tryCatchPattern":"// Catch the proxy-throw when vi is used outside Vitest, to degrade gracefully.\ntry {\n  vi.mock('./logger')\n} catch (e) {\n  if (e instanceof Error && /mocker was not initialized/.test(e.message)) {\n    // not running under vitest; skip mocking\n  } else { throw e }\n}","preventionTips":["Always run test files through the vitest CLI, never node directly.","Do not import vi from 'vitest' in build scripts, servers, or REPL sessions.","If integrating Vitest programmatically, ensure the mocker plugin processes the file before execution."],"tags":["mocker","environment","initialization","globalthis"],"analyzedSha":"d568f8ce3739b532d5bf2c1ee1e45e8a8a473d09","analyzedAt":"2026-08-03T20:23:56.861Z","schemaVersion":2}