読み物Testing

Level: Intermediate

Unit Testing in Real Applications: Mocks, Stubs, Fixtures, and Code Coverage

Test code that talks to clocks, email, and databases: dependency injection, stubs, spies, mocks, and fakes, fake timers, fixtures, and what code coverage does and doesn't tell you.

Edeeson Opina8 min read

An Intermediate lesson card: lesson 6 of the Software Testing & Quality Engineering series, Unit Testing in Real Applications: Mocks, Stubs, Fixtures, and Code Coverage, with the Miso fox at work.

What you’ll learn

  • Design code so dependencies can be replaced in tests
  • Choose between stubs, spies, mocks, and fakes
  • Control time with fake timers
  • Read coverage reports and use them as a flashlight, not a target
On this page
  1. Before you start
  2. The problem: dependencies
  3. Test doubles
  4. Testing with a spy and a fixed clock
  5. Fake timers
  6. Module mocks: use sparingly
  7. Fakes: simpler than mocks for stateful dependencies
  8. Fixtures and test data
  9. Code coverage
  10. What coverage does and doesn't tell you
  11. Avoiding brittle tests
  12. Common mistakes and troubleshooting
  13. Practical exercise: test code with dependencies
  14. Key takeaways
  15. References
  16. What's next

Real application code rarely looks like the pure cartTotal function from lesson 4. It reads the current time, sends emails, calls payment APIs, and writes to databases. Testing it means controlling those dependencies so tests are fast, repeatable, and don't email real customers. This lesson covers test doubles (stubs, spies, mocks, and fakes) and when each helps, controlling time with fake timers, organizing test data with fixtures, measuring code coverage, and the habits that keep tests from becoming brittle. All output is real, from Vitest 5.

Before you start

You should have written and run Vitest tests in Writing Your First Automated Unit Tests with TypeScript and Vitest, and know about regression tests from lesson 5.

The problem: dependencies

Here's a function that sends class reminders:

src/reminders.tsTypeScript
export type Mailer = { send(to: string, subject: string): Promise<void> };
export type Booking = { email: string; startsAt: Date; reminded: boolean };

/** Sends one reminder for each booking that starts within the next 24 hours. Returns how many were sent. */
export async function sendReminders(bookings: Booking[], mailer: Mailer, now: Date = new Date()): Promise<number> {
  const dayAhead = now.getTime() + 24 * 60 * 60 * 1000;
  let sent = 0;
  for (const booking of bookings) {
    if (booking.reminded) continue;
    const start = booking.startsAt.getTime();
    if (start > now.getTime() && start <= dayAhead) {
      await mailer.send(booking.email, "Your class is tomorrow");
      booking.reminded = true;
      sent += 1;
    }
  }
  return sent;
}

Two dependencies would make it hard to test: the mailer (we don't want to send real emails) and the current time (a test that depends on today's date passes today and fails tomorrow). Notice how the function is written to make testing possible: the mailer is passed in as a parameter (dependency injection), and now has a default but can be supplied. Designing for testability like this is often the most important step.

Test doubles

A test double stands in for a real dependency during a test. The vocabulary, popularized by Gerard Meszaros:

  • A dummy is passed but never used, just to fill a parameter.
  • A stub returns canned answers: "the exchange rate is always 1.25."
  • A spy records how it was called, so you can check afterwards.
  • A mock is a spy with expectations about the calls it should receive.
  • A fake is a working, simplified implementation, such as an in-memory repository instead of a database.

In Vitest, vi.fn() creates a function that is both a stub (you can set what it returns) and a spy (it records calls).

Testing with a spy and a fixed clock

src/reminders.test.tsTypeScript
import { beforeEach, describe, expect, it, vi } from "vitest";
import { sendReminders, type Booking } from "./reminders";

const at = (iso: string) => new Date(iso);
const booking = (startsAt: string, reminded = false): Booking => ({ email: "ada@example.test", startsAt: at(startsAt), reminded });

describe("sendReminders", () => {
  const mailer = { send: vi.fn(async () => {}) };
  beforeEach(() => mailer.send.mockClear());

  it("emails bookings starting within 24 hours, once", async () => {
    const bookings = [booking("2026-11-02T08:00:00Z"), booking("2026-11-05T08:00:00Z")];
    const now = at("2026-11-01T09:00:00Z");

    expect(await sendReminders(bookings, mailer, now)).toBe(1);
    expect(mailer.send).toHaveBeenCalledExactlyOnceWith("ada@example.test", "Your class is tomorrow");

    // A second run must not email the same person again.
    expect(await sendReminders(bookings, mailer, now)).toBe(0);
    expect(mailer.send).toHaveBeenCalledTimes(1);
  });

  it("skips bookings that already started", async () => {
    expect(await sendReminders([booking("2026-11-01T08:00:00Z")], mailer, at("2026-11-01T09:00:00Z"))).toBe(0);
    expect(mailer.send).not.toHaveBeenCalled();
  });
});

The mailer is a spy: the test checks *that* an email was requested, to whom, and how many times, without sending anything. Time is passed explicitly, so the test gives the same result every day. mockClear() in beforeEach resets recorded calls, so tests don't affect each other.

Fake timers

When code reads the clock itself, vi.useFakeTimers() replaces the system time and timers for the test:

TypeScript
import { afterEach, beforeEach, expect, it, vi } from "vitest";

beforeEach(() => vi.useFakeTimers());
afterEach(() => vi.useRealTimers());

it("uses the current time by default", async () => {
  vi.setSystemTime(new Date("2026-11-01T09:00:00Z"));
  const mailer = { send: vi.fn(async () => {}) };
  expect(await sendReminders([booking("2026-11-02T09:00:00Z")], mailer)).toBe(1);
});

Fake timers also let you skip ahead with vi.advanceTimersByTime(60_000) instead of waiting for a real minute, which keeps tests fast. Always restore real timers afterwards.

Module mocks: use sparingly

vi.mock("./payments") replaces a whole imported module. It's handy for code you can't restructure, but it couples tests to file layout and hides dependencies. Prefer passing dependencies in. When you do mock a module, mock the boundary to the outside world (an HTTP client, a payment SDK), not your own internal helpers.

Fakes: simpler than mocks for stateful dependencies

When a dependency has state, a fake is often clearer than a stack of mocks. An in-memory repository that behaves like the real one makes tests read naturally:

src/fake-bookings.tsTypeScript
import type { Booking } from "./reminders";

export class InMemoryBookings {
  private rows: Booking[] = [];
  add(booking: Booking) { this.rows.push(booking); }
  upcoming(now: Date) { return this.rows.filter((row) => row.startsAt > now); }
}

A fake must behave like the real thing in the ways your code relies on. Integration tests (lesson 7) check the real implementation, so the fake can't drift silently.

Fixtures and test data

A fixture is the fixed state a test starts from: data, objects, files, or a configured environment. Good fixtures are:

  • Minimal: only the data this test needs, so the reader sees what matters.
  • Explicit: built in the test or by small, named helpers, not hidden in a 500-line shared file.
  • Independent: each test gets its own, so order doesn't matter.

Small builder functions like booking() above keep tests short while letting each test override what it cares about. Vitest also supports fixtures with test.extend, which creates a fresh value for each test that uses it:

src/fixtures.tsTypeScript
import { test as base } from "vitest";
import { InMemoryBookings } from "./fake-bookings";

export const test = base.extend<{ bookings: InMemoryBookings }>({
  bookings: async ({}, use) => {
    await use(new InMemoryBookings()); // a new, empty repository for every test
  },
});

Code coverage

Code coverage measures which code ran during the tests. Vitest supports it through the V8 engine's built-in coverage:

Shell
npm install --save-dev @vitest/coverage-v8
npx vitest run --coverage

