Documentation and Testing · Lesson 27 of 30
Testing REST APIs Automatically
Clicking through Postman before each release doesn't scale. Automated API tests start your app, send real HTTP requests and check the responses – status codes, bodies, headers and error cases – in seconds, on every commit. Node.js has a built-in test runner, and fetch is built in too, so you need no extra libraries.
In this lesson
- Making the app testable
- Integration tests with node:test and fetch
- Testing the error paths
- The testing pyramid for APIs
Make the app testable
Export the Express app from one file and call listen in another, so tests can start it on a random free port:
// app.js
import express from 'express';
export function createApp() {
const app = express();
app.use(express.json());
const tasks = new Map();
let nextId = 1;
app.post('/api/tasks', (req, res) => {
const title = req.body?.title;
if (typeof title !== 'string' || title.trim().length < 3) {
return res.status(422).json({ errors: [{ field: 'title', message: 'must be at least 3 characters' }] });
}
const task = { id: nextId++, title: title.trim(), done: false };
tasks.set(task.id, task);
res.status(201).location(`/api/tasks/${task.id}`).json(task);
});
app.get('/api/tasks/:id', (req, res) => {
const task = tasks.get(Number(req.params.id));
return task ? res.json(task) : res.status(404).json({ error: 'Task not found' });
});
app.delete('/api/tasks/:id', (req, res) => {
return tasks.delete(Number(req.params.id)) ? res.status(204).end() : res.status(404).json({ error: 'Task not found' });
});
return app;
}
The tests
// api.test.js
import { test, describe, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { createApp } from './app.js';
let server;
let base;
before(async () => {
server = createApp().listen(0); // port 0 = any free port
await new Promise((r) => server.once('listening', r));
base = `http://localhost:${server.address().port}`;
});
after(() => server.close());
const post = (path, body) =>
fetch(base + path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
describe('POST /api/tasks', () => {
test('creates a task and returns 201 with Location', async () => {
const res = await post('/api/tasks', { title: ' Write tests ' });
assert.equal(res.status, 201);
const task = await res.json();
assert.equal(res.headers.get('location'), `/api/tasks/${task.id}`);
assert.deepEqual(task, { id: task.id, title: 'Write tests', done: false });
});
test('rejects a short title with 422 and a field error', async () => {
const res = await post('/api/tasks', { title: 'Hi' });
assert.equal(res.status, 422);
const body = await res.json();
assert.equal(body.errors[0].field, 'title');
});
});
describe('GET and DELETE /api/tasks/:id', () => {
test('round trip: create, read, delete, then 404', async () => {
const created = await (await post('/api/tasks', { title: 'Temporary task' })).json();
assert.equal((await fetch(`${base}/api/tasks/${created.id}`)).status, 200);
assert.equal((await fetch(`${base}/api/tasks/${created.id}`, { method: 'DELETE' })).status, 204);
assert.equal((await fetch(`${base}/api/tasks/${created.id}`)).status, 404);
});
test('unknown id returns 404', async () => {
const res = await fetch(`${base}/api/tasks/9999`);
assert.equal(res.status, 404);
});
});
$ node --test --test-reporter=spec api.test.js ▶ POST /api/tasks ✔ creates a task and returns 201 with Location ✔ rejects a short title with 422 and a field error ✔ POST /api/tasks ▶ GET and DELETE /api/tasks/:id ✔ round trip: create, read, delete, then 404 ✔ unknown id returns 404 ✔ GET and DELETE /api/tasks/:id ℹ tests 4 ℹ suites 2 ℹ pass 4 ℹ fail 0
- Each test sends real HTTP requests to the real app – routing, middleware, validation and serialisation are all covered.
- Test the error paths as carefully as the happy path: validation, 404s, auth failures, conflicts. That's where regressions hide.
- Assert on status, headers and the body's shape. Avoid asserting volatile values (timestamps, generated ids) exactly.
- Run with
node --test; add it tonpm testand your CI pipeline.
The testing pyramid for APIs
From many fast tests to a few broad ones
- End-to-enda few smoke tests against a deployed environment
- Contract testsresponses match the OpenAPI spec; consumers' expectations still hold (Pact)
- Integration testsHTTP-level tests like these, with a test database
- Unit testsbusiness logic and validation functions in isolation – the most numerous
Test data
Give each test run a clean database (a container, a transaction rolled back after each test, or unique ids per test), and never point tests at production. Mock third-party APIs at the HTTP level so tests don't depend on someone else's uptime.
Practice
Try it yourself
Write a test that checks
POST /api/taskswith an empty body returns 422 – not 500.Show solution
test('empty body is a 422, not a crash', async () => { const res = await fetch(`${base}/api/tasks`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }); assert.equal(res.status, 422); });
Quick check
Why export the app separately from listen()?
So tests can start it on a free port and stop it afterwards.
What does listen(0) do?
Lets the operating system pick any free port.
Which tests should be most numerous?
Fast unit tests, with fewer integration and end-to-end tests above them.
Summary
- Separate app creation from listen; start the app on port 0 in tests.
- Use node:test, assert and fetch to check status, headers and bodies – especially error cases.
- Combine unit, integration, contract and a few end-to-end tests; run them in CI.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.