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.

TypescriptNodeCli Tooling

Code

typescriptsnippet
41 lines
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: vitest is 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

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.