SuperTest: Requests, Assertions & Headers
SuperTest is a Node.js library for testing HTTP servers/APIs, built on top of superagent. It provides a fluent, chainable API for making requests against an app and asserting on the response -- used alongside a test runner like Jest, Mocha, or Vitest, which provides the describe/it structure.
Basic Request & Status Assertion
import request from 'supertest'
import app from './app'
describe('GET /api/users', () => {
it('returns 200 with a list of users', async () => {
// Passing the app instance directly (not a URL) -- SuperTest binds
// to an ephemeral port internally, no need to manually start/stop
// a server on a fixed port
const res = await request(app).get('/api/users').expect(200)
expect(Array.isArray(res.body)).toBe(true)
})
})POST with a JSON Body
it('creates a new user', async () => {
const res = await request(app)
.post('/api/users')
.send({ name: 'Alice', email: 'alice@example.com' }) // auto-serialized to JSON
.expect(201)
expect(res.body.name).toBe('Alice')
})
it('rejects an invalid payload', async () => {
await request(app).post('/api/users').send({}).expect(400)
})Chained & Custom Assertions
await request(app)
.get('/api/users/1')
.expect(200)
.expect('Content-Type', /json/)
.expect((res) => {
// Custom assertion function for anything not covered by the
// built-in status/header/body-match helpers
if (!res.body.email) throw new Error('missing email field')
})Custom Headers & Query Parameters
// Authenticated request -- mirrors a real client sending a bearer token
await request(app)
.get('/api/profile')
.set('Authorization', `Bearer ${validToken}`)
.expect(200)
// Query string, properly URL-encoded automatically
await request(app)
.get('/api/search')
.query({ q: 'test', page: 2 })
.expect(200)Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free