Skip to the page

Structure, logging, testing and shutdown · mid

Testing APIs with supertest

Test an Express API by importing the app (without calling listen) and sending real HTTP requests with supertest, checking status codes, headers and bodies, with either a real test database or faked repositories.

The notes

What you must know

  • supertest: await request(app).post('/users').send({ ... }).expect(201). It works with node:test, Vitest or Jest.
  • Export the app separately from server.listen so tests do not need a fixed port and do not hang.
  • Integration tests with a real database (Postgres in Docker, or Testcontainers) catch SQL, migration and constraint bugs. Reset data between tests (truncate, or a transaction rolled back per test).
  • Unit-test services with fake repositories; mock outside HTTP (payment gateways, SMS) with nock or MSW (MSW works in Node).
  • Test the contract: status codes, error format, validation errors, 401/403 paths, pagination edges and idempotency.
  • Run CI on the same Node LTS version as production.

The red pen

Common traps: mistake → fix

  • Mistake: Manual Postman checks are enough

    Fix: they are not repeatable; automate the main paths.

  • Mistake: Mock everything, including the database

    Fix: you miss real SQL and constraint errors; keep some integration tests.

Easy to hard

Questions interviewers ask, easy to hard

  1. How do you test an Express API?
  2. Unit vs integration tests for a backend: what goes where?
  3. How do you handle the database in tests?
  4. How do you test an endpoint that calls a payment provider?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview