Learn / Frameworks / Express / Testing with Supertest

Express · Lesson 10 of 15

Testing with Supertest

Hit your app with supertest, isolate the database and assert on status and body.

  • Intermediate
  • 16 min read
  • 3 objectives

Before this lessonLesson 9: Helmet, CORS and Rate Limits

What you will learn

  • Write a request test
  • Reset state between tests
  • Test an auth header

Your Progress

0 of 15 lessons 0%

  • Lessons0 / 15
  • Completed0
  • Est. time left~ 4 hours

Create a free account to keep your progress on every device.

Supertest calls your app without binding a port. Pair it with a test database or an in-memory fake.

A first test

import request from "supertest";
import { app } from "../src/app.js";

test("GET /health", async () => {
  const res = await request(app).get("/health");
  expect(res.status).toBe(200);
  expect(res.body).toEqual({ status: "ok" });
});

test("POST /tasks validates", async () => {
  const res = await request(app).post("/tasks").send({});
  expect(res.status).toBe(400);
});

Auth

test("GET /me needs a token", async () => {
  await request(app).get("/me").expect(401);
  const { body } = await request(app).post("/login").send({ email: "ada@example.com", password: "secret" });
  await request(app).get("/me").set("Authorization", `Bearer ${body.token}`).expect(200);
});

Export app without calling listen (do that in server.js). Reset tables in beforeEach or wrap tests in transactions.

Up next · Lesson 11Express with TypeScriptTyped Request handlers, a tsconfig that works for Node and extending Express types.