CodePark/ questions / HTTP / API tests with supertest
START PRACTICINGPRACTICE
Backend question · Backend testing › HTTP / API tests with supertest

How do you test a protected endpoint with supertest? What should a test check about the status, the body and the auth behaviour?

import request from 'supertest';

it('GET /me returns the current user', async () => {
  const res = await request(app)
    .get('/me')
    .set('Authorization', `Bearer ${token}`)
    .expect('Content-Type', /json/)
    .expect(200);
  expect(res.body).toMatchObject({ id: user.id, email: user.email });
  expect(res.body).not.toHaveProperty('passwordHash');
});

it('rejects a missing token', () =>
  request(app).get('/me').expect(401));

Pass your app to request(app), chain the HTTP call, and check the status, headers and body. Then test three auth cases: no token, a valid token, and a token without permission.

request(app) accepts any of these:

  • an Express app
  • a Node http.Server
  • in Nest, app.getHttpServer()

supertest starts the server on a free port by itself, so you don't call listen().

Build the request in steps:

  • Choose the method: .get(), .post() and so on.
  • Add headers with .set().
  • Send a JSON body with .send().
  • Check the result with .expect(status) or .expect(header, value).

Await the chain, or return it from the test. Then check res.body with normal Jest matchers.

For auth, cover at least three cases:

  • No token gives 401 (not logged in).
  • A valid token gives 200 with the right user.
  • A valid token for a user without permission gives 403 (logged in, but not allowed).

Get the token the way a real client would. Call the login endpoint in beforeAll, or sign a JWT with the test secret. Also check what must not be in the body, such as password hashes.

  • Use request(app) or request(app.getHttpServer()). You don't need to call listen().
  • Set headers, send the body, expect the status and headers, and await the chain.
  • Check res.body with Jest matchers, and check that sensitive fields are absent.
  • Test auth three ways: 401 without a token, 200 with a valid token, 403 without permission.