Overview
You need to verify that your Express API returns the right status codes, bodies, and headers — but spinning up a real server on a real port for every test run is slow and causes port collisions in CI. Supertest solves this by handing your Express app object a fake HTTP client: requests travel through the full routing stack, middleware, and error handlers without ever binding to a port.
The snippets below use supertest 7.x with Express 4.x/5.x and Vitest 3.x. Everything also works with Jest — the request API is identical.
When to Use
- Testing route handlers, middleware, and error handlers together as one HTTP pipeline
- Verifying status codes, response bodies, and headers of API endpoints
- Covering authentication and authorization flows (JWT, session, API keys)
- Checking that request validation rejects bad payloads with the right error format
- Exercising broader integration-testing scenarios at the HTTP layer without external dependencies
When NOT to Use
- Unit testing pure functions — call
vitestorjestdirectly on the function - Testing frontend components — use
@testing-library/reactor@testing-library/vue - Load testing — use
k6orartillery, which are built for throughput measurement - Stubbing third-party HTTP calls — use
mswornock; supertest tests your server, not theirs
Solution
Setup
npm install -D supertest@^7 vitest@^3
npm install express@^4
For TypeScript, also install @types/supertest — supertest ships without bundled types.
A useful production pattern: keep app and listen() in separate files. Export the app from app.js and call app.listen() only in server.js. Tests import app.js directly, so nothing ever binds a port during test runs. A runnable multi-file version of these examples lives in the companion project.
Basic API test
import request from "supertest";
import express from "express";
import { describe, it, expect } from "vitest";
const app = express();
app.use(express.json());
app.get("/api/health", (req, res) => {
res.json({ status: "healthy", timestamp: Date.now() });
});
describe("GET /api/health", () => {
it("returns 200 with healthy status", async () => {
const response = await request(app).get("/api/health");
expect(response.status).toBe(200);
expect(response.body.status).toBe("healthy");
expect(response.body.timestamp).toBeDefined();
});
});
Every supertest call returns a promise — always await it. If you forget, the test finishes before the response arrives and the assertions never run, which produces silently passing tests that check nothing.
Testing POST with JSON body
app.post("/api/users", (req, res) => {
const { email, name } = req.body;
if (!email || !name) {
return res.status(400).json({ error: "email and name are required" });
}
res.status(201).json({ id: 1, email, name });
});
describe("POST /api/users", () => {
it("creates a user with valid data", async () => {
const response = await request(app)
.post("/api/users")
.send({ email: "alice@example.com", name: "Alice" })
.set("Content-Type", "application/json");
expect(response.status).toBe(201);
expect(response.body.id).toBe(1);
expect(response.body.email).toBe("alice@example.com");
});
it("returns 400 when email is missing", async () => {
const response = await request(app)
.post("/api/users")
.send({ name: "Alice" })
.set("Content-Type", "application/json");
expect(response.status).toBe(400);
expect(response.body.error).toContain("email");
});
});
.send(obj) serializes the object as JSON, and .set() applies headers before the request fires. Testing the 400 path matters as much as the 201: validation bugs are the ones that reach production unnoticed because the happy path worked in a demo.
Testing authentication
import jwt, { type JwtPayload } from "jsonwebtoken";
const SECRET = "test-secret";
app.get("/api/profile", (req, res) => {
const auth = req.headers.authorization;
if (!auth?.startsWith("Bearer ")) {
return res.status(401).json({ error: "Unauthorized" });
}
const token = auth.slice(7);
try {
const payload = jwt.verify(token, SECRET) as JwtPayload;
res.json({ userId: payload.userId, email: payload.email });
} catch {
res.status(401).json({ error: "Invalid token" });
}
});
describe("GET /api/profile with auth", () => {
it("returns 401 without token", async () => {
const response = await request(app).get("/api/profile");
expect(response.status).toBe(401);
});
it("returns user data with valid token", async () => {
const token = jwt.sign({ userId: 42, email: "alice@example.com" }, SECRET);
const response = await request(app)
.get("/api/profile")
.set("Authorization", `Bearer ${token}`);
expect(response.status).toBe(200);
expect(response.body.userId).toBe(42);
});
it("returns 401 with expired token", async () => {
const token = jwt.sign({ userId: 42 }, SECRET, { expiresIn: "0s" });
const response = await request(app)
.get("/api/profile")
.set("Authorization", `Bearer ${token}`);
expect(response.status).toBe(401);
});
});
jwt.verify returns string | JwtPayload, so the as JwtPayload cast is needed to read claims in strict TypeScript. The expiresIn: "0s" trick creates a token that’s already expired — verify throws immediately, which exercises the same code path as a genuinely expired token without waiting.
Testing query parameters and pagination
const users = Array.from({ length: 25 }, (_, i) => ({
id: i + 1,
name: `User ${i + 1}`,
}));
app.get("/api/users", (req, res) => {
const page = parseInt(req.query.page as string) || 1;
const limit = parseInt(req.query.limit as string) || 10;
const start = (page - 1) * limit;
const end = start + limit;
res.json({
data: users.slice(start, end),
total: users.length,
page,
limit,
});
});
describe("GET /api/users with pagination", () => {
it("returns first page by default", async () => {
const response = await request(app).get("/api/users");
expect(response.status).toBe(200);
expect(response.body.data).toHaveLength(10);
expect(response.body.page).toBe(1);
expect(response.body.total).toBe(25);
});
it("returns correct page when specified", async () => {
const response = await request(app).get("/api/users?page=2&limit=5");
expect(response.body.data).toHaveLength(5);
expect(response.body.data[0].id).toBe(6);
});
});
You can pass the query string inside .get() as shown, or chain .query({ page: 2, limit: 5 }), which handles URL-encoding for you.
Testing error handling middleware
import type { ErrorRequestHandler } from "express";
app.get("/api/error", () => {
throw new Error("Something went wrong");
});
const errorHandler: ErrorRequestHandler = (err, req, res, next) => {
res.status(500).json({
error: err.message,
stack: process.env.NODE_ENV === "production" ? undefined : err.stack,
});
};
app.use(errorHandler);
describe("Error handling", () => {
it("returns 500 with error message", async () => {
const response = await request(app).get("/api/error");
expect(response.status).toBe(500);
expect(response.body.error).toBe("Something went wrong");
});
});
Express error middleware is identified by its four parameters — a three-argument function is treated as regular middleware and the error path never triggers. It must also be registered after the routes; app.use order determines where in the pipeline it sits.
Testing with cookies and sessions
app.post("/api/login", (req, res) => {
res.cookie("session", "abc-123", { httpOnly: true });
res.json({ authenticated: true });
});
app.get("/api/dashboard", (req, res) => {
if (!req.headers.cookie?.includes("session=abc-123")) {
return res.status(401).json({ error: "No session" });
}
res.json({ data: "secret dashboard data" });
});
describe("Cookie-based sessions", () => {
it("maintains cookies across requests", async () => {
const agent = request.agent(app);
await agent.post("/api/login").expect(200);
const response = await agent.get("/api/dashboard");
expect(response.status).toBe(200);
expect(response.body.data).toBe("secret dashboard data");
});
});
request.agent(app) behaves like a browser cookie jar: Set-Cookie headers from one response are sent on subsequent requests. Plain request(app) has no memory between calls, so a login-then-dashboard flow fails without an agent. Alternatively, set the header manually — .set("Cookie", "session=abc-123") — when the test needs a specific cookie value rather than whatever the server just issued.
Explanation
request(app) starts a throwaway HTTP server on an ephemeral port, fires the request at it, and closes it when the test finishes. Nothing binds a well-known port, so parallel test files never collide — a real advantage over app.listen(3000) in CI, where “port already in use” flakes are common.
Two details worth knowing:
request(app)vsrequest.agent(app)— use the plain call for isolated requests and the agent for anything stateful (cookies, sessions, CSRF tokens).- Ordering is the API —
.set(),.send(),.query(),.attach()configure the request before it dispatches;.expect(status)asserts synchronously and is handy for fast sanity checks.
Underneath, supertest is a thin layer over superagent: the chainable methods map to superagent’s request builder, and the response object is a regular Node http.IncomingMessage extended with a parsed body. Two limits follow from the ephemeral-server model. There’s no TLS layer, so secure cookies or HTTPS-only headers need a different setup, and middleware reading req.hostname sees 127.0.0.1 rather than your production domain. Neither matters for typical route coverage, but both bite when you test cookie flags or multi-subdomain logic.
For tests that hit a real database, pair this recipe with Testcontainers or a dedicated test schema — reset state in beforeEach so tests stay independent. For the bigger strategy picture (which layer should own which assertions), see the API testing strategy template.
Variants
Using supertest with Fastify
import Fastify from "fastify";
const fastify = Fastify();
fastify.get("/api/health", async () => ({ status: "healthy" }));
await fastify.ready();
const response = await request(fastify.server).get("/api/health");
Fastify doesn’t expose an Express-style app, but supertest accepts any http.Server — fastify.server works. Await fastify.ready() before firing requests; without it, routes registered inside plugins may not be loaded yet.
Testing file uploads
app.post("/api/upload", (req, res) => {
res.json({ received: true });
});
it("uploads a file", async () => {
const response = await request(app)
.post("/api/upload")
.attach("file", Buffer.from("test content"), "test.txt");
expect(response.status).toBe(200);
expect(response.body.received).toBe(true);
});
.attach() accepts a file path or a Buffer. Passing a Buffer keeps the test self-contained — no fixture directory, no __dirname (which doesn’t exist under ESM anyway).
Best Practices
- Keep the app export and
listen()in separate files so tests never bind a port - Use
request.agent(app)whenever a flow depends on cookies or sessions persisting across requests - Cover error statuses — 400, 401, 403, 404, 409, 500 — not just the 2xx path; validation failures are where real bugs hide
- Set
Content-Typeexplicitly when sending bodies, or use.send(obj)which defaults to JSON - Reset shared state between tests — a
beforeEachthat truncates tables or re-seeds fixtures prevents order-dependent failures - Assert on the meaningful fields of the response body, not the whole object — brittle snapshot-style equality breaks on any harmless addition like a
timestamp
Common Mistakes
- Calling
app.listen()in the test file: binds a real port and collides with parallel workers. Import theappobject —request(app)handles the server lifecycle itself. - Forgetting
express.json(): POST bodies arrive asundefinedwithout the parser, so every validation test fails for the wrong reason. - Missing
awaiton the request: supertest returns a promise; withoutawaitthe test exits early, the assertions are skipped, and the suite reports a false pass. - Registering error middleware before routes: the handler never fires because errors thrown in routes registered later skip middleware defined earlier. Put
app.use(errorHandler)last. - Hitting the real database or real secrets: tests become flaky and dangerous. Point the app at a test schema or mock the data layer.
Further Reading
- supertest on GitHub — full request API:
.expect()chains,.attach(), agents - Express error handling guide — middleware ordering and the four-argument error signature
- Vitest documentation — test runner used in the snippets
Frequently Asked Questions
How do I test WebSocket endpoints with supertest?
You can't — supertest only speaks HTTP. For WebSocket coverage use the ws package or socket.io-client with a real listener on an ephemeral port.
Can I use supertest with TypeScript?
Yes. Install @types/supertest and the API is identical. Under strict mode you'll need the JwtPayload cast and ErrorRequestHandler typing shown above.
How do I test rate limiting?
Hammer the endpoint in a loop and assert the 429 appears once you cross the configured threshold:
it("returns 429 after rate limit", async () => {
for (let i = 0; i < 100; i++) {
const response = await request(app).get("/api/limited");
if (i >= 50) expect(response.status).toBe(429);
}
});
The 50 here assumes a limiter configured at 50 requests — adjust it to whatever threshold your middleware actually enforces.
Should I mock the database in supertest tests?
Depends on the layer you're testing. For route-level tests, mock the data layer so failures point at the handler. For integration tests, use a real test database — SQLite in-memory, a dedicated schema, or Testcontainers — and reset it per test.
How do I test CORS headers?
Send an OPTIONS preflight or set the Origin header and assert the response headers:
const response = await request(app)
.options("/api/data")
.set("Origin", "https://example.com");
expect(response.headers["access-control-allow-origin"]).toBe("https://example.com");
Related Resources
Vitest Snapshot Testing for React
How to use Vitest snapshot testing to catch unintended UI changes in React components, including inline snapshots and snapshot update workflows.
RecipeMock Network Requests with MSW
How to use Mock Service Worker (MSW) to intercept network requests in JavaScript tests and development, including REST and GraphQL mocking.
RecipeIntegration Testing with Real Dependencies
How to test multiple components working together using real databases, HTTP clients, and message queues in Python, JavaScript, and Java.
DocAPI Testing Strategy Template
A template for planning contract tests, integration tests, and load tests for APIs.
GuideSoftware Testing Strategy Guide
A practical guide to building a layered testing strategy with unit, integration, contract, and end-to-end tests that your team will actually maintain.