Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 30 ยท Testing Real Applications

Testing APIs and Databases

Test HTTP APIs and database code with Jest: the Supertest idea, test data, in-memory databases, isolation between tests, with runnable node:sqlite and loopback server stand-ins.

Sooner or later your code does more than calculate. It answers HTTP requests and reads and writes a database. These tests are different from pure unit tests: they are slower, they have side effects, and they can poison each other. The craft is to keep them fast, repeatable and independent.

This lesson covers the two classic techniques: calling your API without a real network deployment (the idea behind the Supertest library) and running database code against a throwaway database that is rebuilt for every test. The principles come from Test Isolation and Shared State; here you apply them to bigger pieces.

Real versus stand-in. The Jest, Supertest and database-driver code is real but read-only, since the site cannot install packages or run a database server. The TryIt blocks run on a real Node.js with its built-in node:sqlite module and a real HTTP server on the loopback address, but with a tiny hand-written test runner instead of Jest. They show the same structure, not Jest's output.

Three layers of API tests

Unit Handlers with mocked storage.
Integration Real routes plus a test database.
End to end A deployed system in a browser.

Most of the value sits in the middle layer.

1 / 2

Testing an HTTP API

Suppose your app is an Express-style application that exports an app object without starting it:

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

const todos = [];
app.post("/todos", (req, res) => {
  if (!req.body.title) return res.status(400).json({ error: "title is required" });
  const todo = { id: todos.length + 1, title: req.body.title, done: false };
  todos.push(todo);
  res.status(201).json(todo);
});
app.get("/todos", (req, res) => res.json(todos));

module.exports = app;

Splitting the file that defines app from the file that calls app.listen is the key design decision. Tests import app and never open a fixed port. Supertest then starts the app on a temporary port for each request and tears it down afterwards:

JavaScript
const request = require("supertest");
const app = require("./app");

test("POST /todos creates a todo", async () => {
  const response = await request(app)
    .post("/todos")
    .send({ title: "Write tests" })
    .expect(201);

  expect(response.body).toEqual({ id: 1, title: "Write tests", done: false });
});

test("POST /todos rejects a missing title", async () => {
  const response = await request(app).post("/todos").send({}).expect(400);
  expect(response.body.error).toBe("title is required");
});

There is no deployed server, no port conflict and no network flakiness. Test what a client would see: the status code, the headers and the JSON body. Do not reach into the handler's variables. Notice also that the first test created a todo and the module-level todos array keeps it. That leaked state is exactly what the next sections deal with.

Stand-in 1: a loopback request helper

The stand-in below does what Supertest does at its core. It starts the server on port 0 (the operating system picks a free port), sends a real fetch request, and closes the server. The app uses Node's built-in http module so it needs no packages. The small runner prints PASS or FAIL lines; it is not Jest.

Node.js A mini Supertest on loopback

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The third test passes because createApp() builds a new todo list for every call. That is the cure for the shared-state problem described above: export a factory (createApp) instead of a singleton when you can.

Testing database code

Database tests come in three styles, from fastest to most realistic:

  1. Mock the data layer. Replace the repository with a mock (see Mock Functions with jest.fn). Very fast, but it only proves your code calls the repository correctly, not that the SQL is right.
  2. An in-memory or embedded database. SQLite in memory is created in microseconds. It checks real SQL, with the caveat that SQLite's dialect differs from PostgreSQL or MySQL.
  3. The real database engine in a container. Tools such as Testcontainers start a disposable PostgreSQL for the test run. Slowest, but identical to production.

Teams often combine them: many fast tests with style 1 or 2, and a smaller set with style 3 for migrations and engine-specific features.

Whatever you choose, follow these rules:

  • Never use a shared or production database. Point tests at a separate database through an environment variable such as DATABASE_URL, set in setupFiles.
  • Build the schema in beforeAll (run your real migrations) and reset data in beforeEach, either by truncating tables or by wrapping each test in a transaction that is rolled back.
  • Create the data each test needs inside the test, using small factory functions, so a test explains itself and does not depend on a seed file.
  • Close connections in afterAll. An open pool keeps the Node process alive, and Jest will print that it did not exit cleanly.

If your tests pass alone but fail together, they share data or ports. Run with --runInBand to execute files one at a time; if that fixes it, you have a shared-resource problem. The cure is isolation, not permanent serial runs. See The Jest CLI and Watch Mode.

Stand-in 2: node:sqlite with a fresh database per test

Node 24 includes node:sqlite, an embedded SQLite. The stand-in builds a repository on top of it and gives every test its own in-memory database, which is the simplest possible isolation. It prints a warning that the module is experimental on some versions; ignore it.

Node.js A repository tested against in-memory SQLite

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The last test is a proof of isolation: four tests inserted users, yet the final one sees an empty table. In a Jest file you would write the same shape with beforeEach(() => { db = createDb(); repo = makeUserRepo(db); }) and afterEach(() => db.close()).

Test data without pain

A factory creates valid data with sensible defaults and lets each test override only what matters:

JavaScript
function buildUser(overrides = {}) {
  return { email: "[email protected]", name: "Test User", ...overrides };
}

test("rejects an invalid email", () => {
  const user = buildUser({ email: "not-an-email" });
  expect(() => register(user)).toThrow("invalid email");
});

The test shows the one detail that is special, the bad email, and hides everything else. Compare that with a big shared fixture file, where you cannot tell which row a test depends on.

For external services your API calls, such as a payment provider, do not call the real thing in tests. Mock the HTTP client or the module, as shown in Mocking Modules, and keep one separate, optional contract test for the real service.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should app.js export the application without calling listen()?

    Separating app creation from listening lets Supertest (or your own helper) use a free port per request and shut the server down afterwards.
  2. 2. What is the main advantage of an in-memory database over mocking the repository?

    A mocked repository only proves that your code called it. An in-memory database runs the actual queries, though its SQL dialect can differ from production.
  3. 3. Where is the best place to reset table data between tests?

    Resetting for each test means no test depends on what earlier tests left behind, regardless of order.
  4. 4. Jest warns that it did not exit after tests finished. A likely cause in a database test is

    Open handles such as pools and listening servers keep Node alive. Close them in afterAll or afterEach.

Summary

  • Separate creating the app from listening, so tests can call it on a temporary port; Supertest automates this.
  • Assert on what clients see: status, headers and body.
  • Prefer a fresh app or database per test; export factories rather than singletons.
  • Choose between mocked repositories, in-memory databases and containerized real engines by balancing speed against realism.
  • Never touch shared or production data, build test data with factories, and always close connections.

Next, see how Jest handles TypeScript source and automated pipelines in TypeScript, Babel and CI.