Testing APIs in Node.js: Jest and Supertest Tutorial with Runnable Examples

Build a small Express task API and test its routes, validation, headers, JSON responses and state changes without opening a fixed server port.

KnowledgeGate Team

Exam prep & CS education

Updated 25 Nov 20266 min read
Testing APIs in Node.js: Jest and Supertest Tutorial with Runnable Examples

An Express route can look correct in a browser while a validation change, wrong status code or altered response shape silently breaks its clients. A Jest plus Supertest suite proves the HTTP contract of a runnable task API without starting a server on a fixed port. Each test gets a fresh in-memory Map, not MongoDB or production data. That isolates deterministic state, success and failure assertions, and the boundary where a real database needs its own integration test.

Testing APIs in Node.js: choose the boundary before the tool

A unit test might call a title validator directly. An API integration test sends an HTTP-shaped request through Express JSON middleware and routes with Supertest. An end-to-end test instead calls a separately running service with its real dependencies. Supertest gives us the middle boundary, not full end-to-end coverage.

Here, a contract means method, path, input, status, headers, JSON body and state change. For POST /api/tasks, the valid input {"title":"Revise HTTP status codes"} must produce status 201, Location: /api/tasks/1 and {"id":1,"title":"Revise HTTP status codes","done":false}. The Application Layer Protocols: DNS and HTTP Guide explains the HTTP ideas behind methods, status codes and headers.

Tests import the Express app, not listen(3000). Supertest exercises it directly, avoiding port conflicts and open-handle cleanup.

Set up the Node.js API test project with Jest and Supertest

Create a CommonJS project so module-format setup does not distract from the test boundary:

bash
mkdir node-api-test-demo
cd node-api-test-demo
npm init -y
npm install express
npm install --save-dev jest supertest

Change the package.json test script to:

json
"test": "jest --runInBand"

Create app.js, server.js and app.test.js. The application factory owns the routes and private state:

js
// app.js
const express = require("express");

function createApp() {
  const app = express();
  app.use(express.json());

  const tasks = new Map();
  let nextId = 1;

  app.post("/api/tasks", (req, res) => {
    const title =
      typeof req.body?.title === "string" ? req.body.title.trim() : "";

    if (!title) {
      return res.status(400).json({ error: "title is required" });
    }

    const task = { id: nextId++, title, done: false };
    tasks.set(task.id, task);
    return res
      .status(201)
      .location("/api/tasks/" + task.id)
      .json(task);
  });

  app.get("/api/tasks/:id", (req, res) => {
    const task = tasks.get(Number(req.params.id));
    if (!task) {
      return res.status(404).json({ error: "task not found" });
    }
    return res.status(200).json(task);
  });

  return app;
}

module.exports = { createApp };

The state is inside createApp(), so every new app has an empty store and starts numbering at 1.

Build one small Express API whose contract is observable

POST /api/tasks trims title only when the incoming value is a string. A missing body, three spaces or the number 42 therefore reaches the same controlled branch: status 400 with {"error":"title is required"}. That branch returns before nextId changes or the Map receives a record.

A valid title creates { id: nextId++, title, done: false }, stores it under its numeric ID and returns 201 with the location and JSON task. The first valid request gets ID 1. GET /api/tasks/:id converts the parameter with Number, reads the key and returns status 200 with the task. An absent key such as 99 returns 404 with {"error":"task not found"}.

POST and GET are enough to expose validation, creation, retrieval, headers, missing-record handling and state isolation. Update, delete, list and pagination add REST-design decisions, but they do not change the Jest and Supertest boundary.

Keep manual server startup separate:

js
// server.js
const { createApp } = require("./app");

const PORT = process.env.PORT || 3000;
const app = createApp();

app.listen(PORT, () => {
  console.log(`Task API listening on port ${PORT}`);
});

Use node server.js only for manual smoke tests. npm test needs no background server. Timestamps, random IDs, authentication and a database would hide the lesson behind unrelated setup.

Pipeline diagram shows Jest creating task 1 through POST, receiving 201 and Location /api/tasks/1, then retrieving it with GET and receiving 200.

Write the first Node.js API test from request to exact response

The test imports createApp, never server.js. beforeEach gives every test a fresh application, while the two requests inside the success test share one instance:

js
// app.test.js
const request = require("supertest");
const { createApp } = require("./app");

