Vitest Module Mock Unit Test
Isolate a module under test with Vitest vi.mock hoisting, typed mock functions, and restore between tests so suites stay order-independent.
Code
import { describe, it, expect, vi, beforeEach } from 'vitest';
const rateClient = {
async getRate(currency: string): Promise<number> {
throw new Error('real network call in unit test');
},
};
vi.mock('./rate-client', () => ({
rateClient: { getRate: vi.fn() },
}));
import { priceInUsd } from './pricing';
import { rateClient } from './rate-client';
vi.mocked(rateClient.getRate).mockResolvedValue(7.2);
describe('priceInUsd', () => {
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(rateClient.getRate).mockResolvedValue(7.2);
});
it('converts amounts using the fetched rate', async () => {
vi.mocked(rateClient.getRate).mockResolvedValue(7.2);
const result = await priceInUsd(100, 'eur');
expect(result).toBeCloseTo(720);
expect(rateClient.getRate).toHaveBeenCalledWith('eur');
});
it('rejects when the rate service fails', async () => {
vi.mocked(rateClient.getRate).mockRejectedValue(new Error('fx down'));
await expect(priceInUsd(100, 'eur')).rejects.toThrow('fx down');
});
it('caches repeat lookups within one call', async () => {
await priceInUsd(50, 'eur');
await priceInUsd(60, 'eur');
expect(rateClient.getRate).toHaveBeenCalledTimes(2);
});
});The path through the code
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. describe, it, expect, vi, beforeEach are the only symbols borrowed from vitest — the coupling is explicit and narrow. Error is not tied to any input check: it fires whenever execution reaches that line.
Everything operates on top-level bindings: rateClient.
Points of care
- Plan for an install step:
vitestis a real dependency, resolved by the package manager.
Statements that matter
await expect(priceInUsd(100, 'eur')).rejects.toThrow('fx down');
it('converts amounts using the fetched rate', async () => {
vi.mocked(rateClient.getRate).mockResolvedValue(7.2);
const result = await priceInUsd(100, 'eur');
expect(result).toBeCloseTo(720);
expect(rateClient.getRate).toHaveBeenCalledWith('eur');
});
it('caches repeat lookups within one call', async () => {
await priceInUsd(50, 'eur');
await priceInUsd(60, 'eur');
expect(rateClient.getRate).toHaveBeenCalledTimes(2);
});
Interactive Tools for This Topic
CSS Unit ConverterConvert a length between px, rem, em, pt, pc, in, cm, mm, and percent using a configurable root font size, following the 96dpi CSS definition.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Systemd Unit File GeneratorGenerate hardened systemd .service unit files ([Unit], [Service], [Install]) with security sandboxing presets, restart policies, and resource limits.
FAQ
- Does the code guard against bad input?
- The snippet does not validate input. `Error` is thrown unconditionally at its throw site — nothing guards it.
- Which packages must be installed first?
- Yes. The imports resolve to `vitest`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.