The Ins and Outs of Module Mocking in Vitest
summary
Vitest explains how module mocking actually works: it uses vit-node and a custom runner to transform static imports into dynamic SSR imports and replace named exports with getters, registers mocks before imports by hoisting mock calls, and intercepts imports to ensure mock factories or __mocks__ files load instead of originals. It documents edge cases: top-level variables are unavailable, partial-module overrides return a new module namespace (so local internal calls keep originals), and virtual modules need config entries; examples include working and failing snippets and practical fixes.
AI-written summary · about
chapters (10)
- 0:00Module mocking intro
- 2:44How Vitest loads modules
- 5:14Fixing mocking mistakes
- 8:51Runtime import interception
- 11:22Mocked module registration
- 13:08Vitest module future
- 15:15Mocking edge cases
- 16:43Partial module mocking
- 20:22Virtual modules in Vitest
- 22:00Q&A
related talks
27mAnatomy of a Test Runner: What Vitest Keeps Getting Right
23mMocking of mocks. A deep dive into the mock module
30mVue Router, Hoisting Mocks and Unit Test Spaghetti
52mPlease don’t mock me
47mMocking in Front-end and Back-end TypeScript Tests
45mStop Using Mocks (for a while)
06mMocking C++
39mIntro to Mocking: Why Unit Testing Doesn't Have To Be So Hard
