0
0
Expressframework~5 mins

Supertest for HTTP assertions in Express

Choose your learning style9 modes available
Introduction

Supertest helps you check if your web server works correctly by sending fake requests and checking the answers.

You want to make sure your website's API sends the right data back.
You need to test if your server handles errors properly.
You want to check if your routes respond with the correct status codes.
You want to automate testing so you don't have to check manually every time.
You want to test your server without opening a browser.
Syntax
Express
const request = require('supertest');
const app = require('./app');

describe('GET /path', () => {
  it('responds with status 200', async () => {
    await request(app)
      .get('/path')
      .expect(200)
      .expect('Content-Type', /json/);
  });
});

Use request(app) to start testing your Express app.

Chain methods like .get(), .post(), and .expect() to define the test.

Examples
Check if GET /users returns status 200 (OK).
Express
await request(app).get('/users').expect(200);
Send a POST request with data and expect a 401 Unauthorized response.
Express
await request(app).post('/login').send({username: 'bob', password: '123'}).expect(401);
Check if the response has JSON content type.
Express
await request(app).get('/data').expect('Content-Type', /json/);
Sample Program

This example creates a simple Express app with one route /hello that returns a JSON message. Then it uses Supertest to send a GET request to /hello, checks the status and content type, and prints the response body.

Express
const express = require('express');
const request = require('supertest');

const app = express();
app.use(express.json());

app.get('/hello', (req, res) => {
  res.status(200).json({message: 'Hello, world!'});
});

// Test
(async () => {
  const response = await request(app)
    .get('/hello')
    .expect(200)
    .expect('Content-Type', /json/);

  console.log(response.body);
})();
OutputSuccess
Important Notes

Supertest works well with testing frameworks like Jest or Mocha for better test organization.

Always close your server or use app instances to avoid conflicts in tests.

You can chain multiple .expect() calls to check status, headers, and body.

Summary

Supertest lets you test your Express server by sending fake HTTP requests.

You can check status codes, response headers, and response bodies easily.

It helps catch bugs early by automating server tests without a browser.