For the cart and reminder modules, with the tests from lessons 4 and 6:

Text
 % Coverage report from v8
No files with missing coverage.
2 files fully covered.

=============================== Coverage summary ===============================
Statements   : 100% ( 14/14 )
Branches     : 100% ( 9/9 )
Functions    : 100% ( 3/3 )
Lines        : 100% ( 12/12 )
================================================================================

The metrics:

  • Statements and lines: how much of the code ran.
  • Branches: whether both sides of each if, ? :, and && ran. Branch coverage is usually the most informative.
  • Functions: how many functions were called at least once.

What coverage does and doesn't tell you

Coverage is good at showing what's not tested: an uncovered branch is a behavior no test checks. It can't tell you whether the covered code is tested well. Every line above ran, and yet a defect can still slip through: no test checks a booking that starts at exactly the current time. Lesson 13 runs a mutation testing tool on this very file and shows the gap that 100% coverage hides.

So use coverage as a flashlight, not a target. A sensible approach: look at uncovered code in each change during review, and set a modest threshold that blocks big drops rather than chasing 100%:

vitest.config.tsTypeScript
import { defineConfig } from "vitest/config";

export default defineConfig({
  test: {
    coverage: {
      provider: "v8",
      include: ["src/**/*.ts"],
      thresholds: { branches: 80, lines: 85 },
    },
  },
});

When a team makes coverage percentage a goal, people write tests that execute code without asserting anything useful, and the number goes up while confidence doesn't.

Avoiding brittle tests

A brittle test fails when the code changes in harmless ways. The most common causes:

  • Over-mocking: mocking every collaborator, so the test restates the implementation. Refactor the code and every test breaks, though behavior didn't change.
  • Asserting on internals: private methods, call order that doesn't matter, exact log messages.
  • Shared mutable fixtures: one test changes data another test relies on.
  • Real time, randomness, or network: tests that pass or fail depending on the day or the connection.

A good rule: mock what you don't own and can't control (email providers, payment gateways, the clock), and use real objects for your own code wherever practical.

Common mistakes and troubleshooting

  • Mocking the thing you're testing. Then the test checks the mock.
  • Forgetting to reset mocks. Calls leak between tests. Use mockClear() in beforeEach, or enable clearMocks in the config.
  • Leaving fake timers on. Later tests hang or behave oddly. Restore them in afterEach.
  • Chasing 100% coverage. Review uncovered branches instead.
  • Fakes that differ from the real thing. Back them with integration tests.
  • "Cannot redefine property" or mocks not applying. vi.mock calls are hoisted to the top of the file; module mocks must be declared at the top level, not inside tests.

Practical exercise: test code with dependencies

  1. Write a chargeBooking(booking, paymentGateway, clock) function that refuses to charge a booking whose class started more than an hour ago.
  2. Test it with a stub gateway that returns success, and a spy that checks the amount charged.
  3. Add a test where the gateway throws, and check the booking isn't marked as paid.
  4. Replace the passed-in clock with fake timers in one test, and restore real timers afterwards.
  5. Run coverage, find any uncovered branch, and write the test that covers it.
  6. Refactor the function's internals without changing behavior. Did any test break? If so, it was testing implementation details.

Key takeaways

  • Design code so dependencies are passed in; it makes testing straightforward.
  • Stubs return canned answers, spies record calls, mocks expect calls, fakes are simple working implementations.
  • Control time with explicit parameters or fake timers; never depend on the real clock.
  • Keep fixtures minimal, explicit, and independent.
  • Coverage shows what's untested, not how well the rest is tested. Use it as a flashlight, not a target.
  • Mock what you don't own; prefer real objects for your own code.

References

What's next

Fakes and mocks stop at your code's boundary. Integration Testing: APIs, Databases, and Real Application Dependencies tests across it, with real databases and services.

See every lesson in Software Testing & Quality Engineering: From Fundamentals to Production-Ready Software