Partial Mocks with vi.importActual()
You'll learn how to mock just one or two functions from a module while keeping everything else real.
The Problem with Full Mocks
When you call vi.mock('./utils'), Vitest replaces the entire module with mocks. Every function becomes undefined unless you explicitly define it. But what if you only need to fake one function while the rest should work normally?
The Solution: vi.importActual()
vi.importActual() lets you preserve the real module implementation, then selectively override specific exports. Think of it like replacing just one ingredient in a recipe while keeping the rest authentic.
// utils.ts has 10 functions, but you only want to mock fetchData
vi.mock('./utils', async () => {
const actual = await vi.importActual('./utils');
return {
...actual, // Spread the real implementation
fetchData: vi.fn(() => Promise.resolve({ id: 1 })), // Override just this one
};
});
Why This Matters
Without partial mocking, you'd either:
- Mock everything (tedious and brittle)
- Not mock at all (tests depend on real external calls)
With vi.importActual(), you get surgical precision. Your component uses real helper functions, real calculations, real utilities—except for that one API call you need to control.
Anatomy of a Partial Mock
vi.mock('./api', async () => {
const actual = await vi.importActual('./api');
return {
...actual,
postData: vi.fn(), // Mock only this
// fetchUser, deleteItem, etc. remain real
};
});
The await is crucial because module imports are asynchronous in Vitest's module system.
Key Takeaway: Use vi.importActual() to spread the real module implementation, then override only the exports you need to control—preserving authenticity while gaining testability.