Skip to content
Tutorials Center
My learning

Topics

Lesson 106 of 133 ยท Testing

Supertest and Sinon: Testing HTTP Routes and Stubbing Dependencies

Learn how Supertest tests an HTTP app without opening a port by hand, how Sinon spies, stubs and fake timers isolate code, and run mini versions of both in the editor.

A web application is tested at two levels. Pure functions and services are checked directly, as in Testing with Jest, Mocha and Chai. But the part that makes it a web application, "this URL, with this body, produces that status and that JSON", needs a real request. And once a route calls something outside your control, such as a payment provider or an e-mail service, you must replace that dependency, or your tests become slow, flaky and expensive.

Two small libraries cover those needs. Supertest sends HTTP requests to your app and lets you chain expectations onto the response. Sinon provides spies (record calls), stubs (replace a function with a scripted one) and fake timers. They are used together so often that "Mocha, Chai, Supertest, Sinon" is practically one phrase, and they work equally well under Jest and node:test.

The packages are not installable in our editor, so the real usage is shown read-only and mini versions are built so you can run the same ideas. The mini versions are slightly simplified, but they follow the real call style: request(app).get('/x').expect(200) and sinon.stub(obj, 'method').resolves(value).

Supertest: request(app)

The key trick is in the argument. Express apps are functions of (req, res), the same shape http.createServer expects. So Supertest can take your app, start it on a random free port, send the request, and shut it down afterwards. Your test never needs app.listen(3000), so there are no port clashes and nothing to clean up.

That trick makes one rule important: export the app without calling listen. Put app.listen in a separate server.js and export default app from app.js. See Project Structure and Architecture for the layout.

JavaScript
import request from 'supertest';
import app from '../src/app.js';

describe('GET /books', () => {
  it('returns the list as JSON', async () => {
    const res = await request(app)
      .get('/books')
      .set('Accept', 'application/json')
      .expect('Content-Type', /json/)
      .expect(200);

    expect(res.body).toEqual([{ id: 1, title: 'Learning Node' }]);
  });

  it('creates a book', async () => {
    await request(app)
      .post('/books')
      .send({ title: 'Streams in Depth' })      // sets the JSON body and content type
      .expect(201)
      .expect((res) => {
        if (!res.body.id) throw new Error('missing id');
      });
  });
});

.get/.post/.put/.delete choose the method, .set() adds a header, .send() adds a body, and each .expect() adds a check: a number for the status, a header name with a string or regular expression, an object for the body, or a function for anything custom. The request is sent when you await it (the object is "thenable"). For cookies and sessions, request.agent(app) keeps cookies between calls, which is how you test a login followed by a protected route.

A mini-Supertest you can run

Here is the same API in about thirty lines on top of fetch, with a deliberately plain Node handler as the "app". An Express app would be passed in exactly the same way.

Node.js A mini-Supertest: request(app).get(...).expect(...)

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.

Notice that the failing check does not crash the file: the error is thrown from the promise, the runner catches it, and the message says what was expected. That is all a failed .expect() is.

Sinon: spies, stubs and fake time

Sinon's building blocks are small and map to three words.

  • A spy wraps a real function and records every call (arguments, return value, how many times) while still running the original.
  • A stub is a spy whose behaviour you replace: .returns(5), .resolves(user), .rejects(new Error('boom')), .throws(), .withArgs(1).returns('a'), .onCall(0).returns(...).
  • Fake timers replace setTimeout, setInterval and Date so clock.tick(60_000) runs a minute's worth of timers instantly.
JavaScript
import sinon from 'sinon';
import * as gateway from '../src/payment-gateway.js';

afterEach(() => sinon.restore());          // undo every stub, so tests stay independent

it('charges the card once and returns 201', async () => {
  const charge = sinon.stub(gateway, 'charge').resolves({ id: 'ch_1', status: 'paid' });

  await request(app).post('/orders').send({ amount: 500 }).expect(201);

  sinon.assert.calledOnceWithExactly(charge, 500);
});

it('answers 502 when the gateway fails', async () => {
  sinon.stub(gateway, 'charge').rejects(new Error('card network down'));
  await request(app).post('/orders').send({ amount: 500 }).expect(502);
});

it('expires the cache after a minute', () => {
  const clock = sinon.useFakeTimers();
  cache.set('a', 1, { ttl: 60_000 });
  clock.tick(60_001);
  expect(cache.get('a')).toBeUndefined();
  clock.restore();
});

Sinon replaces a property on an object: sinon.stub(gateway, 'charge') swaps the charge property of the module namespace object. With native ES modules, namespace objects are read-only, so the usual solution is to design for it: pass the dependency in (a function argument, a parameter of createApp(deps), or a plain exported object) rather than import-and-call. This is the dependency-injection style from Project Structure and Architecture, and it makes tests simple even without Sinon.

A mini-Sinon plus Supertest

This example uses both ideas together on one route. POST /orders charges a card through a gateway object and answers 201 or 502. The tests replace the gateway's charge with stubs, so no card network is ever called.

Node.js A mini-Sinon stubbing a payment gateway behind a route

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 line proves why restore() matters. After every test the original function is put back, so one test's stub can never leak into the next, which is the most common source of "passes alone, fails in the suite" problems.

Habits for stubs and HTTP tests

  • Stub at the edge, not in the middle. Replace the gateway or the HTTP client, not half of your own functions. A test that stubs everything proves nothing.
  • Assert on behaviour first, calls second. "Answers 502" matters more than "called charge twice". Over-specified call checks break whenever you refactor.
  • Restore after every test (afterEach(() => sinon.restore()), or Node's mock.restoreAll()), and never share a stub between tests.
  • Test the error paths. A stub that rejects is the cheapest way to see what your route does when a dependency fails.
  • Do not stub what you can fake. For a database, an in-memory SQLite (see SQLite) is usually better than a stub, because it checks your SQL as well.
  • Test through the HTTP boundary sparingly. A handful of request tests per route cover status codes, validation and headers; business rules belong in plain function tests that run without HTTP. The built-in alternative to Supertest is shown in Testing HTTP Servers.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can Supertest accept your Express app directly, without app.listen()?

    An Express app has the shape http.createServer expects. Supertest creates a server around it on a free port for the length of one request, which avoids port clashes.
  2. 2. What is the difference between a spy and a stub?

    Spies observe. Stubs are spies with scripted behaviour such as returns, resolves or rejects.
  3. 3. Why call sinon.restore() after every test?

    Stubs replace properties on shared objects. Without a restore the replacement stays in place and later tests see fake behaviour.
  4. 4. Which test best checks that a failing payment gateway is handled?

    A rejecting stub produces the failure deterministically and offline, so the error path is tested every time.

Summary

  • Supertest runs your (req, res) app on a random port per request: request(app).post('/x').send(body).expect(201). Export the app without listen.
  • Chain expectations for status, headers, body or a custom function; use request.agent to keep cookies across calls.
  • Sinon spies record calls, stubs script behaviour (returns, resolves, rejects), fake timers control setTimeout and Date.
  • Always restore stubs after a test; prefer injected dependencies, which also work with native ES modules.
  • Stub the outside world, assert on behaviour, test failure paths, and keep most logic testable without HTTP.

Next: MongoDB with Mongoose.