Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 43 ยท Quality and Operations

Testing Express Apps

Test Express apps: separate app from listen, use supertest and node:test, mock services, and check middleware and errors, with runnable fetch-based tests.

An Express app is a function from request to response, which makes it pleasant to test. You send a request, look at the status, headers and body, and compare them with what you expect. No browser is needed. The skill is mostly in structure: build your app so a test can start it, call it and throw it away.

The real tools, supertest and the built-in node:test runner, are shown read-only, since npm packages cannot be installed on this site. The runnable examples test our mini Express with plain fetch and node:assert, which is exactly the technique supertest automates. For the test runner itself, see The Node.js Test Runner and Testing HTTP Servers.

Testing recipe

Export the app Build it in one file, listen in another.
Send requests supertest or fetch against port 0.
Assert Status, headers, JSON body.

Fast tests are tests you actually run.

1 / 2

Separate the app from listen

The one structural rule: do not call app.listen in the file that builds the app. If importing the app starts a server, every test file fights over a port. Split it in two:

JavaScript
// app.js: builds and exports the app, never listens
import express from 'express';

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

  app.get('/users/:id', async (req, res) => {
    const user = await userService.findById(req.params.id);
    if (!user) return res.status(404).json({ error: 'User not found' });
    res.json(user);
  });

  return app;
}
JavaScript
// server.js: the only file that listens
import { createApp } from './app.js';
import { userService } from './services/users.js';

createApp({ userService }).listen(3000, () => console.log('listening on 3000'));

A factory like createApp also lets tests hand in fake dependencies, which we use below. This matches the layers from Controllers and Services and Project Setup and Structure.

Tests with node:test and supertest

Node 20+ ships with a test runner (node:test), and supertest wraps your app in a temporary server on a random port:

JavaScript
// app.test.js
import { test } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { createApp } from './app.js';

const fakeUsers = {
  findById: async (id) => (id === '1' ? { id: '1', name: 'Ada' } : null),
};
const app = createApp({ userService: fakeUsers });

test('GET /users/1 returns the user', async () => {
  const res = await request(app).get('/users/1').expect(200);
  assert.deepEqual(res.body, { id: '1', name: 'Ada' });
});

test('GET /users/9 returns 404', async () => {
  const res = await request(app).get('/users/9');
  assert.equal(res.status, 404);
  assert.equal(res.body.error, 'User not found');
});

Run it with node --test. Jest and Vitest work the same way; only the test/expect lines differ. request(app) accepts the app function directly, so no port is involved. With a POST you add .send({ name: 'Grace' }) (JSON) or .set('Authorization', 'Bearer ...') for headers.

The same technique with fetch

supertest is convenient, but it is not magic: start the app on port 0 (the operating system picks a free port), send requests, close the server. This tiny runner does the same and prints one line per test:

Node.js A tiny test runner for routes

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 deliberate failure shows what a failed assertion looks like: assert.equal(actual, expected) throws an AssertionError that carries both values. In node:test the runner collects these for you and prints a diff.

Mocking services and other dependencies

Tests should not need a real database, mail server or payment API. They would be slow, flaky and could change real data. Because createApp receives its dependencies, a test passes fakes. Here a service is replaced with one that records calls and can be told to fail:

Node.js Injecting a fake service

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 same test file now covers both the happy path and a failure that is almost impossible to trigger with a real mail server. With node:test you can also use mock.fn() to build the fake and assert how often it was called. When you cannot inject (for example a module that imports its own database client), mock.method or module mocking can replace it, but dependency injection keeps tests simpler.

Testing middleware and errors

Test middleware in the app, through a request, so you check the behavior users see: a guard returns 401 without a token, a limiter returns 429, an error handler turns a thrown error into JSON. For a middleware in isolation, call it with fake req, res and next objects:

JavaScript
test('requireAuth rejects missing tokens', () => {
  const res = { status(code) { this.code = code; return this; }, json(body) { this.body = body; } };
  let nextCalled = false;

  requireAuth({ headers: {} }, res, () => { nextCalled = true; });

  assert.equal(res.code, 401);
  assert.equal(nextCalled, false);
});

Error paths deserve their own tests: an invalid body returns 422, a missing record returns 404, and a crashing handler returns a generic 500 without leaking a stack trace (Error Handling). Also test authorization from both sides: a user can read their own record, and cannot read someone else's.

Habits that keep tests healthy

  • Give every test its own data, and reset state between tests, so they pass in any order.
  • Use a separate test database (often in-memory SQLite or a throwaway container) and set NODE_ENV=test.
  • Test behavior (status and body), not internals such as which function was called.
  • Keep the suite fast; it should run on every save and in CI before every deploy.
  • Fix flaky tests immediately. A test nobody trusts is worse than none.

Write a failing test first for each bug you fix. It proves you reproduced the bug, and it stops the bug from coming back.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should app.listen not be called in the file that creates the app?

    Splitting app.js from server.js lets tests import the app and start it on a random port, or hand it to supertest directly.
  2. 2. What does listening on port 0 do?

    Port 0 avoids conflicts between parallel tests, because each gets its own free port.
  3. 3. Why inject services (such as a mailer) into createApp?

    Fakes make tests fast, deterministic and safe, and let you simulate failures on demand.
  4. 4. What is a good way to test an auth guard middleware?

    Testing through a request checks the behavior clients actually see, including status and body.

Summary

  • Export a createApp factory and listen only in server.js.
  • supertest (or fetch on port 0) sends requests without manual server setup; node --test runs the suite.
  • Inject dependencies so tests can use fakes for databases, mailers and payment APIs.
  • Test routes, validation failures, 404s, thrown errors and authorization, not only happy paths.
  • Keep tests independent, fast and run on every change in CI.

Next: Performance and Caching.