Testing HTTP APIs with Supertest
Testing Express routes in-process with Supertest: split app from listen, keep tests isolated against a real database with truncation, and use fixtures.
Testing HTTP APIs with Supertest
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Export the app from one module and call `listen()` from another. Then a test can hand the app to Supertest, which binds it to an ephemeral port itself, with no port clashes and nothing left running.
- Supertest chains a request with expectations: `request(app).post('/notes').send({...}).expect(201).expect('Content-Type', /json/)`, and the awaited response carries `status`, `headers` and `body` for further assertions.
- Inject dependencies such as the database pool into `createApp(pool)`, so tests supply a test database and production supplies the real one.
- Test against a real database where you can. Create the schema once in `before`, truncate tables in `beforeEach` (with `RESTART IDENTITY` so ids are predictable), and close the pool in `after`.
- Arrange test data with fixtures that insert directly through the pool, not through the API under test, so a bug in `POST` cannot hide a bug in `GET`.
- Test the sad paths as carefully as the happy ones: validation failures (400), missing resources (404), and the exact error body your clients depend on.
Testing the layer clients actually see
Unit tests for a function tell you the function works. They do not tell you that the route is mounted, the JSON body parsed, the status code correct, the header set, or that the SQL matches the schema. For an API, those are the things clients depend on. Testing at the HTTP boundary, sending a request and checking the response, covers all of them at once, and it is cheap when the server runs inside the test process.
That is what Supertest is for. It sends real HTTP requests to your app and gives you a fluent way to assert on the response. The wider argument for testing against real dependencies is in testing backend services with real dependencies. This lesson is how to wire it up in Node, using the Express app from building a REST API with Express and the runner from the built-in test runner.
Make the app importable
Supertest needs the app without a running server. The usual refactor is to split creation from listening:
// app.js
import express from 'express';
export function createApp(pool) {
const app = express();
app.use(express.json());
app.get('/health', (req, res) => res.json({ ok: true }));
app.post('/notes', async (req, res) => {
const { title } = req.body ?? {};
if (typeof title !== 'string' || !title.trim()) {
return res.status(400).json({ error: 'title required' });
}
const { rows } = await pool.query(
'INSERT INTO notes (title) VALUES ($1) RETURNING id, title', [title.trim()]);
res.status(201).location(`/notes/${rows[0].id}`).json(rows[0]);
});
app.get('/notes/:id', async (req, res) => {
const { rows } = await pool.query('SELECT id, title FROM notes WHERE id = $1', [req.params.id]);
if (!rows[0]) return res.status(404).json({ error: 'not found' });
res.json(rows[0]);
});
return app;
}
// server.js: the only file that listens
import { createApp } from './app.js';
import { pool } from './db.js';
createApp(pool).listen(3000);
Two ideas are at work. The app is a value you can build in a test, and the dependency it needs, the pool, is passed in rather than imported from a global. In production you pass the real pool, and in tests a pool for the test database. That second idea is dependency injection in its plainest form.
Supertest basics
request(app) takes an Express app (or an http.Server). It starts the app on an ephemeral port for the duration of the request, so there is no port to choose and nothing to shut down. I ran everything here on Node 26 with Supertest 7.
import request from 'supertest';
import assert from 'node:assert/strict';
const res = await request(app)
.post('/notes')
.send({ title: ' Buy milk ' })
.expect(201)
.expect('Content-Type', /json/);
assert.deepEqual(res.body, { id: 1, title: 'Buy milk' });
assert.equal(res.headers.location, '/notes/1');
.send() serializes an object as JSON and sets the content type. .expect(201) asserts the status, and .expect('Content-Type', /json/) asserts a header against a regex. If an expectation fails, the awaited promise rejects with a clear message, so the test fails. The resolved response gives you status, headers, body and text to assert on with whatever assertion library you use. Because it is awaited, it works in any runner, including node:test, Vitest and Jest.
Test the failures too. A client relies on the exact shape of a 400 or 404 as much as on the success body:
const res = await request(app).post('/notes').send({}).expect(400);
assert.equal(res.body.error, 'title required');
await request(app).get('/notes/999').expect(404);
Error handling that you write in Express itself is covered in Express error handling and async routes. Tests like these are how you prove those handlers return what you intended.
Database isolation
The video’s main contribution is the setup around the request: what is the database, and how does each test get a clean one. Its chapters cover Testcontainers (real Docker containers for the database), migrations, container lifecycle strategies, the testing libraries (Supertest among them), and mocking.
Whichever way you get a real database, the isolation pattern is the same. I ran it against a local Postgres 14:
import { describe, it, before, beforeEach, after } from 'node:test';
import pg from 'pg';
import { createApp } from './app.js';
const pool = new pg.Pool({ connectionString: process.env.TEST_DATABASE_URL, max: 4 });
const app = createApp(pool);
before(async () => {
await pool.query('CREATE TABLE IF NOT EXISTS notes (id serial primary key, title text not null)');
});
beforeEach(async () => { await pool.query('TRUNCATE notes RESTART IDENTITY'); });
after(async () => { await pool.query('DROP TABLE notes'); await pool.end(); });
The schema is created once, before the suite. In a real project this is where your migrations run, so the tests also exercise them. The beforeEach truncates the table, and RESTART IDENTITY resets the serial counter, so the first insert in every test gets id 1 and your assertions can name it. The after closes the pool, without which the process would hang open. Without the truncate, a test that created a note would leave it behind, ids would drift, and tests would pass or fail depending on order. Connection pools is why pool.end() matters.
Truncation is the simplest isolation. Wrapping each test in a transaction and rolling it back is faster, but harder when the code under test opens its own transactions. A separate database or schema per parallel worker is what you need once test files run concurrently. Container lifecycle choices, whether a fresh container per test, per file or per run, trade speed against isolation, and the video walks through them.
Fixtures: arrange without the API
Each test should depend only on the route it is exercising. So set up data directly, not through other endpoints:
it('returns what was stored', async () => {
await pool.query("INSERT INTO notes (title) VALUES ('fixture')");
const res = await request(app).get('/notes/1').expect(200);
assert.equal(res.body.title, 'fixture');
});
If you created the note by calling POST /notes first, a bug in POST would make the GET test fail, pointing you at the wrong place. As suites grow, small helper functions, createNote(pool, overrides), keep fixtures readable. For authenticated routes, a helper that mints a valid token or session cookie plays the same role.
Mocking the edges
A real database is worth it. A real payment provider or email service is not. Mock those at the boundary, which is the subject of mocking and test doubles in Node. The video’s last chapters cover mocking outgoing requests and best practices.
What the video covers
Software Developer Diaries’ “integration testing” video, from October 2024, is chaptered: what integration tests are, Testcontainers, migrations, container lifecycle strategies, testing libraries, mocking and best practices, and contract tests versus integration tests. It is not a Supertest tutorial. Supertest is one chapter, and the app under test is not specifically Express. It has the database-isolation and fixture material that most Supertest videos skip, and the supertest syntax, the app and server split, and the truncate pattern above are carried by this lesson’s prose and code. The video’s description opens with a sponsor blurb for an unrelated tool, and its transcript was not available. Sam Meech-Ward’s “go deeper” video is a clean eleven-minute Supertest-with-Jest introduction from 2021.
Where this fits
Real databases and real HTTP make tests trustworthy, but you still need to replace the slow or dangerous parts. That is mocking and test doubles.
Check yourself
Why does it help to build the Express app in one file and call `app.listen()` in another?
Importing a module that calls `listen()` starts a real server on a fixed port as a side effect, which makes tests slow, order-dependent and prone to `EADDRINUSE`. If the module only exports the app, Supertest can bind it to a random free port for each request, and the production entry point is the only place that listens.
A test for `GET /notes/1` creates its data by calling `POST /notes` first. What is the risk?
If `POST` is broken, the `GET` test fails for a reason unrelated to `GET`, and if both are broken in a compensating way, both pass. Insert fixture rows directly with SQL or a helper so each test depends only on the route it is testing.
Your tests pass alone but fail when run together, with ids that are off by one. What is likely wrong, and what fixes it?
Tests share a database and earlier tests leave rows and advanced sequences behind. Truncate the tables before each test, using `TRUNCATE ... RESTART IDENTITY` in Postgres so the first insert gets id 1 again. Running files in parallel against one database needs separate schemas or databases per worker.
Why test with a real Postgres rather than mocking the pool?
A mock returns whatever you tell it, so it cannot catch a wrong column name, a violated constraint, a bad migration or a transaction bug. A real database catches those, at the cost of startup time and some setup, which containers or a local instance handle.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.