Explain the testing pyramid: unit vs integration vs end-to-end tests.

3 minintermediatenodejstestingunitintegratione2e

Quick Answer

The testing pyramid recommends many fast, isolated unit tests at the base, fewer integration tests that check modules working together (e.g. route + DB), and a small number of slow end-to-end tests exercising the whole system. It balances confidence against speed and maintenance cost.

Detailed Answer

Answer: The testing pyramid is a guideline for how to distribute test types by quantity, based on their speed and cost.

        /\        E2E  (few)      slow, brittle, high confidence
       /  \
      /----\      Integration (some)
     /      \
    /--------\    Unit (many)     fast, isolated, cheap

Unit tests (base — many):

  • Test a single function/module in isolation, mocking its dependencies.
  • Fast (milliseconds) and deterministic; pinpoint failures.
test('calculateTotal applies discount', () => {
  expect(calculateTotal(100, 0.1)).toBe(90);
});

Integration tests (middle — some):

  • Test multiple units working together: a route handler + its service + a real (test) database, or a module + an external client.
  • Catch wiring/contract bugs unit tests miss (SQL, serialization, middleware order).

End-to-end tests (top — few):

  • Drive the whole system as a user would (HTTP in, DB and side effects real), sometimes through a browser (Playwright/Cypress).
  • Highest confidence but slow and brittle — keep them for critical happy paths.

Why the shape:

  • Fast unit tests give quick feedback and cheap coverage of logic/edge cases.
  • Too many E2E tests → slow suites and flaky CI.
  • A common modern variant is the "testing trophy," which weights integration tests more heavily because they catch realistic bugs at reasonable cost.

Rule of thumb: most logic covered by unit tests, key flows by integration tests, a handful of E2E for the money paths.