Testing Node.js: The Test Pyramid with Mocha
How to distribute a Node.js test suite sensibly across different test levels and how Mocha, node:assert, sinon and supertest work together along the way.
A test doesn’t prove that code works. It records which behavior someone once expected from that code – and raises the alarm when that expectation breaks. A test suite is therefore less a proof than a memory, and the person who breaks the expectation is surprisingly often you yourself, half a year later. In the backend, where a wrong calculation slips silently through an API and only gets noticed in accounting, this memory is worth its weight in gold.
So the key question is never “Do we test?” but “How do we distribute our testing effort?” There’s a picture for exactly that which has held up for years: the test pyramid. It’s a heuristic, not a ratio that looks the same for every system. In this article I look at how it works, why suites tip over time, and which tools fit in everyday Node.js work – Mocha as the runner, node:assert for assertions, sinon for isolating external dependencies and supertest for HTTP endpoints. Node.js now ships its own stable test runner with node:test; Mocha remains the deliberately chosen option here, not the only up-to-date one.
The pyramid: broad base, narrow top#
The idea is simple. Not all tests are equally expensive, and not all of them give you an answer equally fast. A unit test runs in milliseconds, isolates a single function and, when it fails, tells me fairly precisely where the problem is. An end-to-end test boots the whole application, clicks through several systems and takes seconds to minutes – and when it turns red, all I know at first is that something broke somewhere along the long way.
This often leads to a distribution with many fast tests at the base, targeted integration tests in the middle and a few end-to-end scenarios at the top. How wide the layers turn out depends on the risks and the system boundaries.
graph TD
E2E["E2E<br/>few, slow, brittle"]
INT["Integration<br/>fewer, medium speed"]
UNIT["Unit<br/>many, fast, isolated"]
E2E --> INT
INT --> UNIT
style UNIT fill:#2d6a4f,color:#fff
style INT fill:#40916c,color:#fff
style E2E fill:#74c69d,color:#000The base is broad because unit tests are cheap – quick to write, quick to run, stable. The top is narrow because E2E tests are expensive to maintain. They break with every environment change, they become flaky as soon as timing comes into play, and they cost time in every CI run. You need a few of them – they’re the only ones that show the parts also work together. But they’re the salt, not the soup.
Which tool for what#
Before I get to code, a quick overview, because in Node.js the work is spread across a small ecosystem rather than a single framework:
- Mocha is the runner. It provides the structure (
describe/it), runs the tests, manages hooks and reports results. Mocha itself deliberately ships no assertions. node:assertprovides exactly those assertions – built in, without an extra dependency. If you want a more expressive BDD syntax, you can use Chai instead (in the CommonJS world of 2024, the v4 line).- sinon provides test doubles: spies observe calls, stubs replace behavior. I use them to isolate external dependencies such as the database, HTTP or time.
- supertest tests HTTP endpoints at the app level without needing a real network port or a browser.
This separation irritates people coming from other languages at first. But it’s a strength: you combine interchangeable building blocks instead of tying yourself to a monolithic framework.
Unit tests: the foundation#
Let’s start at the bottom. A unit test takes a function, gives it inputs and checks the output. Nothing else – no database, no network, no file system.
Mocha structures this with describe (a block that groups related tests) and it (a single test case). For the assertion I use node:assert in strict mode. The node: prefix makes clear that it’s a built-in, and /strict ensures that no silent type coercion happens.
const assert = require('node:assert/strict');
const { sum } = require('../src/math');
describe('sum()', () => {
it('adds two positive numbers', () => {
assert.strictEqual(sum(2, 3), 5);
});
it('handles negative operands', () => {
assert.strictEqual(sum(-4, 1), -3);
});
});
Two details deserve a second look. First, the argument order: assert.strictEqual(actual, expected) – always the actual value first, then the expected one. If you swap them, a failure gives you a diff output that reads exactly the wrong way around. Second, strictEqual instead of equal: strict mode compares with Object.is/=== and doesn’t silently convert anything. 1 is not '1'. That sounds pedantic, but it prevents exactly the class of bugs you actually want to catch with tests.
For objects and arrays I use deepStrictEqual, which compares deeply and with exact types:
const assert = require('node:assert/strict');
it('builds the expected payload', () => {
const result = buildUser({ id: 1, name: 'Ada' });
assert.deepStrictEqual(result, {
id: 1,
name: 'Ada',
role: 'guest',
});
});
Test behavior, not implementation#
This is where most discussions in code reviews start. A colleague once asked whether he shouldn’t check that his function calls Array.map internally. Better not: the test should care about the result – the transformed list – not the way there.
The difference is practical, not academic. A test that targets observable behavior survives a refactoring: as long as the function returns the same output for the same input, it stays green, whether there’s map, reduce or a for loop inside. A test that nails down implementation details, on the other hand, breaks with every rework – even though nothing is broken from a domain perspective. Tests like that train a team to shy away from refactoring. And a team that no longer dares to restructure accumulates technical debt faster than any test could ever catch it.
Isolating external dependencies with sinon#
As soon as a function leaves pure computation and talks to a database, an HTTP client or the clock, things get interesting. I don’t want to hit these dependencies for real in a unit test – they’re slow, unreliable and hard to bring into a defined state. Instead, I replace them with test doubles.
sinon mainly distinguishes between a spy and a stub. A spy lets the real function run and only observes how often and with what it was called. A stub replaces the behavior completely – I tell it what to return or throw.
Take a service that loads a user through a repository. I want to test that it behaves correctly on a DB error without ever touching a real database:
const assert = require('node:assert/strict');
const sinon = require('sinon');
const userRepo = require('../src/user-repo');
const service = require('../src/user-service');
describe('userService.getUser()', () => {
afterEach(() => {
sinon.restore();
});
it('propagates a repository failure', async () => {
const stub = sinon
.stub(userRepo, 'findById')
.rejects(new Error('db down'));
await assert.rejects(() => service.getUser(1), /db down/);
assert.ok(stub.calledOnceWith(1));
});
it('returns the user on success', async () => {
sinon.stub(userRepo, 'findById').resolves({ id: 1, name: 'Ada' });
const user = await service.getUser(1);
assert.strictEqual(user.name, 'Ada');
});
});
The most important piece here isn’t the stub itself but the afterEach(() => sinon.restore()). Since sinon v5, the default sinon object is itself a sandbox; restore() resets all replaced methods. If you forget it, the stubs live on beyond the test case. The next test then silently gets a manipulated userRepo slipped in – and depending on the execution order, it passes sometimes and sometimes doesn’t. That’s exactly what “flaky” means: a test whose result depends on order or parallelism, not on the code. If you prefer your own sandbox, use const sandbox = sinon.createSandbox() and call sandbox.restore() – the principle stays the same.
But be careful: test doubles are a sharp knife. If you mock everything away, in the end you’re only testing that the mocks react the way you configured them. Tests like that mirror your own expectation back at you and break at the first real refactoring. Replace the boundary to the external system – not your own logic along with it.
Integration tests: HTTP endpoints with supertest#
One level up are integration tests. Here I no longer want to check a single function but the interplay – for example, that an Express route returns the right status code and body. That’s what supertest is for.
supertest takes an Express app or an http.Server, binds it to an ephemeral port and sends real HTTP requests against it. No browser, no manually started server, no fixed port number. The API is fluent and reads almost like a description:
const assert = require('node:assert/strict');
const request = require('supertest');
const app = require('../src/app');
describe('GET /users', () => {
it('returns 200 and a JSON list', async () => {
const res = await request(app)
.get('/users')
.expect(200)
.expect('Content-Type', /json/);
assert.ok(Array.isArray(res.body));
assert.strictEqual(res.body.length, 2);
});
it('returns 404 for an unknown user', async () => {
await request(app).get('/users/999').expect(404);
});
});
The await at the front is crucial. supertest returns a promise; without await (or a return of the promise), the test ends before the assertions have run – and Mocha wrongly reports it as green. This kind of false positive is especially treacherous, because the suite stays reassuringly green for weeks even though it checks nothing.
That also makes it clear why I consistently handle async one way. Mocha allows two styles: either async/promise-returning or the classic done callback. You must not mix them. Either
it('waits for the promise', async () => {
const value = await loadValue();
assert.strictEqual(value, 42);
});
or, if you’re working with a callback-based API:
it('waits for the callback', function (done) {
loadValue((err, value) => {
if (err) return done(err);
assert.strictEqual(value, 42);
done();
});
});
Both at once – a done parameter and async – Mocha rejects with a clear error (“Resolution method is overspecified”). A side note: Mocha’s default timeout per test is 2000 ms. If an asynchronous test never calls its done or a promise never resolves, it runs into this timeout and turns red – often the first hint of a forgotten await or done.
The most common mistake: the pyramid upside down#
Now to the most common pitfall. A team starts with the best intentions but mostly writes E2E tests, because they feel so nicely “real.” After a year, the distribution looks like this:
graph TD
UNIT["Unit<br/>barely there"]
INT["Integration<br/>a few"]
E2E["E2E<br/>many, slow, flaky"]
UNIT --> INT
INT --> E2E
style E2E fill:#9d0208,color:#fff
style INT fill:#dc2f02,color:#fff
style UNIT fill:#f48c06,color:#000This is called the “ice cream cone” – the inverted pyramid with the broad, expensive top up above. The symptoms are always the same: the suite runs for ten minutes instead of ten seconds. A single red test doesn’t tell you where the bug is, because it passes through a dozen components at once. And because E2E tests depend on timing and environment, they become flaky – at some point the team simply reruns the pipeline until it’s green. That’s the moment when tests stop being a memory and become a ritual nobody takes seriously anymore.
The way out is unspectacular: for every bug a slow E2E test catches, you write the actual regression test one level lower – as a unit or integration test that catches the same cause in milliseconds. The pyramid doesn’t straighten itself out through one big rework, but through the habit of pinning down bugs at the cheapest level where they’re reproducible.
This attitude fits a thought I already described in errors as architecture: an error isn’t a nuisance you push away, but information about the system. A test is the preserved form of that information. And if you want to understand why asynchronous tests play such a big role in the backend in the first place, you’ll find the basics in the Node.js training on the event loop and architecture.
A word about hooks#
For tests to stay independent, each one needs a clean starting state. Mocha offers four hooks for this: before and after run once per describe block, beforeEach and afterEach before and after each individual test. The order is reliable: first all before, then per test beforeEach → test → afterEach, and finally after.
describe('orderService', () => {
let db;
before(async () => {
db = await connectTestDb();
});
beforeEach(async () => {
await db.reset();
});
afterEach(() => {
sinon.restore();
});
after(async () => {
await db.close();
});
it('creates an order', async () => {
// ...
});
});
Expensive one-time work like setting up the connection belongs in before/after, resetting state in beforeEach/afterEach. A beforeEach inside a nested describe only applies to its tests – that’s how you keep setup local and avoid a global hook needlessly slowing down half the suite.
Conclusion#
Testing in the backend isn’t busywork you tack on at the end. It’s how a team records its architectural expectations and safeguards them across refactorings. The test pyramid gives a direction, but no fixed count: fast tests carry the base, integration tests secure important boundaries, a few end-to-end scenarios check the interplay. In this example the toolbox is small and interchangeable – Mocha structures, node:assert checks, sinon isolates external dependencies, supertest tests HTTP endpoints.
What has turned out to be the core for me over the years: test observable behavior, not the implementation, and pin down bugs at the cheapest level where they’re reproducible. Then the suite stays fast, meaningful and – most importantly – trustworthy. A test suite nobody believes in anymore is more expensive than none at all.
Further reading#
- Mocha – documentation and hooks: mochajs.org and mochajs.org/features/hooks
- node:assert – strict mode: nodejs.org/api/assert.html
- node:test – built-in test runner: nodejs.org/api/test.html
- sinon – test doubles and stubs: sinonjs.org and sinonjs.org/concepts/stubs
- supertest: npmjs.com/package/supertest
- Chai (alternative to assert): chaijs.com
- Companion repository with a testing chapter: github.com/mikebild/introduction-nodejs
Revised and translated from German with the help of AI.