Supertest — API Integration Testing
Advertisement
Supertest makes testing Express/Node.js APIs straightforward. Start HTTP server, send requests, assert responses.
Basic Usage
npm install -D supertest
npm install -D @types/supertest
import request from "supertest";
import app from "./app";
describe("User API", () => {
it("GET /users returns users", async () => {
const res = await request(app).get("/users");
expect(res.status).toBe(200);
expect(res.body).toHaveProperty("users");
});
it("POST /users creates user", async () => {
const res = await request(app)
.post("/users")
.send({ name: "Alice", email: "alice@example.com" });
expect(res.status).toBe(201);
expect(res.body.id).toBeDefined();
});
it("GET /users/:id returns user", async () => {
const res = await request(app).get("/users/1");
expect(res.status).toBe(200);
expect(res.body.id).toBe(1);
});
it("GET /users/999 returns 404", async () => {
const res = await request(app).get("/users/999");
expect(res.status).toBe(404);
});
});
Advanced Examples
// With authentication
it("protected endpoint requires auth", async () => {
const res = await request(app)
.get("/admin")
.set("Authorization", "Bearer invalid");
expect(res.status).toBe(401);
});
// File upload
it("uploads file", async () => {
const res = await request(app)
.post("/upload")
.attach("file", "./test.txt");
expect(res.status).toBe(200);
});
// Form data
it("submits form", async () => {
const res = await request(app)
.post("/form")
.field("name", "Alice")
.field("email", "alice@example.com");
expect(res.status).toBe(200);
});
FAQ
Q: Supertest vs other tools? A: Best for Express testing. Use for integration tests.
Q: Mock external APIs? A: Use nock for HTTP mocking.
Supertest is essential for API testing in Node.js.
Advertisement