Interview frequency: …
Short answer
Pass an Express or Fastify app to supertest; it creates a lightweight server, sends simulated HTTP requests, and checks status codes, headers, and JSON content.
Explanation
Supertest enables fast, isolated integration tests without port conflicts when tests run in parallel. It automatically calls server.listen(0) on a temporary random port and closes the server when the assertions finish.
Code example
import request from "supertest";
import { app } from "./app";
test("GET /api/health returns 200", async () => {
const res = await request(app)
.get("/api/health")
.expect("Content-Type", /json/)
.expect(200);
assert.equal(res.body.status, "healthy");
});Common mistakes
- Exporting a server that is already listening on a fixed port (app.listen(3000)) from the main app file, instead of separating the app definition from starting the server.