Unit Testing with Jest & Supertest

🦁 Express.jsLesson 14Advanced

Supertest is a Node library for testing HTTP servers, allowing developers to write clean, assertion-driven API tests without having to start local listener sockets.

1 Configuring Jest and Supertest

Install testing utilities: npm install --save-dev jest supertest. Separate your server config from your server listener so you don't bind ports during tests:

JavaScript — app.test.js
const request = require("supertest");
const express = require("express");
const app = express();

app.get("/api/health", (req, res) => res.status(200).send("OK"));

describe("GET /api/health", () => {
  it("should return a status code of 200 and OK string payload", async () => {
    const res = await request(app).get("/api/health");
    expect(res.statusCode).toEqual(200);
    expect(res.text).toBe("OK");
  });
});
2 Code Challenge
Challenge: Write a unit test script mapping POST request actions to /api/users. Validate that creating a new user record successfully returns a JSON response containing an ID.