Mocking isolates code components from external systems. By building spy functions, stubbing module exports, and configuring mock timers, developers control test environments.
testingmockingspiesstubsvitest-mockingjest-fn
Curated Video Reference
YouTube
Hand-picked video lecture to deepen your understanding of Mocking
To test code containing external side effects (like API requests, file saves, or analytics), we replace those dependencies with test doubles:
Spy (vi.fn()): A function wrapper that records execution history (arguments passed, return values, call counts) while letting the original code execute.
Stub: Replaces a function with a dummy implementation that returns static hardcoded data instantly, preventing network operations.
Mock: A mock object pre-programmed with specific behavioral expectations.
import { vi, test, expect } from 'vitest';import { sendAlert } from './alert';import { checkServerStatus } from './status';// 1. Mocking a module importvi.mock('./alert', () => ({ sendAlert: vi.fn() // Replaces function with a spy}));test('sends alert when status is offline', () => { // 2. Act checkServerStatus('offline'); // 3. Assert on the spy function expect(sendAlert).toHaveBeenCalledTimes(1); expect(sendAlert).toHaveBeenCalledWith('Server is offline!');});
If your module executes delay functions (like setTimeout) or evaluates date offsets, unit tests can become slow or pass/fail randomly based on execution times. Use mock timers:
Over-mocking makes tests useless. If you mock the internals of the class you are actively testing, your assertions verify your mock configuration rather than the production compiled code. Only mock boundaries (external API libraries, databases, disk filesystem writers).
Spy call histories (like toHaveBeenCalledTimes()) compile globally within test runner files. If you do not reset mock state caches after each test case runs, count histories leak across tests, leading to random failures:
// Prevent leak:afterEach(() => { vi.clearAllMocks(); // Resets call histories // or vi.resetAllMocks() to reset implementation too});