What you'll learn: By the end of this lesson you will be able to explain where the test pyramid and the testing trophy come from, say why the same word "integration" means different things in the two, describe what unit, component, integration and end-to-end tests can and cannot see, read a matrix of which layer catches which seeded bug, and choose a mix of layers for a front end by reasoning about confidence, cost and fragility instead of copying a ratio.
Think of a bakery that wants to be sure its bread is good. Tasting the dough is quick and tells you about the dough. Baking a test loaf tells you about the oven and the recipe together. Serving a customer tells you whether the whole shop works, but it is slow, depends on the weather and the customer, and when it goes wrong you still have to work out whether the dough, the oven or the till was to blame. A sensible baker does all three, in different amounts. A front-end team faces the same choice for its tests.
The running example is the checkout cart of the ShopStream grocery marketplace: a cart screen with line items, a total, a discount code and a Checkout button, which sends the order to an API.
The core idea
- Every test trades confidence against cost. A test that runs more of the real system can fail for more reasons, so it gives more confidence and costs more to write, run and debug.
- A layer is defined by what it runs for real and what it replaces. Unit tests replace nearly everything around one piece; end-to-end tests replace as little as possible. What a layer replaces is exactly what it cannot see.
- A shape (pyramid, trophy) is a starting hypothesis about the mix, not a rule. The useful skill is knowing which bug each layer is blind to, so you can place a check where it will notice.
Where the shapes come from
The pyramid. Martin Fowler's bliki entry says most people know the Test Pyramid through Mike Cohn, who described it in his 2009 book Succeeding with Agile under the name Test Automation Pyramid. Cohn's original layers, bottom to top, are unit tests, service tests and user interface tests. Fowler's practical guide states the rule: the more high-level you get, the fewer tests you should have. He gives the reason for the narrow top: tests that run end to end through the UI are brittle, expensive to write and time consuming to run.
Two further pieces of advice matter for front ends. Push your tests as far down the pyramid as you can: a low-level test is better than a high-level one. And if a higher-level test finds an error and no lower-level test fails, write a lower-level test. The bliki entry adds that teams often conflate end-to-end tests, UI tests and customer-facing tests, which it calls orthogonal characteristics: a test can drive the UI against a fake API without being end to end.
The ice-cream cone. The same entry names the inverted shape: a suite that is mostly slow, broad tests on top of few small ones "quickly runs into trouble, becoming an ice-cream cone".
The trophy. Kent C. Dodds' post on the testing trophy credits the line "Write tests. Not too many. Mostly integration." to Guillermo Rauch, who tweeted it on 10 December 2016. The trophy's levels, from the top, are end to end, integration, unit and static (the static level being checks that run without executing the code, such as types and linters). Dodds frames the choice as getting a good return on investment, where "return" is confidence and "investment" is time, and states his guiding principle: the more your tests resemble the way your software is used, the more confidence they can give you. The Testing Library project repeats that principle in its documentation.
Same word, different meanings. Fowler's guide defines integration tests as tests of the integration of your application with the parts that live outside it, such as a database or another service. Dodds defines a unit as a single function, class or object that contains logic, and integration tests as tests of several units working together. For a UI engineer, a test that renders a screen with its real child components and real state logic is an integration test in the trophy's sense and a "sociable unit test" in Fowler's vocabulary. When someone says "we need more integration tests", ask which meaning they use. This course uses the plain names below.
The four layers in this course
| Layer | What runs for real | What is replaced | What it cannot see |
|---|---|---|---|
| Static | Nothing runs; types and linters read the code | Everything | Wrong behaviour that is well typed |
| Unit | One function or module | Every collaborator, or nothing, if it has none | Whether the pieces fit together |
| Component | A screen or widget with its real logic and children | The network and other apps (stubbed or faked) | Whether the stub matches the real API |
| Integration | Several of your modules, such as a service layer, against a fake of one external part that enforces its contract | Everything outside that boundary | Wiring done only in the real application |
| End to end | The assembled application, built the way it ships | As little as possible (often third parties) | Bugs in code paths no scenario exercises |
Figure 1. The four parts of the cart and where each layer of test enters
How to read this: the cart has four pieces of your own code and one external part. A unit test calls the pricing functions directly. A component test renders the screen with a stub for the service. An integration test runs the service against the fake API. Only a test that builds the whole app reads the configuration box, which is why a mistake there is invisible to every lower layer.
Illustration 1: the minimal example
A unit check from the lab below, on the discount rule (ten percent off with the code SAVE10, the discount rounded half up):
assert.equal(s.pricing.applyDiscount(1995, "SAVE10"), 1795)
The input is 1995 cents; ten percent is 199.5, rounded half up to 200, so the result is 1795. The check runs one function and fails for one reason: change the rounding to Math.floor and the discount becomes 199 and the check names the function. That precision is what the bottom of the pyramid buys. It cannot tell you whether the screen calls that function with the right arguments.
Build it
The lab examples/frontend/labs/testing-layers-model is a small model of exactly this cart. It has 14 checks (5 unit, 5 component, 2 integration, 2 end to end) written as plain functions, and six seeded bugs that can be switched on one at a time. For each bug the lab runs every check and records which layers have a failing check. It also records which of nine named code points each check reaches.
cd examples/frontend/labs/testing-layers-model
../../node_modules/.bin/vitest run
node src/demo.ts
The tests passed (14 of 14, Vitest 5.1.0 on Node 26.13.1). This is a model: no DOM, no network, no framework, and "end to end" means the assembled app against a fake API, not a real browser. The bugs and checks were chosen by the lab's author, so the matrix shows how the layers relate in this feature, not how often each layer catches real bugs.
Expected output, captured from a real run (the last two tables of the demo):
=== 2. one seeded bug at a time: which layer has a failing check?
unit component integration e2e
discountRounding FAIL FAIL pass pass
negativeQuantity FAIL pass pass pass
payloadField pass pass FAIL FAIL
moneyFormat FAIL FAIL pass FAIL
checkoutEnabledWhenEmpty pass FAIL pass FAIL
basePath pass pass pass FAIL
=== 3. which bugs escape if only some layers exist?
unit only checks= 5 escaped: payloadField, checkoutEnabledWhenEmpty, basePath
unit + component checks=10 escaped: payloadField, basePath
component + integration checks= 7 escaped: negativeQuantity, basePath
e2e only checks= 2 escaped: discountRounding, negativeQuantity
all four layers checks=14 escaped: none
Read the matrix row by row. negativeQuantity (the pricing function accepts a zero quantity) is seen only by the unit layer: no screen or service check ever passes a zero. basePath (the app is configured with the wrong API path) is seen only by the end-to-end layer, because the integration checks build their own configuration. moneyFormat (a total shown as "$25" instead of "$25.00") is seen by three layers, which is overlap. The last table shows the cost of owning a single layer: unit tests alone let three bugs through, and end-to-end tests alone let the two logic bugs through, because the two end-to-end scenarios never use a discount code or a bad quantity.
The demo's first table (not shown) counts the code points each check reaches: one of nine for a unit check, four to six for component checks, six to nine for end-to-end checks. A check that reaches more code can fail for more reasons.
Illustration 2: the realistic example
Read the matrix as a plan for the checkout page. Pricing rules belong at the unit layer, where a failure names the function; screen behaviour at the component layer with the service stubbed; the request the service sends at the integration layer, against a fake that enforces the contract; and a few end-to-end scenarios confirm the assembled app can place an order. The counts in the lab (5, 5, 2, 2) are not a recommended ratio.
Illustration 3: a failure the layers hide
Look at payloadField in the matrix. The service sends quantity where the API expects qty. The unit and component layers both pass, because the component checks use a stub service that answers "ok" whatever it is given. A stub returns canned answers; it does not know the contract. Fowler's description of test doubles makes this precise: a stub supplies canned responses to calls made during a test. The bug is caught only where the real service meets something that enforces the contract: here, the integration and end-to-end checks. A suite of fast, green component tests can therefore sit on top of a broken integration. That is the cost of the stub, and the reason contract tests (a later lesson in this module) exist.
Choosing a shape
Figure 2. Where should this check live?
and its own logic"| C["Component test
stub or fake the network"] A -->|"how we talk to
an outside service"| I["Integration test
fake that enforces the contract"] A -->|"build, config,
deployment, browser"| E["End-to-end test
few, on critical journeys"] E --> F["A bug found here that no
lower test caught?
Add a lower-level test"]
How to read this: start from where the rule lives, not from a ratio. The last step is Fowler's rule: when a high-level test is the only one that fails, the bug has revealed a gap one layer down, and the cheaper test should exist too.
For end-to-end tests, the Playwright documentation advises that tests should verify what end users see, that each test should be isolated from the others, and that you should not test links to external sites or third-party servers you do not control. Fowler adds that end-to-end tests give the biggest confidence, and that because they are flaky and costly you should keep them to a bare minimum.
Figure 3. Closing the gap when a high-level test is the only one to fail
How to read this: the high-level failure is the signal, and the cheap test is the fix for the gap it revealed.
Trade-offs
| Choice | Gain | Cost |
|---|---|---|
| Many unit tests | Fast, precise failures | Blind to wiring, stubs and configuration |
| Mostly component and integration tests (trophy) | Resemble real use; catch wiring | Heavier setup; failures point at a larger area |
| Few end-to-end tests | Confidence the assembled app works | Slow, brittle, hard to debug |
| Stubbing the network in component tests | Fast, deterministic | The stub can drift from the real API |
| Duplicating checks at several layers | A second chance to catch a bug | Every test is extra baggage |
In practice: the checkout page
This is a realistic scenario, not a case history. It is a composite built from common production patterns. It describes no specific company or product, and every detail in it is an illustrative assumption.
The situation
The checkout page has been changed by several people over a year. The team has a large set of end-to-end browser tests that take long enough that developers stop running them before merging, a handful of unit tests for the price calculation, and no component tests. Releases are slowed by failures that turn out to be test infrastructure problems, and a recent bug (a discount rounded the wrong way) reached customers although the end-to-end tests were green.
Starting architecture
Figure 4. An ice-cream cone
How to read this: the warning box carries most of the checking. Any bug in the screen's behaviour or the request payload can only be found by launching the whole journey, and a rule that the journeys never exercise (a discount code) is not checked at all.
Options considered
| Option | What it fixes | What it costs | Risk |
|---|---|---|---|
| Add more end-to-end tests | Covers more journeys | Longer runs, more flakiness | Slower merges; the rounding bug still needs the right scenario |
| Rebalance toward component and integration tests | Fast feedback on behaviour and the payload | Writing fakes that match the contract | Fakes drift without contract tests |
The decision
| Field | Decision record |
|---|---|
| Context | Slow, flaky journeys carry most checks; a logic bug reached customers; developers skip the suite. |
| Decision | Keep a small set of journeys for the critical purchase path. Move pricing rules to unit tests, screen behaviour to component tests with a stubbed service, and the request shape to integration tests against a fake that enforces the API contract. When a journey finds a bug that nothing lower caught, add the lower test. |
| Consequences, good | Faster merges; failures that name a function or a request. |
| Consequences, bad | Fakes and stubs to maintain; some overlap between layers. |
| Revisit when | The API owner publishes a contract test, or a layer's failures stop being useful. |
Rollout and verification
- List the last few escaped bugs and mark which layer could have caught each (use the matrix idea from the lab).
- Add the missing lower-level test for each, and watch it fail on the old code before the fix.
- Move a scenario down only when a lower test covers the same risk; delete the journey after.
The 2 a.m. failure
The payload sent to the orders API is changed (a field renamed). The component tests stay green because their stub accepts any request, and the single journey that places an order is skipped on that pipeline because it is slow. Orders fail in production with a 422.
First three checks: (1) compare the request body with the API's contract; (2) find which test layer sends a real payload to something that validates it; (3) see whether the journey ran. Mitigation: roll back the rename. Follow-up: an integration test against a fake that enforces the contract, and a contract test shared with the API team.
Architect's notes
- Ask what each layer replaces. That list is its blind spot.
- Treat a ratio as a hypothesis and review it against the bugs that actually escaped.
- Keep end-to-end tests for what only the assembled app can show, such as configuration and wiring.
Common mistakes
- Copying a percentage split without asking what your bugs are.
- Stubbing the network everywhere and never checking the stub against the contract.
- Deleting journeys before a lower test covers the risk.
Key takeaways
- The pyramid (Cohn, described by Fowler) says: many fast low-level tests, few high-level ones, and push tests down.
- The trophy (Rauch's line, Dodds' post) says: weight the middle, because tests that resemble real use give more confidence per unit of time.
- "Integration" means a different thing in each source; define your own words.
- Each layer is blind to what it replaces: stubs hide contract drift, and only the assembled app sees its own configuration.
- When a high-level test is the only one that fails, add a lower-level test.
- A mix is a hypothesis; check it against the bugs that actually get through.
Practice exercises
Exercise 1: Starter (30 min). Run the lab and, before looking at the output, predict which layers fail for moneyFormat. Then explain why the unit layer and the end-to-end layer both fail but the integration layer does not.
Exercise 2: Intermediate (2 hours). Add a seventh seeded bug that only the component layer can see (for example, a wrong message after a failed submit) and a check that catches it. Update the expected matrix in the tests.
Exercise 3: Advanced (half day). For a feature of your own, list its last five bugs, the lowest layer that could have caught each, and whether a test existed there. Propose one change to the mix.
Related reading
In this course:
- Component-Based Architecture: the unit of composition that component tests exercise.
- Error, Loading and Empty States: the states a component test should cover.
- Server State, Caching and Revalidation: the data layer whose network calls get stubbed or faked.
- Pagination: Offset, Cursor and Infinite Scroll: a lab whose tests render a real component under jsdom.
Later in this module: unit and component testing, integration testing with network mocking, end-to-end testing and flakiness, contract testing for front ends, and visual regression testing.
Official documentation
- Martin Fowler: The Practical Test Pyramid: layers, pushing tests down, and not duplicating them.
- Martin Fowler: Test Pyramid: the origin, brittle UI tests and the ice-cream cone.
- Kent C. Dodds: The Testing Trophy and Testing Classifications: the trophy and its definitions.
- Martin Fowler: Mocks Aren't Stubs: stubs, fakes, spies and mocks.
- Testing Library: Guiding Principles: tests that resemble how software is used.
- Playwright: Best Practices: user-visible behaviour, isolation and third-party dependencies.