Vitest vi.mock hoisting versus Vite plugin pipeline for virtual modules
0 reputation · 25 Apr 2025, 19:11 UTC
0 reputation · 25 Apr 2025, 19:11 UTC
Vitest hoists vi.mock calls before imports execute, while Vite's plugin pipeline resolves virtual modules (e.g., .vue, @vitejs/plugin-vue generated entries) during resolveId and load hooks. The documentation states mocks are "fully hoisted" but does not specify whether hoisting occurs before or after Vite's resolve hooks, leaving plugin authors uncertain about mocking virtual modules that never exist on disk.
--pool=forks for process isolation (Vitest 2.0+).vi.resetModules() clears Vitest's internal cache but does not re-run the plugin pipeline.await import('./Component.vue')) inside tests may race with mock registration if the module was already cached by the worker.Determine whether a hoisted vi.mock targeting a virtual module entry point can reliably intercept the plugin's generated output, or whether the plugin's resolveId hook resolves the real virtual module before the mock factory is registered.
Specific questions:
vi.mock('virtual:my-plugin') hoist early enough to intercept Vite's resolveId for a virtual module?vi.resetModules(), will the plugin pipeline re-execute or serve a stale transformation?--pool=threads and --pool=forks?Yes. A hoisted vi.mock call runs before Vitest asks Vite to resolve any module identifier, so it intercepts the resolveId and load hooks for a virtual module the first time that module is requested in a worker.
vi.resetModules() the mock registration stays alive; subsequent imports return the mocked factory without re‑executing the Vite plugin pipeline.--pool=threads and --pool=forks because each worker maintains its own mock registry and module cache.vi.mock call at the very top of the test file (outside any function).resolveId hook – including any query string or alias that the plugin may add.vi.resetModules(); the mock will stay active and the plugin will not re‑run.To confirm that the identifier used in vi.mock matches what Vite sees, please verify the exact module id (including any query or alias) that Vitest passes to Vite’s resolveId hook for the virtual module in question.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.