Which Vitest API is your favorite? There are so many great ones to choose from. test is a classic, vi.fn might have the best name, and expect is a great Swiss Army knife. Like a proud parent, I have trouble choosing my favorite. But I know which API I hate the most: vi.mock. It creates more confusion than clarity and encourages mocking that’s too broad and brittle for maintainable codebases.
Let me start with a confession: I am a recovering vi.mock abuser. I enjoy the mockist style of TDD, so naturally every time I needed to isolate my code from a dependency, I'd reach for that sledgehammer. After all, it says "mock" right on the tin, what's not to love?
But I've seen the light, and I'm here to show you why vi.spyOn should be your preferred choice. It's a sharper, safer tool that gives you precision without the pitfalls.
When you see vi.mock('./someModule') in a test file, it may look like a simple inline method call but under the hood your test runner is breaking the rules. Before a single line of code is executed, vitest pre-parses the test file and hoists all vi.mock(...) calls to the top. It then evaluates every vi.mock before any imports or any other code in the file has a chance to run. This behavior applies globally, affecting every test in the file.