Tutorial

Testing Strategies: Unit, Integration, and E2E

Structure your tests across the test pyramid: fast unit tests, contract-driven integration tests, and few high-value end-to-end tests in CI.

On this page

  1. Introduction
  2. The Test Pyramid
  3. Unit Tests: Fast, Isolated, Deterministic
  4. What to Mock and What Not to Mock
  5. Integration Tests: Verifying Composition
  6. End-to-End Tests: Few, High-Value, Resilient
  7. CI: Fast Feedback and Trust
  8. Snapshot Testing: Use and Abuse, and Property-Based Testing
  9. Conclusion

Introduction

A test suite is a safety net, and like any net it is only as good as its weave. A suite of a thousand unit tests and no integration tests passes happily while the application is broken, because each unit works in isolation but the units do not compose. A suite of a hundred end-to-end tests is slow, flaky, and impossible to localize when it fails. The testing strategy that actually catches bugs before users do is shaped like a pyramid: many fast, cheap unit tests at the base; a smaller layer of integration tests that verify the units compose; and a small apex of end-to-end tests that verify the user-visible flows. This article covers how to build each layer, what to mock and what not to, and how to keep the suite fast and trustworthy in CI.

The Test Pyramid

The pyramid is a ratio, not a count. The base is wide because unit tests are cheap — they run in milliseconds, they localize failures to a single function, and you can have thousands of them without slowing the feedback loop. The apex is narrow because end-to-end tests are expensive — they start a browser, hit a database, and take seconds each, so a hundred of them is a suite that takes ten minutes and flakes on a slow CI runner. The middle layer, integration tests, is where most teams underinvest: they are fast enough to run on every commit and they catch the composition bugs that unit tests cannot.

The anti-patterns are the ice cream cone (few unit tests, many E2E tests) and the hourglass (many unit tests, many E2E tests, no integration tests). Both produce slow, flaky suites that developers learn to ignore. The fix is to push tests down the pyramid: every test that can be a unit test should be, and every E2E test that is really verifying a unit should become one.

Unit Tests: Fast, Isolated, Deterministic

A unit test exercises a single function or module in isolation, with its dependencies replaced by test doubles. It should run in under ten milliseconds, produce the same result on every run, and fail with a message that points at the exact assertion. The determinism rule is the one most often broken: a test that depends on the current time, a random number, or the order of a hash map will pass on your machine and fail on CI. Inject the non-determinism — pass a clock, seed the RNG, use sorted assertions — so the test controls its inputs entirely.

import { describe, it, expect } from "vitest";
import { formatPrice } from "./format";

describe("formatPrice", () => {
  it("formats USD with two decimals and the symbol", () => {
    expect(formatPrice(1234.5, "USD")).toBe("$1,234.50");
  });
  it("returns zero for negative amounts", () => {
    expect(formatPrice(-10, "USD")).toBe("$0.00");
  });
  it.each([[0, "USD", "$0.00"], [1, "JPY", "¥1"], [99.999, "EUR", "€100.00"]])(
    "formatPrice(%d, %s) === %s",
    (amount, currency, expected) => expect(formatPrice(amount, currency)).toBe(expected),
  );
});

The it.each table is a unit-test workhorse: it documents the boundary cases inline and produces a separate, named assertion for each row, so a failure tells you exactly which input broke. Test the boundaries — zero, negatives, empty strings, the maximum value, off-by-one — because those are where the bugs live. A test that only verifies the happy path is a test that verifies nothing about the edges.

What to Mock and What Not to Mock

Mocking is a tool with a cost: every mock is a claim about how the dependency behaves, and if the claim is wrong the test passes against a fiction. The rule is to mock external, slow, or non-deterministic dependencies (the network, the filesystem, the clock, random) and to use the real implementation for everything else. A pure function that formats a price needs no mocks. A function that fetches a price from an API should mock the HTTP call, not the price formatter it composes.

import { vi } from "vitest";

