Testing HTTP APIs
Overview
Unit tests check individual functions. But many bugs live in the connections between pieces: a route registered with the wrong method, validation middleware in the wrong order, an error that becomes a 500 instead of a 404, a missing authentication check.
API tests (a kind of integration test) catch these. They send real HTTP requests to your app and check the real responses — status codes, headers and bodies — exactly as a client would see them. For a back end, they usually give the most confidence for the least effort.
supertest
supertest sends requests to an Express app without you having to start a server on a fixed port:
npm install --save-dev supertestThis is where the createApp factory from earlier pays off. Because building the app is separate from calling listen, a test can create its own app with whatever dependencies it needs:
// test/health.test.js
import { it } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from '../src/app.js';
it('GET /health returns ok', async () => {
const app = createApp({ coursesRepo: makeMemoryCoursesRepo() });
const res = await request(app).get('/health');
assert.equal(res.status, 200);
assert.deepEqual(res.body, { status: 'ok' });
});Requests and expectations
const api = request(app);
// JSON bodies
await api.post('/api/v1/courses').send({ title: 'Node.js' });
// headers and query strings
await api.get('/api/v1/courses').query({ level: 'Beginner', limit: 5 });
await api.get('/me').set('Authorization', `Bearer ${token}`);
// built-in expectations (they throw if they don't match)
await api.get('/api/v1/courses/1').expect(200).expect('Content-Type', /json/);You can mix supertest’s .expect() with assert on res.body — use whichever reads more clearly.
Testing errors
Error paths deserve as much attention as success. They’re where security and data-integrity bugs hide:
it('returns 400 with details for invalid input', async () => {
const res = await api.post('/api/v1/courses').send({ title: '', level: 'Expert' });
assert.equal(res.status, 400);
const paths = res.body.error.details.map((d) => d.path);
assert.deepEqual(paths.sort(), ['level', 'title']);
});
it('returns 400 for malformed JSON', async () => {
const res = await api
.post('/api/v1/courses')
.set('Content-Type', 'application/json')
.send('{"title": ');
assert.equal(res.status, 400);
});
it('returns JSON 404 for unknown routes', async () => {
const res = await api.get('/api/v1/nope');
assert.equal(res.status, 404);
assert.ok(res.body.error.message);
});Testing authentication and authorisation
Write a small helper that creates a user and returns a token (or a logged-in supertest agent, which keeps cookies between requests):
async function loginAs(role = 'learner') {
const token = signAccessToken({ id: 1, role });
return (req) => req.set('Authorization', `Bearer ${token}`);
}
it('requires login', async () => {
await api.get('/me').expect(401);
});
it('forbids learners from deleting courses', async () => {
const asLearner = await loginAs('learner');
await asLearner(api.delete('/api/v1/courses/1')).expect(403);
});
it("doesn't show other users' orders", async () => {
// order 50 belongs to user 2; we are user 1
const asUser1 = await loginAs('learner');
await asUser1(api.get('/api/v1/orders/50')).expect(404);
});That last kind of test — trying to access someone else’s data — catches the most common serious API vulnerability. Have at least one for every resource that belongs to a user.
With a real database
The in-memory repository makes tests fast, but it isn’t Postgres: it won’t catch a typo in SQL, a missing index, a constraint, or a transaction bug. For full confidence, run API tests against a real test database:
// test/helpers/db.js
import { pool } from '../../src/db.js';
export async function resetDatabase() {
await pool.query('TRUNCATE courses, users, enrolments RESTART IDENTITY CASCADE');
}import { before, beforeEach, after } from 'node:test';
before(async () => { await runMigrations(); });
beforeEach(async () => { await resetDatabase(); });
after(async () => { await pool.end(); });Points to watch:
- Use a separate database (e.g.
academy_test) via a test environment file:node --env-file=.env.test --test. - Start it with Docker in CI (a
services: postgresblock in GitHub Actions). node --testruns test files in parallel by default. If they share one database, run them one at a time with--test-concurrency=1, or give each file its own schema.
A common balance: many fast tests with in-memory fakes for business rules, plus a smaller set of API tests against Postgres covering each endpoint’s main paths.
What makes a good API test
- Black box: interact only through HTTP, as a client would.
- Independent: each test creates the data it needs; no test relies on another having run.
- Specific assertions: check the status, the important fields and error details — not the entire body, which makes tests brittle.
- Readable: a helper for creating test data (
createCourse({ title })) keeps tests short and focused.
A test suite is documentation that can’t go out of date. A new teammate can read
courses.test.jsto learn exactly how the API behaves — including every error case.
Test the courses API
Write API tests for the CRUD project from chapter 8: creating a course returns 201 with a Location header; creating a duplicate returns 409; an invalid body returns 400 with a title detail; listing respects limit; and fetching a deleted course returns 404. Use a fresh in-memory repository for each test.
import { describe, it, beforeEach } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from '../src/app.js';
import { makeMemoryCoursesRepo } from '../src/courses/courses.repository.memory.js';
let api;
beforeEach(() => {
api = request(createApp({ coursesRepo: makeMemoryCoursesRepo() }));
});describe('courses API', () => {
it('creates a course', async () => {
const res = await api.post('/api/v1/courses').send({ title: 'Node.js', level: 'Intermediate' });
assert.equal(res.status, 201);
assert.match(res.headers.location, /\/api\/v1\/courses\/\d+$/);
assert.equal(res.body.title, 'Node.js');
});
it('rejects duplicate titles', async () => {
await api.post('/api/v1/courses').send({ title: 'Node.js' });
const res = await api.post('/api/v1/courses').send({ title: 'node.js' });
assert.equal(res.status, 409);
});
it('validates the body', async () => {
const res = await api.post('/api/v1/courses').send({ title: 'x' });
assert.equal(res.status, 400);
assert.ok(res.body.error.details.some((d) => d.path === 'title'));
});
it('paginates', async () => {
for (const title of ['Alpha', 'Bravo', 'Charlie']) {
await api.post('/api/v1/courses').send({ title });
}
const res = await api.get('/api/v1/courses?limit=2');
assert.equal(res.body.data.length, 2);
assert.equal(res.body.page.total, 3);
});
it('returns 404 after deleting', async () => {
const { body } = await api.post('/api/v1/courses').send({ title: 'Temporary' });
await api.delete(`/api/v1/courses/${body.id}`).expect(204);
await api.get(`/api/v1/courses/${body.id}`).expect(404);
});
});Summary
- API tests send real HTTP requests through routing, middleware, validation and error handling.
- supertest calls an Express app directly — no
listen, no port management. - Build the app with a factory (
createApp) so tests can pass in test dependencies. - Use a dedicated test database, reset before each test, for full-stack confidence.
- Test the unhappy paths — 400, 401, 403, 404, 409 — as carefully as the happy ones.