skip to content

HTTP Route Testing

Driving an Express app over HTTP with Supertest: status, header and body assertions on an exported app, plus error and sign-in paths. Interviewers ask why the app is exported and listen never called.

on this pageshow

questions

5

With Supertest against an Express app, how do chained .expect calls assert status, headers and body, and what does each form compare?

level: juniorimportance: must knowfreq 58%

answer

  1. the argument types pick the check
  2. number, field and value, or body
  3. RegExp for Content-Type
  4. object body means deep equality

basics

~20 s

Supertest's .expect picks its check from the arguments: a number asserts the status, a field and a value assert a header, and a string, RegExp or object asserts the body. Checks run in the order written and the first failure is reported.

solid answer

~30 s

Supertest reads the arguments: `.expect(200)` checks the status, `.expect(200, body)` adds a body check, `.expect('Content-Type', /json/)` checks a header, `.expect(body)` checks only the body and `.expect(fn)` runs a custom assertion that throws to fail. A header value given as a string must match exactly, so `'application/json'` fails against Express's `application/json; charset=utf-8`; use a RegExp. An object body is compared with deep strict equality against the parsed `res.body`, so an extra field fails it, while a string must equal `res.text` exactly. The expectations run in the order you chained them, and the first one that fails becomes the error the test sees.

code

javascript · 23 lines
javascript
const { test } = require('node:test');
const request = require('supertest');
const app = require('./app');

test('GET /api/health answers JSON', async () => {
  await request(app)
    .get('/api/health')
    .set('Accept', 'application/json')
    .expect('Content-Type', /json/)       // header: RegExp match
    .expect(200, { status: 'ok' });      // status, then deep-equal body
});

test('POST /login rejects a wrong password', async () => {
  await request(app)
    .post('/login')
    .send({ password: 'wrong' })          // object -> JSON body
    .expect(401)
    .expect((res) => {
      if (res.body.error !== 'invalid_credentials') {
        throw new Error(`unexpected error code ${res.body.error}`);
      }
    });
});

go deeper

for a junior

Recall the forms: a number for status, a header name and value, a body, or a function, and that they chain on one request.

for a middle

Explain the comparisons: exact string versus RegExp for headers, deep strict equality for object bodies, res.text for strings, and order of evaluation.

for a senior

Write assertions that fail with a useful message: status first, RegExp for parameterised headers, partial checks where fields are generated.

for a principal

Decide what a team asserts on every route test, such as status, content type and body shape, so suites stay strict without becoming brittle.

