Supertest helps you check if your web server works correctly by sending fake requests and checking the answers.
Supertest for HTTP assertions in 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.
await request(app).get('/users').expect(200);
await request(app).post('/login').send({username: 'bob', password: '123'}).expect(401);
await request(app).get('/data').expect('Content-Type', /json/);
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.
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); })();
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.
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.