Skip to main content
CodingMarble

Programming fundamentals

The Software Testing Pyramid Explained With Examples

The testing pyramid is the idea that you should have many fast unit tests, fewer integration tests and only a small number of slow end-to-end tests, because cost and fragility rise as tests cover more of the system. It is a guide to balance, not a rule, and the right mix depends on where your application's real risk lives.

By CodingMarble · Published · 5 min read

A laptop turned on showing code
Photo: Andras Vas on Unsplash

Three layers of tests

A unit test checks one small piece of code, usually a function or a class, in isolation. It runs in milliseconds and needs no network, database or browser. An integration test checks that several pieces work together, for example that your route handler, your validation and your database layer cooperate to save an order. An end-to-end test, often shortened to E2E, drives the whole application the way a user would: it opens a browser, fills in a form, clicks a button and checks what appears.

Each layer catches different mistakes. Unit tests catch logic errors close to where they happen. Integration tests catch mismatches between parts, such as a field renamed on one side only. End-to-end tests catch the failures that only exist when everything is wired together: a missing environment variable, a broken button, a login that no longer redirects.

The pyramid idea and why it is shaped that way

Draw the three layers as a pyramid: a wide base of unit tests, a middle band of integration tests, and a narrow top of E2E tests. The shape reflects trade-offs. Tests lower down are faster, cheaper to write and easier to diagnose, since a failing unit test points at one function. Tests higher up give more realistic confidence but run slowly, depend on many moving parts and fail for reasons unrelated to the change, so a failure tells you less about where to look.

The pyramid is advice, not law. Some teams prefer a trophy shape with more integration tests, arguing that most real bugs live between components and that well-designed integration tests are still quick. An application that is mostly a thin layer over a database has little pure logic to unit test, so integration tests may be the more valuable base. A heavily algorithmic library is the opposite. Pick the shape by asking where your bugs would actually come from, and adjust when the failures you see do not match your tests.

What to test and what to leave alone

Test behaviour that matters and could plausibly break: business rules such as discounts and tax, input validation, permission checks, edge cases like empty lists and boundary values, and every bug you have fixed. Test through the public interface, what the function returns or what the user sees, rather than its internal steps. Tests tied to implementation details break whenever you refactor, even though nothing is wrong, and soon people stop trusting them.

Leave alone code that only forwards to a framework, trivial getters, and the internals of third-party libraries, which have their own tests. Do not write a test that merely restates the code line by line. A good test states a rule in terms a colleague would recognise and would fail if that rule were broken.

JavaScript· Unit tests in generic runner syntax: describe, it, expect
function applyCoupon(total, coupon) {
  if (total < 0) throw new Error("total cannot be negative");
  if (!coupon) return total;
  return Math.max(0, total - coupon.amountOff);
}

describe("applyCoupon", () => {
  it("returns the total unchanged when there is no coupon", () => {
    expect(applyCoupon(500, null)).toBe(500);
  });

  it("subtracts the coupon amount", () => {
    expect(applyCoupon(500, { amountOff: 100 })).toBe(400);
  });

  it("never goes below zero", () => {
    expect(applyCoupon(50, { amountOff: 100 })).toBe(0);
  });

  it("rejects a negative total", () => {
    expect(() => applyCoupon(-1, null)).toThrow("negative");
  });
});

Each case has a name that reads as a sentence, one clear expectation, and covers a boundary: no coupon, normal use, the floor at zero and invalid input. If one fails, the name already says which rule broke. The describe, it and expect functions exist in the common JavaScript runners, with small differences, so check the documentation of the one you use.

Test doubles: stubs, mocks and fakes

A test double is a stand-in for a real dependency such as a payment gateway, an email service or the clock. A stub returns canned answers: when asked for the exchange rate, it always says 80. A mock also records how it was called, so the test can assert that sendEmail was called once with a given address. A fake is a lightweight working version, such as an in-memory database that behaves like the real one without the setup. People use these words loosely, so what matters is the idea: replace the slow or unpredictable thing so the test is fast and deterministic.

JavaScript· Replace a slow dependency with a stub, and check a call with a mock
async function sendReceipt(order, mailer) {
  if (!order.email) return false;
  await mailer.send(order.email, "Receipt for " + order.id);
  return true;
}

it("sends one receipt to the customer", async () => {
  const calls = [];
  const fakeMailer = { send: async (to, subject) => calls.push({ to, subject }) };

  const sent = await sendReceipt({ id: "A1", email: "a@example.com" }, fakeMailer);

  expect(sent).toBe(true);
  expect(calls).toEqual([{ to: "a@example.com", subject: "Receipt for A1" }]);
});

it("skips orders without an email", async () => {
  const mailer = { send: async () => { throw new Error("should not be called"); } };
  expect(await sendReceipt({ id: "B2" }, mailer)).toBe(false);
});

The cost of doubles is that they can drift from reality. A mock that accepts anything will happily pass while the real service rejects the request. Keep a small number of integration tests that use the real dependency or its official test mode, so the doubles are checked against the truth somewhere. Also, mock at the boundary of your system, not everywhere. A test that mocks every collaborator ends up verifying the mocks.

Flaky tests and how to treat them

A flaky test passes and fails on the same code. The usual causes are timing, such as waiting a fixed number of seconds instead of waiting for a condition, shared state between tests, dependence on test order, real network calls, random data without a fixed seed, and clocks and time zones. Flakiness is corrosive because people learn to ignore red builds, and then real failures hide among the noise.

Treat a flaky test as a bug: reproduce it by running it many times, find the shared state or timing assumption, and fix it. Isolate tests so each sets up its own data and cleans up, wait for observable events rather than sleeping, and inject the clock and the random source so tests control them. Quarantining a test temporarily is acceptable if you track it and return to it, but deleting retries and leaving it red or ignored is how suites rot.

Coverage is a signal, not a goal

Code coverage reports which lines or branches ran during the tests. Low coverage in an important module is a useful warning that something is untested. High coverage proves much less than it appears to, because a test can execute a line without checking anything about its result. Once a percentage becomes a target, people write assertion-free tests to reach it, and the number stops meaning anything.

Practical tip: use the coverage report to find untested branches in code that matters, then read those lines and ask what could go wrong there. To check whether your tests are strong, deliberately break a rule in the code, for instance change a plus to a minus, and confirm that at least one test fails. If none does, the test suite would not notice that bug in real life.

A sensible balance for a small team is a base of fast unit tests for logic, integration tests for the main workflows against a real test database, and a handful of end-to-end checks for the journeys that must never break, such as sign in and checkout. Run the fast ones on every change and the slow ones before release, and review the mix whenever a production bug slips past it.

Need this built properly for your business?

CodingMarble is a remote studio in India that builds websites, apps and games on fixed packages with the scope written down before payment. Try the free tools we run, or start a project when you are ready.