Concept
Integration Testing with Supertest
Unit testing individual middleware functions in isolation is useful, but verifying API contracts requires Integration Testing.
Supertest is a library that spins up an ephemeral instance of your Express server in memory and executes mock HTTP requests against it, returning responses for assert assertions:
import request from 'supertest';
import { expect, test } from 'vitest';
import app from './app'; // Express app (without app.listen)
test('GET /api/v1/users returns status 200 and list', async () => {
const response = await request(app)
.get('/api/v1/users')
.set('Accept', 'application/json');
expect(response.status).toBe(200);
expect(response.body).toBeInstanceOf(Array);
expect(response.body[0]).toHaveProperty('name');
});Isolating Server Startup from App Definition
To test an Express application with Supertest, do not execute app.listen() inside your main app definition file. If you do, running multiple test suites concurrently will cause ports to collide and trigger EADDRINUSE errors.