describe("tasks API", () => {
  let app;

  beforeEach(() => {
    app = createApp();
  });

  test("creates a task and reads it back", async () => {
    const created = await request(app)
      .post("/api/tasks")
      .send({ title: "Revise HTTP status codes" });

    expect(created.status).toBe(201);
    expect(created.headers["content-type"]).toMatch(/json/);
    expect(created.headers.location).toBe("/api/tasks/1");
    expect(created.body).toEqual({
      id: 1,
      title: "Revise HTTP status codes",
      done: false,
    });

    const fetched = await request(app).get("/api/tasks/1");
    expect(fetched.status).toBe(200);
    expect(fetched.body).toEqual(created.body);
  });

  test("rejects a blank title", async () => {
    const rejected = await request(app)
      .post("/api/tasks")
      .send({ title: "   " });
    expect(rejected.status).toBe(400);
    expect(rejected.body).toEqual({ error: "title is required" });

    const created = await request(app)
      .post("/api/tasks")
      .send({ title: "Write four API tests" });
    expect(created.status).toBe(201);
    expect(created.body).toEqual({
      id: 1,
      title: "Write four API tests",
      done: false,
    });
  });

  test("rejects a missing title", async () => {
    const response = await request(app).post("/api/tasks");
    expect(response.status).toBe(400);
    expect(response.body).toEqual({ error: "title is required" });
  });

  test("rejects a non-string title", async () => {
    const response = await request(app)
      .post("/api/tasks")
      .send({ title: 42 });
    expect(response.status).toBe(400);
    expect(response.body).toEqual({ error: "title is required" });
  });

  test("returns 404 for a missing task", async () => {
    const response = await request(app).get("/api/tasks/99");
    expect(response.status).toBe(404);
    expect(response.body).toEqual({ error: "task not found" });
  });
});

Status and body both matter: 200 on creation is wrong, as is 201 with a missing location or wrong schema. The first POST changes the Map from 0 records to 1; GET creates none. Always await or return each Supertest chain.

Test validation, missing data and test isolation

rejects a blank title leaves 0 records and nextId at 1, so its following valid POST creates ID 1, not ID 2. An omitted body and a numeric title also return 400; GET 99 returns 404.

Each test starts with 0 records because beforeEach calls createApp(). The first two tests each finish with 1 record in separate Maps; the other three finish with 0. Order cannot leak records or IDs.

Four-lane test-flow diagram shows isolated Maps, successful creation of ID 1, validation failures at 0 records, and a missing task returning 404.

Separate API route tests from real-database integration tests

The next architectural step is to put Map operations behind a taskStore interface and inject it through createApp({ taskStore }). Most route-contract tests can use a deterministic fake while still exercising Express, JSON parsing, routing and response formatting. A fake that returns a task does not prove MongoDB persistence.

Test persistence separately with a disposable test database. Create only test-owned data, await setup and cleanup, and never target production. Cover schema validation, one create-and-read path and relevant database errors. Mongoose Schemas and Models is the next concept for schemas and validation, though it is not a ready-made test environment.

Place external APIs behind injected clients and stub them deterministically. Routine tests should not depend on the public internet, time of day or another team's live service.

Common Node.js API testing mistakes and assessment prompts

Mistake

What goes wrong

Repair

Importing a module that calls listen

Jest can retain an open server handle

Export the app and start it only in server.js

Sharing one Map

Records and IDs leak across tests

Call createApp() in beforeEach

Omitting await

Jest can report a false pass

Await or return every Supertest chain

Asserting only status

Header and body regressions go unseen

Check the complete HTTP contract

Mocking req and res

Express parsing and routing are bypassed

Keep an HTTP-boundary test with Supertest

Three useful interview, lab or code-review prompts follow directly from the suite:

  1. What ID follows a blank title and one valid POST? ID 1, because rejection does not increment nextId.

  2. Why can GET /api/tasks/1 return 404 after a successful POST? A newly created app owns a different empty Map.

  3. Why does 201 with the wrong Location fail? The header is part of the promised client contract.

Testing APIs in Node.js: the short version and next step

Define the HTTP contract, export the Express app, keep listen separate, start every test with fresh state, assert status, headers, body and state, and reserve real dependencies for explicit integration tests. In this fixture, success means 201, /api/tasks/1 and task ID 1; controlled failures return 400 or 404.

Continue with the Node.js, Express.js & MongoDB Course. For a broader full-stack route, use the MERN Stack Course, or browse Skill Development Courses. The in-memory fixture proves its chosen boundary, not production readiness.