## One method, several assertions **Supertest** describes an HTTP request against an app and then checks the response. The request side uses the underlying client's methods: `.get(path)`, `.post(path)`, `.set(field, value)` for a request header, `.send(data)` for a body, `.auth(user, password)` for Basic credentials and `.bearer(token)` as a shortcut for an `Authorization: Bearer` header. The response side is one overloaded method, **`.expect()`**, whose behaviour is decided by the types of its arguments. | Call | What it asserts | Compared how | |---|---|---| | `.expect(200)` | status code | strict equality with `res.status` | | `.expect([200, 204])` | status is one of a list | membership | | `.expect(200, body)` | status, then body | as the body forms below | | `.expect('Content-Type', value)` | one response header | string: exact; RegExp: `test()` | | `.expect({ id: 7 })` | parsed body | deep strict equality with `res.body` | | `.expect('done')` | raw body text | exact equality with `res.text` | | `.expect(/done/)` | raw body text | RegExp match on `res.text` | | `.expect(fn)` | anything | `fn(res)` throws (or returns an `Error`) to fail | A trailing callback, as in `.expect(200, done)`, also ends the request and hands the result to that callback. ## The details that trip people up - **Header strings are exact.** Express's `res.json()` sends `Content-Type: application/json; charset=utf-8`, so `.expect('Content-Type', 'application/json')` fails. A RegExp such as `/json/` matches the media type and ignores the parameter. Header names are looked up case-insensitively, so `'content-type'` works too. - **Object bodies are compared whole.** The object form uses deep strict equality against the parsed JSON body. If the route also returns `uptime`, the assertion fails. When only some fields matter, use `.expect(fn)` or assert on `res.body` after awaiting. - **String bodies are compared as text.** `.expect('ok')` compares with `res.text`, the unparsed body, so a JSON response never equals a plain string unless the text matches character for character. - **`.send()` decides the request's content type.** An object is serialised as JSON with `Content-Type: application/json`; a string such as `'name=ada'` is sent as `application/x-www-form-urlencoded`. The Express app must mount the matching parser (`express.json()` or `express.urlencoded()`), or the route sees no parsed body. ## Order and the first failure Expectations are stored as you chain them and run **in definition order** once the response arrives. The first failing one stops the run and becomes the error, with a message such as `expected 200 "OK", got 404 "Not Found"`. Two consequences: 1. Put the status first. If the route answered 500, a status failure says so directly, while a body assertion placed first would complain about a missing field and hide the real cause. 2. A custom function placed early may **modify** `res.body` (normalising a generated id, say) before a later object-body comparison runs; this is a documented use, and also a trap when it is accidental. ## Custom assertions and awaiting the response `.expect(fn)` receives the response object. It fails by throwing, which is how the test runner's own `assert` functions behave, so `assert.strictEqual(res.body.error, 'invalid_credentials')` inside the function works. The alternative is to `await` the chain, take the response it resolves with, and assert on `res.status`, `res.headers` and `res.body` with the runner's assertions. Both are fine; mixing the two styles is fine too, as long as the chain itself is awaited or returned. ## Multiple statuses and request helpers `.expect([200, 304])` passes when the status is any listed code, which suits a conditional GET that may answer either. On the request side, `.auth('user', 'pass')` sends Basic credentials and `.bearer(token)` is a shortcut for `.set('Authorization', 'Bearer ' + token)`. Both only shape the request; what the route does with the credentials is still asserted with `.expect()`, so a protected route test pairs one of them with the status and body it should produce. ## What the response object holds - `res.status`: the numeric status code; - `res.headers`: the response headers, keyed in lower case; - `res.body`: the body parsed by content type (JSON becomes an object); - `res.text`: the raw body as a string. ## Summing up Read the call as a sentence: a number is a status, two values starting with a header name are a header, and anything else is a body. Prefer RegExp for headers with parameters, deep equality only when the whole body is the contract, and status first in every chain.

  • How do you assert just one field of a JSON response with Supertest when other fields vary between runs?
    Pass a function: `.expect((res) => { ... })` that throws when the field is wrong, or await the chain and assert on `res.body.field` with the runner's assertions. The object form `.expect({ ... })` is a deep strict comparison of the whole body, so it fails on any extra or differing field.
  • In Supertest, what does .expect(200, done) do differently from .expect(200)?
    Adding the callback ends the request: Supertest dispatches it, runs the expectations and calls `done(err, res)`, with `err` set to the first failed expectation. Without a callback or an `await`, the chain only records the assertion and nothing is sent yet.

  • .expect('Content-Type', 'application/json') passes for any JSON response.
  • An object passed to .expect only needs to contain the listed fields.
  • Supertest runs every expectation and reports all the failures together.
  • .expect('ok') checks a field called ok in the JSON body.
  • Header names in .expect must match the exact case the server sent.
open as a page

When testing an Express 5 app with Supertest, why does app.js export the app and leave app.listen to a separate entry file?

level: juniorimportance: must knowfreq 62%

basics

~20 s

Supertest's request(app) takes the Express app, a plain request-handler function, and runs it on its own server on an ephemeral port, closed afterwards. An app module that calls listen grabs a fixed port at import and keeps the test process from exiting.

open as a page

In a Supertest suite for an Express app, why can a test that never awaits or returns its request(app) chain pass, and what does it leave behind?

level: middleimportance: should knowfreq 42%

basics

~20 s

A Supertest chain sends nothing until .then() (which await calls) or .end() runs, so a test that only builds it returns at once and is reported as passing. The ephemeral server Supertest already started is never closed, so the run can hang.

open as a page

How do you test an Express 5 error path with Supertest so the assertion proves your four-argument error handler answered, not the default handler?

level: middleimportance: should knowfreq 45%

basics

~20 s

Assert more than the status: Express 5's default error handler also takes the status from err.status, but it answers text/html with the stack outside production. Expect your JSON content type and body shape, so a test only passes when the custom handler ran.

open as a page

With Supertest, how do you test a login-protected Express route, and why can a shared request.agent make an anonymous-access test pass or fail depending on test order?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Supertest's request(app) keeps no cookies between calls, while request.agent(app) stores each Set-Cookie and sends it on later requests. An agent shared across tests carries one test's login into the next, so an anonymous-access check depends on order.

open as a page