vitest-mocking
Vitest mocking patterns and test double strategies. Use when writing tests that need mocks, spies, stubs, or fakes. Triggers include: mocking modules, stubbing globals (fetch, Date, timers), testing composables, mocking imports (default/named), creating test doubles, replacing dependencies, verifying mock calls, cleaning up mocks, or any question about "how do I mock X in Vitest". Also use when reviewing tests for proper mocking practices.
When & Why to Use This Skill
This Claude skill provides comprehensive Vitest mocking patterns and test double strategies to streamline unit testing and quality assurance. It empowers developers to effectively implement mocks, spies, stubs, and fakes, covering essential scenarios such as module mocking, global stubbing (fetch, Date, timers), and dependency replacement to ensure robust, isolated, and reliable test environments.
Use Cases
- Mocking external API calls and network requests using vi.mock or vi.stubGlobal to ensure fast and deterministic test execution without real network overhead.
- Utilizing spies (vi.spyOn) to track function interactions and verify that internal methods are called with the correct arguments while maintaining original behavior.
- Simulating time-sensitive operations with fake timers to test complex asynchronous logic, timeouts, and intervals without waiting for real-world time to pass.
- Isolating components or composables by replacing complex third-party imports or internal dependencies with controlled test doubles to focus on unit logic.
- Implementing proper test lifecycle management and cleanup strategies using clearAllMocks and restoreAllMocks to prevent state leakage between tests.
| name | vitest-mocking |
|---|---|
| description | | |
| Vitest mocking patterns and test double strategies. Use when writing tests that need mocks, spies, stubs, or fakes. Triggers include | mocking modules, stubbing globals (fetch, Date, timers), testing composables, mocking imports (default/named), creating test doubles, replacing dependencies, verifying mock calls, cleaning up mocks, or any question about "how do I mock X in Vitest". Also use when reviewing tests for proper mocking practices. |
Vitest Mocking
Test Double Types
| Type | Purpose | Changes Implementation? |
|---|---|---|
| Spy | Record calls, verify interactions | No (uses real code) |
| Mock | Replace module entirely | Yes |
| Stub | Return canned responses | Yes |
| Fake | Working but simplified impl | Yes |
Decision Guide
Use spy when: Verifying a function was called correctly while keeping real behavior
const fetchSpy = vi.spyOn(globalThis, "fetch");
await doSomething();
expect(fetchSpy).toHaveBeenCalledWith("https://api.example.com");
Use mock when: Replacing external dependencies (network, database, third-party modules)
vi.mock("./api-client");
vi.mocked(apiClient.fetch).mockResolvedValue({ data: "test" });
Use stubGlobal when: Replacing browser/Node globals
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(mockResponse));
Essential Patterns
Mock Module (hoisted)
import { someFunc } from "./module";
vi.mock("./module"); // hoisted to top
it("test", () => {
vi.mocked(someFunc).mockReturnValue("mocked");
});
Mock with Implementation
vi.mock("./module", () => ({
someFunc: vi.fn().mockReturnValue("mocked"),
}));
Spy with Fake Return
const spy = vi.spyOn(obj, "method").mockReturnValue("fake");
Mock Global Fetch
globalThis.fetch = vi.fn().mockResolvedValue({
ok: true,
json: async () => ({ data: "test" }),
} as Response);
Fake Timers
beforeAll(() => vi.useFakeTimers());
afterAll(() => vi.useRealTimers());
it("test", async () => {
// advance time
await vi.advanceTimersByTimeAsync(5000);
});
Clean Up
beforeEach(() => vi.clearAllMocks()); // reset call counts
afterEach(() => vi.restoreAllMocks()); // restore originals
Reference
For complete examples including default imports, named imports, classes, partial mocks, snapshot testing, composables, and verification patterns, see references/cheat-sheet.md.