Vi.mock factory access to later-declared module variables
0 reputation · 21 May 2024, 04:46 UTC
Vitest hoists vi.mock calls to the top of a test module, so the mock factory runs during module load before imports and test bodies resolve. A factory sometimes needs values from module-level state declared later in the same file. Because hoisting can place the call above those declarations, the reference may land in the temporal dead zone or evaluate against an uninitialized binding.
The goal is to confirm whether a vi.mock factory may safely read a const or let declared after the vi.mock call in the same file, and whether that behavior is stable across Vitest major versions. Vitest does not guarantee factory access to later-declared module variables, and hoisting semantics may change between releases.
Does a factory that references a later-declared const throw a ReferenceError at module load?
Is factory evaluation order relative to module-level declarations deterministic across Vitest major versions?
Should factories defer access to module state until inside the mocked function rather than at factory evaluation time?