it("returns cached price when the API fails", async () => {
  const api = { fetch: vi.fn().mockRejectedValue(new Error("network")) };
  const cache = { get: vi.fn().mockResolvedValue(42) };
  const service = new PriceService(api, cache);
  expect(await service.get("AAPL")).toBe(42);
  expect(api.fetch).toHaveBeenCalledOnce();
  expect(cache.get).toHaveBeenCalledWith("AAPL");
});

Prefer fakes over mocks where possible. A fake is a real, in-memory implementation of an interface (an in-memory repository instead of a mocked database); it behaves like the real thing without the cost, and it does not encode assumptions about call sequences that drift as the implementation changes. A mock that asserts the database was called exactly once breaks the moment you add a cache; a fake does not.

Integration Tests: Verifying Composition

An integration test verifies that units compose correctly, using real implementations for as many components as possible and replacing only the outermost boundaries (the HTTP client, the database) with fakes or a test instance. This is the layer that catches the bug where the service returns a number and the formatter expects a string, or where the API sorts ascending and the UI assumes descending. Use a real database in a test schema or a test container (Testcontainers spins a real Postgres in a Docker container per test run) rather than a mock, so you catch SQL and migration bugs that a mock hides.

import { buildApp } from "./app";
import { createTestDb } from "./test/db";

describe("POST /users integration", () => {
  let app: ReturnType<typeof buildApp>;
  let db: Awaited<ReturnType<typeof createTestDb>>;

  beforeAll(async () => {
    db = await createTestDb();
    app = buildApp({ db });
  });
  afterAll(() => db.close());

  it("creates a user and returns 201 with the id", async () => {
    const res = await app.request("/users", { method: "POST", body: JSON.stringify({ email: "[email protected]" }) });
    expect(res.status).toBe(201);
    const { id } = await res.json();
    const found = await db.users.findById(id);
    expect(found?.email).toBe("[email protected]");
  });
});

The integration test uses the real app, the real database, and the real request pipeline; it fakes nothing except the external world. It is slower than a unit test (it hits a database) but far faster than an E2E test (it does not start a browser), and it catches the composition bugs that matter.

End-to-End Tests: Few, High-Value, Resilient

An E2E test drives a browser through a user-visible flow: log in, add an item to the cart, check out, see the confirmation. These tests are the most valuable (they verify the whole system from the user’s perspective) and the most expensive (they are slow and flaky). Keep them few and focused on the critical paths — the signup funnel, the payment flow, the core feature — not on every button. A suite of twenty E2E tests on the critical paths catches the regressions that matter; a suite of two hundred E2E tests on every interaction is a maintenance nightmare.

import { test, expect } from "@playwright/test";

test("user can sign up and see the dashboard", async ({ page }) => {
  await page.goto("/signup");
  await page.getByLabel("Email").fill(`user-${Date.now()}@test.com`);
  await page.getByLabel("Password").fill("Sup3rSecret!");
  await page.getByRole("button", { name: "Create account" }).click();
  await expect(page.getByRole("heading", { name: "Welcome" })).toBeVisible();
  await expect(page).toHaveURL(/\/dashboard/);
});

Fight flakiness ruthlessly, because a flaky E2E test is worse than no test — it trains the team to ignore failures. Prefer getByRole and getByLabel over CSS selectors, because they survive refactors and they encode accessibility (a button you cannot find by role is a button a screen reader cannot find). Wait for the state you expect (expect(...).toBeVisible()) rather than sleeping, because a sleep is either too short (flaky) or too long (slow). Retry a genuinely flaky external dependency (a third-party auth provider) at the test level, but never at the assertion level — a retried assertion hides a real race.

CI: Fast Feedback and Trust

The test suite in CI is the gate that keeps broken code out of production. Run the unit and integration tests on every commit, in parallel, and fail the build on any failure. Run the E2E tests on pull requests and on merges to main, but not on every push to a feature branch — they are too slow for the inner loop. Use test splitting to parallelize the E2E suite across CI runners so a twenty-minute serial suite becomes a three-minute parallel one. Cache the dependencies and the browser binaries so CI does not reinstall them every run.

