Testing, Performance & Deployment
Node.js API Testing with Supertest
Supertest sends real HTTP requests to an Express app without binding a port, which makes it ideal for integration-testing routes, middleware and status codes end to end.
What is API Testing with Supertest in Node.js?
Supertest sends real HTTP requests to an Express app without binding a port, which makes it ideal for integration-testing routes, middleware and status codes end to end.
API Testing with Supertest example
JavaScript
import request from 'supertest';
import { app } from '../src/app.js';
test('GET /api/jobs returns a list', async () => {
const res = await request(app).get('/api/jobs').expect(200);
assert.ok(Array.isArray(res.body.data));
});
test('POST /api/jobs rejects invalid input', async () => {
const res = await request(app)
.post('/api/jobs')
.send({ title: 'x' }) // too short
.expect(400);
assert.equal(res.body.error, 'Validation failed');
});
test('protected route requires a token', async () => {
await request(app).delete('/api/jobs/1').expect(401);
});Key points to remember
- Export the app separately from the server so tests can import it without listening.
- Use an in-memory MongoDB or a dedicated test database — never the development one.
- Test the unhappy paths: 400, 401, 403, 404. Those are where bugs live.
Common mistakes with API Testing with Supertest
- Importing a file that calls app.listen, leaving the port open after tests finish.
- Tests that depend on each other’s data and fail when run in a different order.
Node.js API Testing with Supertest— Interview Questions & FAQs
How do I test an Express app without starting a server?+
Export the app object from a separate module and pass it to supertest. Supertest binds an ephemeral port internally, so no manual listen call is needed.
