Testing and Deploying Express APIsLesson 6.1
How to test Express routes with Jest and Supertest
supertest library, jest test runner, describe it blocks, request(app).get, expect status, expect body, beforeEach afterEach, test isolation, app export pattern
Testing Express Routes with Supertest
Supertest lets you fire real HTTP requests against your Express app without starting a server on a port. Jest provides the test runner and assertions.
npm install --save-dev jest supertestapp.js — export without listening
const express = require('express');
const app = express();
app.use(express.json());
app.get('/health', (req, res) => res.json({ status: 'ok' }));
app.post('/users', (req, res) => {
if (!req.body.name) return res.status(400).json({ error: 'name required' });
res.status(201).json({ id: 1, name: req.body.name });
});
module.exports = app;tests/app.test.js
const request = require('supertest');
const app = require('../app');
describe('Health check', () => {
it('GET /health returns 200 with status ok', async () => {
const res = await request(app).get('/health');
expect(res.statusCode).toBe(200);
expect(res.body.status).toBe('ok');
});
});
describe('POST /users', () => {
it('creates a user when name is provided', async () => {
const res = await request(app)
.post('/users')
.send({ name: 'Alice' })
.set('Content-Type', 'application/json');
expect(res.statusCode).toBe(201);
expect(res.body.name).toBe('Alice');
});
it('returns 400 when name is missing', async () => {
const res = await request(app).post('/users').send({});
expect(res.statusCode).toBe(400);
});
});Run tests: npx jest. Add "test": "jest" to package.json scripts.