The most important property of the CI suite is trust: a failure must mean a real bug, and a pass must mean the code works. Flaky tests destroy trust — quarantine them immediately (move to a separate suite that does not gate the build) and fix or delete them within a sprint. A green build that everyone ignores is worse than no CI at all, because it provides the illusion of safety. Invest in determinism and the suite pays back in confidence for every deploy.

Snapshot Testing: Use and Abuse, and Property-Based Testing

Snapshot tests capture the output of a function or component at a point in time and fail when the output changes. They are fast to write — expect(output).toMatchSnapshot() — and they are seductive for that reason, but they are easy to misuse. A snapshot of a large object is a test that fails when anything changes, including changes that are correct, and the common response to a snapshot failure is to update the snapshot with --updateSnapshot without reading the diff. A snapshot that is updated without review is a snapshot that tests nothing — it asserts only that the output is whatever it is today.

Use snapshots for output that is large, stable, and meaningful to review: a serialized configuration, a generated AST, a rendered email template. Do not use them for output that is small enough to assert explicitly — expect(formatPrice(10, "USD")).toBe("$10.00") is a better test than a snapshot of the same value, because the assertion documents the expectation inline and fails with a clear message. Keep snapshots small by serializing only the relevant fields, not the entire object, so the diff is readable and the failure is localized. And never update a snapshot in CI without a human reading the diff — the --updateSnapshot flag is a local convenience, not a CI habit.

// A focused snapshot of a generated config, not the whole object.
expect(pick(generated, "routes", "redirects")).toMatchInlineSnapshot();
// Inline snapshots put the expected value in the test file, where the diff is visible in code review.

Inline snapshots (toMatchInlineSnapshot) are preferable to external snapshot files for small outputs, because the expected value lives in the test source and appears in the pull request diff, where a reviewer sees it. An external snapshot file is a separate file that a reviewer might not open; an inline snapshot is in the code they are already reading. Reserve external snapshots for outputs too large to inline readably.

Property-based testing is the complement to the example-based tests above. An example-based test asserts that a specific input produces a specific output; a property-based test asserts that a property holds for all inputs in a generated space. For a sort function, the property is “the output is in order” and “the output is a permutation of the input”; for a parse function, the property is “parsing a serialized value round-trips to the original.” The testing library generates hundreds of inputs and checks the property on each, and a failure produces a minimized counterexample that pinpoints the bug.

import { fc, testProp } from "@fast-check/vitest";

testProp("sort is idempotent", [fc.array(fc.integer())], (arr) => {
  return JSON.stringify(sort(sort(arr))) === JSON.stringify(sort(arr));
});

testProp("parse and serialize round-trip", [fc.anything()], (value) => {
  return deepEqual(parse(serialize(value)), value);
});

Property-based tests find the edge cases the examples miss: the empty array, the array with one element, the array of duplicates, the NaN, the nested object with a null. The minimization is the valuable part — when a property fails on a generated input of 47 elements, the library shrinks it to the smallest input that still fails (often 0 or 1 elements), which is the input that exposes the bug. Use property-based tests for pure functions with a clear invariant (sort, serialize, parse, normalize, format), and use example-based tests for the cases that document the behavior a reader needs to understand. The two together — examples for documentation, properties for coverage — are stronger than either alone.

The discipline with both snapshots and properties is to make the test assert something a human can reason about. A snapshot that is updated blindly and a property that holds vacuously (because the generator produces only trivial inputs) are both tests that pass and test nothing. Review the snapshots, tune the generators to produce realistic inputs, and the suite catches bugs rather than confirming assumptions.

Conclusion

A trustworthy test suite is shaped like a pyramid: many fast, deterministic unit tests at the base; a focused layer of integration tests that use real implementations and catch composition bugs; and a small, resilient set of end-to-end tests on the critical user paths. Mock only what is external, slow, or non-deterministic; prefer fakes over mocks; fight flakiness as a first-class concern; and keep the CI gate trustworthy by quarantining flakes. The reward is a suite that runs fast, fails meaningfully, and gives you the confidence to deploy on a Friday afternoon.

Related Examples