Testing APIs
Automated tests let you change code without fear: run one command and know whether every endpoint still behaves. For Express you don't need a browser or Postman — start the app on a random port, send real HTTP requests with fetch, and assert on the responses. Node's built-in node:test runner and node:assert are all you need.
Make the app testable
The key design step: build the app in one module, start it in another. Tests import the app without opening a fixed port:
// src/app.js — creates and configures the app, no listen()
const express = require('express');
function createApp({ store }) {
const app = express();
app.use(express.json());
app.get('/notes', async (req, res) => res.json(await store.list()));
app.post('/notes', async (req, res) => {
if (!req.body?.text) return res.status(400).json({ error: 'text is required' });
res.status(201).json(await store.add(req.body.text));
});
return app;
}
module.exports = { createApp };
// src/server.js — the only file that listens on a real port
const { createApp } = require('./app');
const { createStore } = require('./store');
createApp({ store: createStore() }).listen(process.env.PORT ?? 3000);Passing the store in (instead of importing it inside) means each test can use a fresh, isolated store.
A test file
// test/notes.test.js
const { test, describe, before, after } = require('node:test');
const assert = require('node:assert/strict');
const { createApp } = require('../src/app');
function memoryStore() {
const notes = [];
return {
async list() { return notes; },
async add(text) { const n = { id: notes.length + 1, text }; notes.push(n); return n; },
};
}
describe('notes API', () => {
let server, base;
before(async () => {
server = createApp({ store: memoryStore() }).listen(0);
await new Promise((resolve) => server.once('listening', resolve));
base = `http://localhost:${server.address().port}`;
});
after(() => server.close());
test('starts empty', async () => {
const res = await fetch(`${base}/notes`);
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), []);
});
test('creates a note', async () => {
const res = await fetch(`${base}/notes`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: 'buy milk' }),
});
assert.equal(res.status, 201);
assert.deepEqual(await res.json(), { id: 1, text: 'buy milk' });
});
test('rejects an empty note', async () => {
const res = await fetch(`${base}/notes`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
assert.equal(res.status, 400);
});
});Running the tests
node --test finds files named *.test.js (and similar patterns) automatically. The durations vary from run to run, so this output is illustrative:
node --test▶ notes API
✔ starts empty (12.4ms)
✔ creates a note (3.1ms)
✔ rejects an empty note (1.9ms)
▶ notes API (25.8ms)
ℹ tests 3
ℹ suites 1
ℹ pass 3
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 96.2
Add it to package.json as "test": "node --test" and run npm test. node --test --watch re-runs tests on every save; --experimental-test-coverage prints a coverage report.
The same checks, runnable here
The runner prints timings, so this site can't verify its exact output. The playground below runs the same three assertions with plain assert and prints a deterministic summary instead:
const express = require('express');
const assert = require('node:assert/strict');
function createApp({ store }) {
const app = express();
app.use(express.json());
app.get('/notes', async (req, res) => res.json(await store.list()));
app.post('/notes', async (req, res) => {
if (!req.body?.text) return res.status(400).json({ error: 'text is required' });
res.status(201).json(await store.add(req.body.text));
});
return app;
}
function memoryStore() {
const notes = [];
return {
async list() { return notes; },
async add(text) { const n = { id: notes.length + 1, text }; notes.push(n); return n; },
};
}
const json = (body) => ({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
const tests = {
'starts empty': async (base) => {
const res = await fetch(`${base}/notes`);
assert.equal(res.status, 200);
assert.deepEqual(await res.json(), []);
},
'creates a note': async (base) => {
const res = await fetch(`${base}/notes`, json({ text: 'buy milk' }));
assert.equal(res.status, 201);
assert.deepEqual(await res.json(), { id: 1, text: 'buy milk' });
},
'rejects an empty note': async (base) => {
const res = await fetch(`${base}/notes`, json({}));
assert.equal(res.status, 400);
},
'a deliberately wrong expectation': async (base) => {
const res = await fetch(`${base}/notes`);
assert.equal((await res.json()).length, 5);
},
};
const server = createApp({ store: memoryStore() }).listen(0, async () => {
const base = `http://localhost:${server.address().port}`;
let passed = 0;
for (const [name, fn] of Object.entries(tests)) {
try {
await fn(base);
passed++;
console.log('✔', name);
} catch (err) {
console.log('✖', name, '-', err.message.split('\n')[0]);
}
}
console.log(`${passed}/${Object.keys(tests).length} passed`);
server.close();
});✔ starts empty
✔ creates a note
✔ rejects an empty note
✖ a deliberately wrong expectation - Expected values to be strictly equal:
3/4 passed
What to test
| Kind | Example | Tool |
|---|---|---|
| unit | validateTicket() returns the right errors |
node:test, plain function calls |
| integration (HTTP) | POST /notes returns 201 and stores the note |
app on port 0 + fetch |
| contract | responses match your OpenAPI schema | schema validators |
| end-to-end | the real frontend + API + database work together | Playwright |
For each endpoint, cover the happy path, validation failures, not found, and auth failures (401/403). Those edges are where bugs hide.
Tip:
supertestis a popular alternative that drives the app without you managing the port:await request(app).get('/notes').expect(200). NestJS projects use it by default for e2e tests.
Test yourself
Why export the app from one module and call listen() in another?
- Express requires two files
- Tests can import and start the app on a random port without side effects
- It makes the app faster
- To enable HTTPS
Which command runs tests with Node's built-in runner?
- node test
- node --test
- npm run jest
- node --assert
Besides the happy path, what should an endpoint test cover?
- Only the happy path
- Validation errors, not-found cases and auth failures
- The Express source code
- CSS styling