{"record":{"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/1fa9837ec26533512fdcad8baebf249771bd340a/packages/mocker/src/browser/hints.ts#L25-L61","documentation":"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>()`.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Run the file through `vitest` (browser mode) so the mocker global is injected.","Ensure `@vitest/browser` is configured and the project uses the browser environment.","Move `vi.*` calls so they only execute during a test, not at module import time.","Guard code that may run outside tests behind a `if (import.meta.env?.MODE === 'test')` check."],"exampleFix":"// before: module calls vi.mock at top level and is imported by a Node script\nvi.mock('./db')\n\n// after: keep vi usage inside test files only\n// test.spec.ts\nimport { test } from 'vitest'\ntest('x', () => { /* vi.mock in test setup */ })","handlingStrategy":"validation","validationCode":"if (typeof (globalThis as any).__vitest_mocker__ === 'undefined') {\n  throw new Error('run this file under vitest browser mode')\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Run test files through vitest, not node/tsx.","Enable @vitest/browser and the mocker plugin in the Vite config.","Keep vi.* calls out of module top-level code imported by non-test scripts."],"tags":["mocker","browser","vi-mock","environment","proxy"],"backgroundTag":null,"analyzedSha":"1fa9837ec26533512fdcad8baebf249771bd340a","analyzedAt":"2026-08-11T16:11:39.638Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}