Why vi.mock in Vitest silently fails and how to fix it
A common Vitest pitfall causes mocks to silently fail when developers reference variables defined outside the vi.mock factory. This happens because Vitest hoists vi.mock calls to the top of the file during transformation, before any imports or variable declarations are executed. As a result, any variable referenced inside the factory does not yet exist at runtime, causing the mock to break without a clear error. The fix is to use vi.hoisted to create mock values in the same hoisted phase, or to define them directly inside the factory itself. Alternatively, developers can use vi.mocked inside individual tests to apply mock behavior without relying on shared variables.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.


Discussion (0)
Log in to join the discussion and vote.
Log in