Testing HTTP APIs

Topic 2 of 3 in Testing6 min readIntermediateFree course

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:

Terminal
npm install --save-dev supertest

A test file uses request(app).post(‘/courses’).expect(201). supertest sends in-memory HTTP to createApp, which runs the real routes, middleware and services against a test database that is migrated and cleaned before each test, and returns the response. Only things you don’t control, such as email and payments, are swapped for fakes.

This 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:

JavaScript
// 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

JavaScript
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:

JavaScript
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):

JavaScript
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:

JavaScript
// test/helpers/db.js
import { pool } from '../../src/db.js';

export async function resetDatabase() {
  await pool.query('TRUNCATE courses, users, enrolments RESTART IDENTITY CASCADE');
}
JavaScript
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: postgres block in GitHub Actions).
  • node --test runs 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.js to learn exactly how the API behaves — including every error case.

Exercise

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.

JavaScript
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() }));
});

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.