vi.mock hoists. Your closure variables do not.
Blog post from Mergify
The text delves into the intricacies of handling mocks in Vitest, particularly focusing on the concept of hoisting and its implications on mock factories and test execution. It explains how Vitest's compiler hoists `vi.mock` calls to the top of the file, which can lead to ReferenceErrors when closure variables like `stubUser` are accessed before initialization. This behavior arises from the hoisting model inherited from Jest, where ESM imports are evaluated before any module-level code, necessitating mock registration prior to import resolution. The text provides solutions such as using `vi.hoisted()` to declare values that are hoisted alongside mocks, ensuring availability throughout the test file. It also highlights how Mergify's Test Insights can preemptively catch hoisting-related issues by tracking test reliability across different execution environments. The broader context includes various patterns in the flaky-tests-in-Vitest guide, emphasizing the balance between speed optimization and semantic clarity in testing.