What is the test pyramid, how do unit, integration and end-to-end tests differ for a backend service, and how do you balance them?
The test pyramid says to write many fast, focused unit tests, fewer integration tests that check real collaboration (a database, a message broker, an HTTP boundary), and very few slow end-to-end tests of whole user journeys. The shape follows cost: lower tests are cheap, fast and precise about failures, while higher tests give more confidence per test but are slow, flaky and hard to debug. Many backend teams use a 'trophy' variant with more integration tests, because most bugs live at the boundaries.
Full answer
Layers
- Unit tests: one function or class, with no network or database. Milliseconds. They check business rules (price calculation, validation) and edge cases. Test doubles replace collaborators.
- Integration tests: several parts together with real infrastructure: the repository against a real PostgreSQL, the HTTP layer with real routing and serialisation, the consumer with a real queue. Seconds. They catch SQL mistakes, mapping errors and configuration problems that unit tests cannot see.
- Contract tests: check the agreement between two services without running both (see the contract testing item).
- End-to-end tests: a deployed system through its public interface. Minutes, more flaky. Keep a small set for critical journeys (sign up, pay).
Guidelines
- Push each check to the lowest level that can prove it.
- Make tests deterministic: control time, random values and ids; use isolated data per test; avoid sleeps.
- Test behaviour, not implementation details, so refactoring does not break tests.
- Run unit tests on every change and integration tests in CI with disposable containers or databases. Track flaky tests and fix or remove them.
- Coverage is a signal, not a goal. Mutation testing and production monitoring complement it.
const { spawnSync } = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pyramid-'));
fs.writeFileSync(path.join(dir, 'app.test.js'), `
const { describe, it, before, after } = require('node:test');
const assert = require('node:assert');
const http = require('node:http');
const { Client } = require(${JSON.stringify(require.resolve('pg'))});
const price = (qty, unit, discount = 0) => Math.round(qty * unit * (1 - discount) * 100) / 100; // business rule
describe('unit: price rules', () => {
it('multiplies quantity and unit price', () => assert.strictEqual(price(3, 9.99), 29.97));
it('applies a discount', () => assert.strictEqual(price(2, 50, 0.1), 90));
it('handles zero quantity', () => assert.strictEqual(price(0, 50), 0));
});
describe('integration: real PostgreSQL', () => {
it('stores and reads a row', async () => {
const db = new Client(); await db.connect();
await db.query('CREATE TEMP TABLE t (id int, name text)');
await db.query("INSERT INTO t VALUES (1, 'Asha')");
assert.strictEqual((await db.query('SELECT name FROM t WHERE id = 1')).rows[0].name, 'Asha');
await db.end();
});
});
describe('end to end style: a real HTTP request', () => {
let server;
before(() => new Promise((resolve) => { server = http.createServer((req, res) => res.end(JSON.stringify({ total: price(2, 50, 0.1) }))).listen(0, resolve); }));
after(() => server.close());
it('returns the total over HTTP', async () => {
const body = await (await fetch('http://127.0.0.1:' + server.address().port + '/orders/1')).json();
assert.deepStrictEqual(body, { total: 90 });
});
});
`);
const run = spawnSync(process.execPath, ['--test', '--test-reporter=tap', path.join(dir, 'app.test.js')], { encoding: 'utf8', env: process.env });
const lines = run.stdout.split('\n');
const groups = lines.filter((l) => /^# Subtest: (unit|integration|end to end)/.test(l)).map((l) => l.replace('# Subtest: ', ''));
console.log('test groups :', groups.join(' | '));
for (const key of ['tests', 'pass', 'fail']) console.log(key.padEnd(12), ':', (lines.find((l) => l.startsWith('# ' + key + ' ')) || '').split(' ').pop());
const pyramid = [['end-to-end', 1], ['integration', 1], ['unit', 3]];
console.log('\nthe run above, drawn as a pyramid (one # per test):');
for (const [name, n] of pyramid) console.log(name.padStart(12), '|', '#'.repeat(n));
fs.rmSync(dir, { recursive: true });A temporary test file with three tiers is run with node --test against the local PostgreSQL. It is a miniature of the idea, not a complete suite. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): test groups : unit: price rules | integration: real PostgreSQL | end to end style: a real HTTP request tests : 5 pass : 5 fail : 0 the run above, drawn as a pyramid (one # per test): end-to-end | # integration | # unit | ###
Key points
- Many unit tests, fewer integration tests, very few end-to-end tests.
- Lower levels are faster and pinpoint failures.
- Integration tests use real infrastructure at the boundaries.
- Keep tests deterministic and isolated.
- Test behaviour rather than implementation.
Common mistakes
- An inverted pyramid: mostly slow end-to-end tests.
- Mocking everything so no test touches real SQL.
- Tests that depend on the order of other tests.
- Sleeping instead of waiting for a condition.
- Chasing a coverage number.
Follow-ups
- What is the testing trophy?
- How do you test code that uses the current time?
- How do you run a real database in CI?
Tips
- Explain by cost and confidence.
- Give an example for each layer.
- Mention flaky tests.