JavaScript & TypeScript / Quiz
vi.mock: Hoisted, Async, and Unforgiving
vi.hoisted, importOriginal factories, the TDZ error that greets every Jest migrant, and where Vitest's __mocks__ rules differ.
- Difficulty
- Hard
- Format
- Quiz
- Points
- 200
- Estimate
- 11 min
// MISSION BRIEF
Your Mission
Vitest kept Jest's mental model, mock at the module boundary, but rebuilt it for an ESM world. The differences are small, sharp, and exactly where migrating teams bleed.
This quiz covers vi.mock's hoisting, the vi.hoisted escape hatch, async factories with importOriginal, importActual, and manual mock folder semantics.
Speed bonus active.
// FIRST CONTACT
Battle teaser
Like jest.mock, vi.mock('./api', factory) affects imports written above it. What makes that work in Vitest?
- AIt only works if the import uses require() syntax
- BVitest's transform hoists vi.mock calls to the top of the module before execution, so the mock registers before static imports are evaluated
- CESM import order is unspecified, so it works by luck
- Dvi.mock patches the live module namespace after import, retroactively
Answers, scoring, hints, and the full battle stay sealed.
// SKILL TAGS
typescriptvitestmockingmodulesunit-testing