How to Use Supertest to Test HTTP APIs in Node.js

Supertest is a fast, flexible way to test HTTP APIs in Node.js. This guide shows how to install it, write rock-solid assertions, integrate with Jest and CI, and when to use an API test platform like Apidog for collaboration, mocking, and end‑to‑end validation.

Oliver Kingsley

Oliver Kingsley

14 August 2025

How to Use Supertest to Test HTTP APIs in Node.js

In the rapidly evolving API landscape, teams need two things: fast feedback at the code level and trustworthy, end‑to‑end validation across environments. Supertest delivers the first—blazing‑fast HTTP assertions for Node.js services. And when you are ready to collaborate across roles, run scenario tests, mock dependencies, and publish documentation, an API testing platform like Apidog completes the picture. This official, objective guide explains how to use Supertest to test APIs, where it shines, and how to pair it with Apidog to accelerate delivery with confidence.

Pro Tip: Turn your Supertest checks into production‑ready quality gates with Apidog. Design API specifications, auto‑mock endpoints, build visual assertions, run CI, and publish API docs—all in one place.
button

What Is Supertest?

Supertest is a lightweight Node.js library for testing HTTP servers. It builds on superagent and lets you write expressive assertions against status codes, headers, and response bodies—without spinning up external clients. It’s ideal when you:

When you need collaboration, API compliance governance, environment orchestration, and visual testing, you’ll complement Supertest with an API test platform like Apidog. The rest of this article shows how to do both.

button

Install and Set Up Supertest

You can install Supertest in minutes. Use npm, pnpm, or yarn:

# npm   npm install --save-dev supertest jest

# pnpm  pnpm add -D supertest jest

# yarn

yarn add -D supertest jest

A minimal Express API (app.js):

const express = require('express');

const app = express();



app.get('/greet', (req, res) => {

  const name = req.query.name || 'World';

  res.json({ message: `Hello, ${name}!` });

});



module.exports = app;

A simple test (app.test.js) using Supertest + Jest:

const request = require('supertest');

const app = require('./app');



describe('GET /greet', () => {

  it('greets anonymously', async () => {

    const res = await request(app)

      .get('/greet')

      .expect('Content-Type', /json/)

      .expect(200);



    expect(res.body.message).toBe('Hello, World!');

  });



  it('greets by name', async () => {

    const res = await request(app)

      .get('/greet?name=Alice')

      .expect('Content-Type', /json/)

      .expect(200);



    expect(res.body.message).toBe('Hello, Alice!');

  });

});

Update package.json to run tests:

{

  "scripts": {

    "test": "jest"

  }

}

Run your tests:

npm test

If you prefer Mocha or Vitest, Supertest works the same—the .expect() API is identical.


Writing Great Supertest Assertions

Supertest’s power comes from its chainable assertions—quick to write and easy to read. Here are patterns you’ll use every day:

request(app)

  .get('/users')

  .expect(200)

  .expect('Content-Type', /json/);
request(app)

  .get('/users')

  .expect(200)

  .expect(res => {

    if (!Array.isArray(res.body)) throw new Error('Expected an array');

    if (res.body.length === 0) throw new Error('Expected at least one user');

  });
request(app)

  .get('/health')

  .expect(200)

  .expect({ status: 'ok' });



request(app)

  .get('/health')

  .expect(200)

  .expect(/"status":"ok"/);
request(app)

  .post('/posts')

  .set('Authorization', 'Bearer test-token')

  .send({ title: 'Hello', body: 'World' })

  .expect(201)

  .expect(res => {

    if (!res.body.id) throw new Error('Missing id');

  });
const agent = request.agent(app);

await agent.get('/login').expect(200);

await agent.get('/me').expect(200).expect(res => {

  if (!res.body.user) throw new Error('Expected authenticated user');

});
Tip: Keep tests small and deterministic. Supertest excels at validating controllers, middleware, and adapters in isolation.

Supertest in CI/CD and Monorepos

To keep quality consistent, run Supertest in CI for every pull request. A typical setup:

Example GitHub Actions snippet:

name: api-tests

on: [push, pull_request]

jobs:

  test:

    runs-on: ubuntu-latest

    steps:

      - uses: actions/checkout@v4

      - uses: actions/setup-node@v4

        with:

          node-version: '20'

      - run: npm ci

      - run: npm test -- --ci

In monorepos, run affected tests only and cache node_modules to speed up feedback loops. Supertest’s minimal overhead makes it a great fit for large codebases.


When to Use an API Test Platform

Supertest is superb for fast, code‑level feedback. But production realities demand more:

This is where an API test platform like Apidog shines. It unifies API design, mocking, testing, debugging and documentation to keep teams aligned and your quality gates durable.

button
Apidog Testing UI

Why Apidog Complements Supertest


A Combined Workflow: Supertest + Apidog

Use Supertest for developer‑centric checks and Apidog for end‑to‑end collaboration. Here’s a pragmatic split of responsibilities:

Task
Supertest
Apidog
Controller/middleware unit checks
Excellent
Complementary
Quick contract regressions (status/headers)
Excellent
Excellent
Schema governance (OpenAPI)
Manual
First‑class
Mock servers for front‑end
Limited
Built‑in
Data‑driven scenarios
Limited
First‑class
CI orchestration across envs
Good
First‑class
Team collaboration/docs
Minimal
First‑class

Example flow:


Advanced Supertest Patterns

A few additional tips that pay off:


Conclusion: A Balanced Approach to API Quality

Quality APIs are built with both speed and rigor. Supertest gives developers a fast, expressive way to verify endpoints near the code—perfect for tight feedback loops and catching regressions before they escape a branch. It’s simple, dependable, and battle‑tested across many Node.js backends.

As systems grow, however, you need collaboration, contract governance, and environment‑aware execution. That’s where Apidog—an integrated API test platform—elevates your workflow. By unifying contract design (OpenAPI), mock servers, visual assertions, environment variables, and CI orchestration, Apidog helps teams move in lockstep from idea to delivery. Front‑end, back‑end, and QA can share the same source of truth while Supertest continues to guard your code paths with swift, deterministic assertions.

If you want confident velocity, use both:

This balanced approach yields APIs that are not only correct today but resilient as your product evolves. Start writing your Supertest checks now—and bring them to life in a production‑grade pipeline with Apidog.

button

Explore more

How to Use Wave – An Open-source Terminal

How to Use Wave – An Open-source Terminal

Wave Terminal is an open-source terminal that blends classic command-line power with modern graphical tools, file previews, web browsing, and AI assistance. This guide shows you how to install, customize, and master Wave Terminal.

13 August 2025

How to Use BlueJ - A Free Java Development Environment for Beginners

How to Use BlueJ - A Free Java Development Environment for Beginners

BlueJ is a free Java development environment that makes learning object-oriented programming simple and interactive. This guide shows you how to install, use, and master BlueJ's visual tools.

13 August 2025

How to Set an Enumeration for a Field (e.g. string, array, etc.) in Apidog

How to Set an Enumeration for a Field (e.g. string, array, etc.) in Apidog

Set Apidog enumerations for strings, arrays, and more with this guide. Learn to use AI, JSON Schema, and reusable models for clear, error-free API documentation and testing.

13 August 2025

Practice API Design-first in Apidog

Discover an easier way to build and use APIs