Module 1 · Our first Express application
1.5 First tests, and the limits of memory
Separate the app from the server so tests can import it, write HTTP tests with node:test and Supertest, and watch in-memory data disappear.
Starting point
src/server.js holds the whole application: configuration, middleware, data, routes, error handling, and the app.listen call. We test it by hand with curl and the browser.
Outcome
caretaker/├── src/│ ├── app.js ← builds and exports the Express app│ └── server.js ← imports the app and listens on a port└── test/ └── issues.test.jsnpm test sends real HTTP requests to the app, without opening a port, and checks status codes, JSON and HTML. You will also see two concrete reasons why the array of issues has to go.
The problem
Every lesson so far ended with "run these curl commands and compare". That does not scale. Each new feature can break an old one, and from Module 5 on, most of our tests check who may do what: dozens of user, resource and action combinations. We need tests a machine runs in seconds.
There is a structural problem first. Tests want to import the app, but importing src/server.js also calls app.listen(3000). That fails if the dev server is running, and it leaves a process that never ends.
Build it
1. Split the app from the server
Rename the file with Git, so Git records a move rather than a delete and a create:
git mv src/server.js src/app.js
In src/app.js, export the app and drop everything about ports:
const app = express();const port = 3000;export const app = express();
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path'; export const app = express(); app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }); app.use((req, res, next) => { const started = Date.now(); res.on('finish', () => { console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`); }); next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.json());app.use(express.urlencoded({ extended: false })); const issues = [ { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' }, { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' }, { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; const PRIORITIES = ['low', 'medium', 'high', 'critical']; function validateIssue(input) { const errors = {}; const title = typeof input.title === 'string' ? input.title.trim() : ''; const building = typeof input.building === 'string' ? input.building.trim() : ''; if (title.length < 3 || title.length > 200) { errors.title = 'Title must be between 3 and 200 characters.'; } if (!PRIORITIES.includes(input.priority)) { errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`; } if (building.length === 0) { errors.building = 'Building is required.'; } return { errors, values: { title, priority: input.priority, building } };} app.get('/', (req, res) => { res.redirect('/issues');}); app.get('/api/issues', (req, res) => { const { status } = req.query; const result = status ? issues.filter((issue) => issue.status === status) : issues; res.json(result);}); app.get('/api/issues/:id', (req, res) => { const id = Number(req.params.id); const issue = issues.find((e) => e.id === id); if (!issue) { return res.status(404).json({ error: 'Issue not found' }); } res.json(issue);}); let nextId = 4; app.post('/api/issues', (req, res) => { const { errors, values } = validateIssue(req.body ?? {}); if (Object.keys(errors).length > 0) { return res.status(400).json({ errors }); } const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() }; issues.push(issue); res.status(201).location(`/api/issues/${issue.id}`).json(issue);}); app.get('/issues', (req, res) => { res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', (req, res) => { res.render('issues/new', { title: 'Report an issue', values: {}, errors: {}, priorities: PRIORITIES });}); app.post('/issues', (req, res) => { const { errors, values } = validateIssue(req.body ?? {}); if (Object.keys(errors).length > 0) { return res.status(400).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES }); } const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() }; issues.push(issue); res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/:id', (req, res) => { const issue = issues.find((e) => e.id === Number(req.params.id)); if (!issue) { return res.status(404).render('not-found', { title: 'Not found', path: req.path }); } res.render('issues/show', { title: issue.title, issue });}); app.use((req, res) => { if (req.path.startsWith('/api/')) { return res.status(404).json({ error: `No route for ${req.method} ${req.path}` }); } res.status(404).render('not-found', { title: 'Not found', path: req.path });}); app.use((err, req, res, next) => { const status = err.status ?? 500; if (status >= 500) { console.error(err); } const message = err.expose ? err.message : 'Something went wrong'; if (req.path.startsWith('/api/')) { return res.status(status).json({ error: message }); } res.status(status).render('error', { title: 'Error', status, message });}); app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});import express from 'express';
import path from 'node:path';
export const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(import.meta.dirname, '..', 'views'));
app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });
app.use((req, res, next) => {
const started = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);
});
next();
});
app.use(express.static(path.join(import.meta.dirname, '..', 'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const issues = [
{ id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },
{ id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },
{ id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },
];
const PRIORITIES = ['low', 'medium', 'high', 'critical'];
function validateIssue(input) {
const errors = {};
const title = typeof input.title === 'string' ? input.title.trim() : '';
const building = typeof input.building === 'string' ? input.building.trim() : '';
if (title.length < 3 || title.length > 200) {
errors.title = 'Title must be between 3 and 200 characters.';
}
if (!PRIORITIES.includes(input.priority)) {
errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;
}
if (building.length === 0) {
errors.building = 'Building is required.';
}
return { errors, values: { title, priority: input.priority, building } };
}
app.get('/', (req, res) => {
res.redirect('/issues');
});
app.get('/api/issues', (req, res) => {
const { status } = req.query;
const result = status ? issues.filter((issue) => issue.status === status) : issues;
res.json(result);
});
app.get('/api/issues/:id', (req, res) => {
const id = Number(req.params.id);
const issue = issues.find((e) => e.id === id);
if (!issue) {
return res.status(404).json({ error: 'Issue not found' });
}
res.json(issue);
});
let nextId = 4;
app.post('/api/issues', (req, res) => {
const { errors, values } = validateIssue(req.body ?? {});
if (Object.keys(errors).length > 0) {
return res.status(400).json({ errors });
}
const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };
issues.push(issue);
res.status(201).location(`/api/issues/${issue.id}`).json(issue);
});
app.get('/issues', (req, res) => {
res.render('issues/index', { title: 'Maintenance issues', issues });
});
app.get('/issues/new', (req, res) => {
res.render('issues/new', { title: 'Report an issue', values: {}, errors: {}, priorities: PRIORITIES });
});
app.post('/issues', (req, res) => {
const { errors, values } = validateIssue(req.body ?? {});
if (Object.keys(errors).length > 0) {
return res.status(400).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES });
}
const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };
issues.push(issue);
res.redirect(303, `/issues/${issue.id}`);
});
app.get('/issues/:id', (req, res) => {
const issue = issues.find((e) => e.id === Number(req.params.id));
if (!issue) {
return res.status(404).render('not-found', { title: 'Not found', path: req.path });
}
res.render('issues/show', { title: issue.title, issue });
});
app.use((req, res) => {
if (req.path.startsWith('/api/')) {
return res.status(404).json({ error: `No route for ${req.method} ${req.path}` });
}
res.status(404).render('not-found', { title: 'Not found', path: req.path });
});
app.use((err, req, res, next) => {
const status = err.status ?? 500;
if (status >= 500) {
console.error(err);
}
const message = err.expose ? err.message : 'Something went wrong';
if (req.path.startsWith('/api/')) {
return res.status(status).json({ error: message });
}
res.status(status).render('error', { title: 'Error', status, message });
});
app.listen(port, () => {
console.log(`Caretaker listening on http://localhost:${port}`);
});
res.status(status).render('error', { title: 'Error', status, message });}); app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path'; export const app = express(); app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }); app.use((req, res, next) => { const started = Date.now(); res.on('finish', () => { console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`); }); next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.json());app.use(express.urlencoded({ extended: false })); const issues = [ { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' }, { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' }, { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; const PRIORITIES = ['low', 'medium', 'high', 'critical']; function validateIssue(input) { const errors = {}; const title = typeof input.title === 'string' ? input.title.trim() : ''; const building = typeof input.building === 'string' ? input.building.trim() : ''; if (title.length < 3 || title.length > 200) { errors.title = 'Title must be between 3 and 200 characters.'; } if (!PRIORITIES.includes(input.priority)) { errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`; } if (building.length === 0) { errors.building = 'Building is required.'; } return { errors, values: { title, priority: input.priority, building } };} app.get('/', (req, res) => { res.redirect('/issues');}); app.get('/api/issues', (req, res) => { const { status } = req.query; const result = status ? issues.filter((issue) => issue.status === status) : issues; res.json(result);}); app.get('/api/issues/:id', (req, res) => { const id = Number(req.params.id); const issue = issues.find((e) => e.id === id); if (!issue) { return res.status(404).json({ error: 'Issue not found' }); } res.json(issue);}); let nextId = 4; app.post('/api/issues', (req, res) => { const { errors, values } = validateIssue(req.body ?? {}); if (Object.keys(errors).length > 0) { return res.status(400).json({ errors }); } const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() }; issues.push(issue); res.status(201).location(`/api/issues/${issue.id}`).json(issue);}); app.get('/issues', (req, res) => { res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', (req, res) => { res.render('issues/new', { title: 'Report an issue', values: {}, errors: {}, priorities: PRIORITIES });}); app.post('/issues', (req, res) => { const { errors, values } = validateIssue(req.body ?? {}); if (Object.keys(errors).length > 0) { return res.status(400).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES }); } const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() }; issues.push(issue); res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/:id', (req, res) => { const issue = issues.find((e) => e.id === Number(req.params.id)); if (!issue) { return res.status(404).render('not-found', { title: 'Not found', path: req.path }); } res.render('issues/show', { title: issue.title, issue });}); app.use((req, res) => { if (req.path.startsWith('/api/')) { return res.status(404).json({ error: `No route for ${req.method} ${req.path}` }); } res.status(404).render('not-found', { title: 'Not found', path: req.path });}); app.use((err, req, res, next) => { const status = err.status ?? 500; if (status >= 500) { console.error(err); } const message = err.expose ? err.message : 'Something went wrong'; if (req.path.startsWith('/api/')) { return res.status(status).json({ error: message }); } res.status(status).render('error', { title: 'Error', status, message });});import express from 'express';
import path from 'node:path';
export const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(import.meta.dirname, '..', 'views'));
app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });
app.use((req, res, next) => {
const started = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);
});
next();
});
app.use(express.static(path.join(import.meta.dirname, '..', 'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const issues = [
{ id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },
{ id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },
{ id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },
];
const PRIORITIES = ['low', 'medium', 'high', 'critical'];
function validateIssue(input) {
const errors = {};
const title = typeof input.title === 'string' ? input.title.trim() : '';
const building = typeof input.building === 'string' ? input.building.trim() : '';
if (title.length < 3 || title.length > 200) {
errors.title = 'Title must be between 3 and 200 characters.';
}
if (!PRIORITIES.includes(input.priority)) {
errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;
}
if (building.length === 0) {
errors.building = 'Building is required.';
}
return { errors, values: { title, priority: input.priority, building } };
}
app.get('/', (req, res) => {
res.redirect('/issues');
});
app.get('/api/issues', (req, res) => {
const { status } = req.query;
const result = status ? issues.filter((issue) => issue.status === status) : issues;
res.json(result);
});
app.get('/api/issues/:id', (req, res) => {
const id = Number(req.params.id);
const issue = issues.find((e) => e.id === id);
if (!issue) {
return res.status(404).json({ error: 'Issue not found' });
}
res.json(issue);
});
let nextId = 4;
app.post('/api/issues', (req, res) => {
const { errors, values } = validateIssue(req.body ?? {});
if (Object.keys(errors).length > 0) {
return res.status(400).json({ errors });
}
const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };
issues.push(issue);
res.status(201).location(`/api/issues/${issue.id}`).json(issue);
});
app.get('/issues', (req, res) => {
res.render('issues/index', { title: 'Maintenance issues', issues });
});
app.get('/issues/new', (req, res) => {
res.render('issues/new', { title: 'Report an issue', values: {}, errors: {}, priorities: PRIORITIES });
});
app.post('/issues', (req, res) => {
const { errors, values } = validateIssue(req.body ?? {});
if (Object.keys(errors).length > 0) {
return res.status(400).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES });
}
const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };
issues.push(issue);
res.redirect(303, `/issues/${issue.id}`);
});
app.get('/issues/:id', (req, res) => {
const issue = issues.find((e) => e.id === Number(req.params.id));
if (!issue) {
return res.status(404).render('not-found', { title: 'Not found', path: req.path });
}
res.render('issues/show', { title: issue.title, issue });
});
app.use((req, res) => {
if (req.path.startsWith('/api/')) {
return res.status(404).json({ error: `No route for ${req.method} ${req.path}` });
}
res.status(404).render('not-found', { title: 'Not found', path: req.path });
});
app.use((err, req, res, next) => {
const status = err.status ?? 500;
if (status >= 500) {
console.error(err);
}
const message = err.expose ? err.message : 'Something went wrong';
if (req.path.startsWith('/api/')) {
return res.status(status).json({ error: message });
}
res.status(status).render('error', { title: 'Error', status, message });
});
The request logger would print a line for every test request. Turn it off when NODE_ENV is test:
app.use((req, res, next) => { if (process.env.NODE_ENV === 'test') { return next(); } const started = Date.now();
Show the whole src/app.js after this change
import express from 'express';import path from 'node:path'; export const app = express(); app.set('view engine', 'ejs');app.set('views', path.join(import.meta.dirname, '..', 'views'));app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' }); app.use((req, res, next) => { if (process.env.NODE_ENV === 'test') { return next(); } const started = Date.now(); res.on('finish', () => { console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`); }); next();}); app.use(express.static(path.join(import.meta.dirname, '..', 'public')));app.use(express.json());app.use(express.urlencoded({ extended: false })); const issues = [ { id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' }, { id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' }, { id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },]; const PRIORITIES = ['low', 'medium', 'high', 'critical']; function validateIssue(input) { const errors = {}; const title = typeof input.title === 'string' ? input.title.trim() : ''; const building = typeof input.building === 'string' ? input.building.trim() : ''; if (title.length < 3 || title.length > 200) { errors.title = 'Title must be between 3 and 200 characters.'; } if (!PRIORITIES.includes(input.priority)) { errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`; } if (building.length === 0) { errors.building = 'Building is required.'; } return { errors, values: { title, priority: input.priority, building } };} app.get('/', (req, res) => { res.redirect('/issues');}); app.get('/api/issues', (req, res) => { const { status } = req.query; const result = status ? issues.filter((issue) => issue.status === status) : issues; res.json(result);}); app.get('/api/issues/:id', (req, res) => { const id = Number(req.params.id); const issue = issues.find((e) => e.id === id); if (!issue) { return res.status(404).json({ error: 'Issue not found' }); } res.json(issue);}); let nextId = 4; app.post('/api/issues', (req, res) => { const { errors, values } = validateIssue(req.body ?? {}); if (Object.keys(errors).length > 0) { return res.status(400).json({ errors }); } const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() }; issues.push(issue); res.status(201).location(`/api/issues/${issue.id}`).json(issue);}); app.get('/issues', (req, res) => { res.render('issues/index', { title: 'Maintenance issues', issues });}); app.get('/issues/new', (req, res) => { res.render('issues/new', { title: 'Report an issue', values: {}, errors: {}, priorities: PRIORITIES });}); app.post('/issues', (req, res) => { const { errors, values } = validateIssue(req.body ?? {}); if (Object.keys(errors).length > 0) { return res.status(400).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES }); } const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() }; issues.push(issue); res.redirect(303, `/issues/${issue.id}`);}); app.get('/issues/:id', (req, res) => { const issue = issues.find((e) => e.id === Number(req.params.id)); if (!issue) { return res.status(404).render('not-found', { title: 'Not found', path: req.path }); } res.render('issues/show', { title: issue.title, issue });}); app.use((req, res) => { if (req.path.startsWith('/api/')) { return res.status(404).json({ error: `No route for ${req.method} ${req.path}` }); } res.status(404).render('not-found', { title: 'Not found', path: req.path });}); app.use((err, req, res, next) => { const status = err.status ?? 500; if (status >= 500) { console.error(err); } const message = err.expose ? err.message : 'Something went wrong'; if (req.path.startsWith('/api/')) { return res.status(status).json({ error: message }); } res.status(status).render('error', { title: 'Error', status, message });});import express from 'express';
import path from 'node:path';
export const app = express();
app.set('view engine', 'ejs');
app.set('views', path.join(import.meta.dirname, '..', 'views'));
app.locals.formatDate = (iso) => new Date(iso).toLocaleString('en-IE', { dateStyle: 'medium', timeStyle: 'short', timeZone: 'UTC' });
app.use((req, res, next) => {
if (process.env.NODE_ENV === 'test') {
return next();
}
const started = Date.now();
res.on('finish', () => {
console.log(`${req.method} ${req.originalUrl} -> ${res.statusCode} (${Date.now() - started} ms)`);
});
next();
});
app.use(express.static(path.join(import.meta.dirname, '..', 'public')));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
const issues = [
{ id: 1, title: 'Lift stuck between floors 2 and 3', priority: 'high', status: 'open', building: 'Dublin Offices', occurredAt: '2026-11-02T09:15:00.000Z' },
{ id: 2, title: 'Dripping tap in the second-floor kitchen', priority: 'medium', status: 'closed', building: 'Dublin Offices', occurredAt: '2026-11-05T14:40:00.000Z' },
{ id: 3, title: 'Front door lock sticks at entrance 4', priority: 'critical', status: 'open', building: 'Cork Apartments', occurredAt: '2026-11-08T07:05:00.000Z' },
];
const PRIORITIES = ['low', 'medium', 'high', 'critical'];
function validateIssue(input) {
const errors = {};
const title = typeof input.title === 'string' ? input.title.trim() : '';
const building = typeof input.building === 'string' ? input.building.trim() : '';
if (title.length < 3 || title.length > 200) {
errors.title = 'Title must be between 3 and 200 characters.';
}
if (!PRIORITIES.includes(input.priority)) {
errors.priority = `Priority must be one of: ${PRIORITIES.join(', ')}.`;
}
if (building.length === 0) {
errors.building = 'Building is required.';
}
return { errors, values: { title, priority: input.priority, building } };
}
app.get('/', (req, res) => {
res.redirect('/issues');
});
app.get('/api/issues', (req, res) => {
const { status } = req.query;
const result = status ? issues.filter((issue) => issue.status === status) : issues;
res.json(result);
});
app.get('/api/issues/:id', (req, res) => {
const id = Number(req.params.id);
const issue = issues.find((e) => e.id === id);
if (!issue) {
return res.status(404).json({ error: 'Issue not found' });
}
res.json(issue);
});
let nextId = 4;
app.post('/api/issues', (req, res) => {
const { errors, values } = validateIssue(req.body ?? {});
if (Object.keys(errors).length > 0) {
return res.status(400).json({ errors });
}
const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };
issues.push(issue);
res.status(201).location(`/api/issues/${issue.id}`).json(issue);
});
app.get('/issues', (req, res) => {
res.render('issues/index', { title: 'Maintenance issues', issues });
});
app.get('/issues/new', (req, res) => {
res.render('issues/new', { title: 'Report an issue', values: {}, errors: {}, priorities: PRIORITIES });
});
app.post('/issues', (req, res) => {
const { errors, values } = validateIssue(req.body ?? {});
if (Object.keys(errors).length > 0) {
return res.status(400).render('issues/new', { title: 'Report an issue', values, errors, priorities: PRIORITIES });
}
const issue = { id: nextId++, ...values, status: 'open', occurredAt: new Date().toISOString() };
issues.push(issue);
res.redirect(303, `/issues/${issue.id}`);
});
app.get('/issues/:id', (req, res) => {
const issue = issues.find((e) => e.id === Number(req.params.id));
if (!issue) {
return res.status(404).render('not-found', { title: 'Not found', path: req.path });
}
res.render('issues/show', { title: issue.title, issue });
});
app.use((req, res) => {
if (req.path.startsWith('/api/')) {
return res.status(404).json({ error: `No route for ${req.method} ${req.path}` });
}
res.status(404).render('not-found', { title: 'Not found', path: req.path });
});
app.use((err, req, res, next) => {
const status = err.status ?? 500;
if (status >= 500) {
console.error(err);
}
const message = err.expose ? err.message : 'Something went wrong';
if (req.path.startsWith('/api/')) {
return res.status(status).json({ error: message });
}
res.status(status).render('error', { title: 'Error', status, message });
});
Now create the new, very small src/server.js:
import { app } from './app.js'; const port = 3000; app.listen(port, () => { console.log(`Caretaker listening on http://localhost:${port}`);});app.js describes what the application does. server.js decides where it runs. The start and dev scripts still point at src/server.js, so nothing else changes.
2. Install Supertest
Supertest takes an Express app, starts it on a temporary internal port for each request, sends the request, and gives you the response. --save-dev records it under devDependencies: needed to develop and test, not to run in production.
npm install --save-dev supertest@7.3.2
added 20 packages, and audited 87 packages in 2s
35 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
3. Configure the test script
Node.js has a test runner built in: node --test finds files named *.test.js and runs them. Set the script:
npm pkg set scripts.test="NODE_ENV=test node --test --test-reporter=spec"
NODE_ENV=testsets the variable for this one command, as you saw in lesson 0.3.--test-reporter=specprints readable results. (Without it, Node prints the machine-oriented TAP format when the output is not a terminal, for example in CI.)
4. Write the tests
Create test/issues.test.js:
import { test } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js'; test('GET /api/issues lists the starting issues as JSON', async () => { const res = await request(app).get('/api/issues'); assert.equal(res.status, 200); assert.match(res.headers['content-type'], /application\/json/); assert.equal(res.body.length, 3); assert.equal(res.body[0].title, 'Lift stuck between floors 2 and 3');}); test('GET /api/issues/:id returns 404 JSON for an unknown id', async () => { const res = await request(app).get('/api/issues/99'); assert.equal(res.status, 404); assert.deepEqual(res.body, { error: 'Issue not found' });}); test('POST /api/issues rejects invalid input with field errors', async () => { const res = await request(app).post('/api/issues').send({ title: 'Hi', priority: 'extreme' }); assert.equal(res.status, 400); assert.ok(res.body.errors.title); assert.ok(res.body.errors.priority); assert.ok(res.body.errors.building);}); test('POST /api/issues creates an issue', async () => { const res = await request(app) .post('/api/issues') .send({ title: 'Broken light in stairwell B', priority: 'low', building: 'Cork Apartments' }); assert.equal(res.status, 201); assert.match(res.headers.location, /^\/api\/issues\/\d+$/); assert.equal(res.body.status, 'open');}); test('GET /issues renders the list page', async () => { const res = await request(app).get('/issues'); assert.equal(res.status, 200); assert.match(res.text, /<h1>Maintenance issues<\/h1>/); assert.match(res.text, /Lift stuck between floors 2 and 3/);}); test('POST /issues re-renders the form with errors', async () => { const res = await request(app).post('/issues').type('form').send({ title: '', building: '', priority: '' }); assert.equal(res.status, 400); assert.match(res.text, /Title must be between 3 and 200 characters/);}); test('POST /issues redirects to the new issue (Post/Redirect/Get)', async () => { const res = await request(app) .post('/issues') .type('form') .send({ title: 'Water leak by the staff entrance', building: 'Dublin Offices', priority: 'low' }); assert.equal(res.status, 303); assert.match(res.headers.location, /^\/issues\/\d+$/);});What each piece does:
test(name, fn)registers a test. Iffnthrows, or returns a promise that rejects, the test fails.assertfromnode:assert/strictcompares with strict equality.assert.matchchecks a string against a regular expression.request(app).get(...)builds a request;awaitsends it..send(object)sends JSON;.type('form')switches to URL-encoded form data, exactly like a browser form.res.bodyis parsed JSON;res.textis the raw body, which we use for HTML.
Run and inspect
Stop the dev server if it is running (the tests do not need it). Then:
npm test
> caretaker@1.0.0 test
> NODE_ENV=test node --test --test-reporter=spec
✔ GET /api/issues lists the starting issues as JSON (10.5735ms)
✔ GET /api/issues/:id returns 404 JSON for an unknown id (2.726375ms)
✔ POST /api/issues rejects invalid input with field errors (3.640708ms)
✔ POST /api/issues creates an issue (1.102584ms)
✔ GET /issues renders the list page (11.260208ms)
✔ POST /issues re-renders the form with errors (3.439875ms)
✔ POST /issues redirects to the new issue (Post/Redirect/Get) (1.614791ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 135.547375
Seven tests ran against the real app, with real HTTP, in well under a second. Make it fail on purpose to see what a failure looks like: change the expected title in the first test.
assert.equal(res.body[0].title, 'Lift stuck between floors 2 and 3'); assert.equal(res.body[0].title, 'Broken window latch');
Show the whole test/issues.test.js after this change
import { test } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js'; test('GET /api/issues lists the starting issues as JSON', async () => { const res = await request(app).get('/api/issues'); assert.equal(res.status, 200); assert.match(res.headers['content-type'], /application\/json/); assert.equal(res.body.length, 3); assert.equal(res.body[0].title, 'Broken window latch');}); test('GET /api/issues/:id returns 404 JSON for an unknown id', async () => { const res = await request(app).get('/api/issues/99'); assert.equal(res.status, 404); assert.deepEqual(res.body, { error: 'Issue not found' });}); test('POST /api/issues rejects invalid input with field errors', async () => { const res = await request(app).post('/api/issues').send({ title: 'Hi', priority: 'extreme' }); assert.equal(res.status, 400); assert.ok(res.body.errors.title); assert.ok(res.body.errors.priority); assert.ok(res.body.errors.building);}); test('POST /api/issues creates an issue', async () => { const res = await request(app) .post('/api/issues') .send({ title: 'Broken light in stairwell B', priority: 'low', building: 'Cork Apartments' }); assert.equal(res.status, 201); assert.match(res.headers.location, /^\/api\/issues\/\d+$/); assert.equal(res.body.status, 'open');}); test('GET /issues renders the list page', async () => { const res = await request(app).get('/issues'); assert.equal(res.status, 200); assert.match(res.text, /<h1>Maintenance issues<\/h1>/); assert.match(res.text, /Lift stuck between floors 2 and 3/);}); test('POST /issues re-renders the form with errors', async () => { const res = await request(app).post('/issues').type('form').send({ title: '', building: '', priority: '' }); assert.equal(res.status, 400); assert.match(res.text, /Title must be between 3 and 200 characters/);}); test('POST /issues redirects to the new issue (Post/Redirect/Get)', async () => { const res = await request(app) .post('/issues') .type('form') .send({ title: 'Water leak by the staff entrance', building: 'Dublin Offices', priority: 'low' }); assert.equal(res.status, 303); assert.match(res.headers.location, /^\/issues\/\d+$/);});import { test } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
test('GET /api/issues lists the starting issues as JSON', async () => {
const res = await request(app).get('/api/issues');
assert.equal(res.status, 200);
assert.match(res.headers['content-type'], /application\/json/);
assert.equal(res.body.length, 3);
assert.equal(res.body[0].title, 'Broken window latch');
});
test('GET /api/issues/:id returns 404 JSON for an unknown id', async () => {
const res = await request(app).get('/api/issues/99');
assert.equal(res.status, 404);
assert.deepEqual(res.body, { error: 'Issue not found' });
});
test('POST /api/issues rejects invalid input with field errors', async () => {
const res = await request(app).post('/api/issues').send({ title: 'Hi', priority: 'extreme' });
assert.equal(res.status, 400);
assert.ok(res.body.errors.title);
assert.ok(res.body.errors.priority);
assert.ok(res.body.errors.building);
});
test('POST /api/issues creates an issue', async () => {
const res = await request(app)
.post('/api/issues')
.send({ title: 'Broken light in stairwell B', priority: 'low', building: 'Cork Apartments' });
assert.equal(res.status, 201);
assert.match(res.headers.location, /^\/api\/issues\/\d+$/);
assert.equal(res.body.status, 'open');
});
test('GET /issues renders the list page', async () => {
const res = await request(app).get('/issues');
assert.equal(res.status, 200);
assert.match(res.text, /<h1>Maintenance issues<\/h1>/);
assert.match(res.text, /Lift stuck between floors 2 and 3/);
});
test('POST /issues re-renders the form with errors', async () => {
const res = await request(app).post('/issues').type('form').send({ title: '', building: '', priority: '' });
assert.equal(res.status, 400);
assert.match(res.text, /Title must be between 3 and 200 characters/);
});
test('POST /issues redirects to the new issue (Post/Redirect/Get)', async () => {
const res = await request(app)
.post('/issues')
.type('form')
.send({ title: 'Water leak by the staff entrance', building: 'Dublin Offices', priority: 'low' });
assert.equal(res.status, 303);
assert.match(res.headers.location, /^\/issues\/\d+$/);
});
npm test
> caretaker@1.0.0 test
> NODE_ENV=test node --test --test-reporter=spec
✖ GET /api/issues lists the starting issues as JSON (11.6055ms)
✔ GET /api/issues/:id returns 404 JSON for an unknown id (3.293834ms)
✔ POST /api/issues rejects invalid input with field errors (5.335166ms)
✔ POST /api/issues creates an issue (1.4045ms)
✔ GET /issues renders the list page (11.173125ms)
✔ POST /issues re-renders the form with errors (3.021792ms)
✔ POST /issues redirects to the new issue (Post/Redirect/Get) (3.290792ms)
ℹ tests 7
ℹ suites 0
ℹ pass 6
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 128.629584
✖ failing tests:
test at test/issues.test.js:6:1
✖ GET /api/issues lists the starting issues as JSON (11.6055ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
+ actual - expected
+ 'Lift stuck between floors 2 and 3'
- 'Broken window latch'
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/issues.test.js:11:10)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async Test.run (node:internal/test_runner/test:1054:7)
at async startSubtestAfterBootstrap (node:internal/test_runner/harness:296:3) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 'Lift stuck between floors 2 and 3',
expected: 'Broken window latch',
operator: 'strictEqual',
diff: 'simple'
Show 1 more lines
}
The report shows the test name, the expected and actual values, and the line. Put the correct title back:
assert.equal(res.body[0].title, 'Broken window latch'); assert.equal(res.body[0].title, 'Lift stuck between floors 2 and 3');
Show the whole test/issues.test.js after this change
import { test } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js'; test('GET /api/issues lists the starting issues as JSON', async () => { const res = await request(app).get('/api/issues'); assert.equal(res.status, 200); assert.match(res.headers['content-type'], /application\/json/); assert.equal(res.body.length, 3); assert.equal(res.body[0].title, 'Lift stuck between floors 2 and 3');}); test('GET /api/issues/:id returns 404 JSON for an unknown id', async () => { const res = await request(app).get('/api/issues/99'); assert.equal(res.status, 404); assert.deepEqual(res.body, { error: 'Issue not found' });}); test('POST /api/issues rejects invalid input with field errors', async () => { const res = await request(app).post('/api/issues').send({ title: 'Hi', priority: 'extreme' }); assert.equal(res.status, 400); assert.ok(res.body.errors.title); assert.ok(res.body.errors.priority); assert.ok(res.body.errors.building);}); test('POST /api/issues creates an issue', async () => { const res = await request(app) .post('/api/issues') .send({ title: 'Broken light in stairwell B', priority: 'low', building: 'Cork Apartments' }); assert.equal(res.status, 201); assert.match(res.headers.location, /^\/api\/issues\/\d+$/); assert.equal(res.body.status, 'open');}); test('GET /issues renders the list page', async () => { const res = await request(app).get('/issues'); assert.equal(res.status, 200); assert.match(res.text, /<h1>Maintenance issues<\/h1>/); assert.match(res.text, /Lift stuck between floors 2 and 3/);}); test('POST /issues re-renders the form with errors', async () => { const res = await request(app).post('/issues').type('form').send({ title: '', building: '', priority: '' }); assert.equal(res.status, 400); assert.match(res.text, /Title must be between 3 and 200 characters/);}); test('POST /issues redirects to the new issue (Post/Redirect/Get)', async () => { const res = await request(app) .post('/issues') .type('form') .send({ title: 'Water leak by the staff entrance', building: 'Dublin Offices', priority: 'low' }); assert.equal(res.status, 303); assert.match(res.headers.location, /^\/issues\/\d+$/);});import { test } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
test('GET /api/issues lists the starting issues as JSON', async () => {
const res = await request(app).get('/api/issues');
assert.equal(res.status, 200);
assert.match(res.headers['content-type'], /application\/json/);
assert.equal(res.body.length, 3);
assert.equal(res.body[0].title, 'Lift stuck between floors 2 and 3');
});
test('GET /api/issues/:id returns 404 JSON for an unknown id', async () => {
const res = await request(app).get('/api/issues/99');
assert.equal(res.status, 404);
assert.deepEqual(res.body, { error: 'Issue not found' });
});
test('POST /api/issues rejects invalid input with field errors', async () => {
const res = await request(app).post('/api/issues').send({ title: 'Hi', priority: 'extreme' });
assert.equal(res.status, 400);
assert.ok(res.body.errors.title);
assert.ok(res.body.errors.priority);
assert.ok(res.body.errors.building);
});
test('POST /api/issues creates an issue', async () => {
const res = await request(app)
.post('/api/issues')
.send({ title: 'Broken light in stairwell B', priority: 'low', building: 'Cork Apartments' });
assert.equal(res.status, 201);
assert.match(res.headers.location, /^\/api\/issues\/\d+$/);
assert.equal(res.body.status, 'open');
});
test('GET /issues renders the list page', async () => {
const res = await request(app).get('/issues');
assert.equal(res.status, 200);
assert.match(res.text, /<h1>Maintenance issues<\/h1>/);
assert.match(res.text, /Lift stuck between floors 2 and 3/);
});
test('POST /issues re-renders the form with errors', async () => {
const res = await request(app).post('/issues').type('form').send({ title: '', building: '', priority: '' });
assert.equal(res.status, 400);
assert.match(res.text, /Title must be between 3 and 200 characters/);
});
test('POST /issues redirects to the new issue (Post/Redirect/Get)', async () => {
const res = await request(app)
.post('/issues')
.type('form')
.send({ title: 'Water leak by the staff entrance', building: 'Dublin Offices', priority: 'low' });
assert.equal(res.status, 303);
assert.match(res.headers.location, /^\/issues\/\d+$/);
});
Experiment
Our tests share one issues array. Add a test at the end of the file that checks the list again:
assert.equal(res.status, 303); assert.match(res.headers.location, /^\/issues\/\d+$/);}); test('the list still has the three starting issues', async () => { const res = await request(app).get('/api/issues'); assert.equal(res.body.length, 3);});
Show the whole test/issues.test.js after this change
import { test } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js'; test('GET /api/issues lists the starting issues as JSON', async () => { const res = await request(app).get('/api/issues'); assert.equal(res.status, 200); assert.match(res.headers['content-type'], /application\/json/); assert.equal(res.body.length, 3); assert.equal(res.body[0].title, 'Lift stuck between floors 2 and 3');}); test('GET /api/issues/:id returns 404 JSON for an unknown id', async () => { const res = await request(app).get('/api/issues/99'); assert.equal(res.status, 404); assert.deepEqual(res.body, { error: 'Issue not found' });}); test('POST /api/issues rejects invalid input with field errors', async () => { const res = await request(app).post('/api/issues').send({ title: 'Hi', priority: 'extreme' }); assert.equal(res.status, 400); assert.ok(res.body.errors.title); assert.ok(res.body.errors.priority); assert.ok(res.body.errors.building);}); test('POST /api/issues creates an issue', async () => { const res = await request(app) .post('/api/issues') .send({ title: 'Broken light in stairwell B', priority: 'low', building: 'Cork Apartments' }); assert.equal(res.status, 201); assert.match(res.headers.location, /^\/api\/issues\/\d+$/); assert.equal(res.body.status, 'open');}); test('GET /issues renders the list page', async () => { const res = await request(app).get('/issues'); assert.equal(res.status, 200); assert.match(res.text, /<h1>Maintenance issues<\/h1>/); assert.match(res.text, /Lift stuck between floors 2 and 3/);}); test('POST /issues re-renders the form with errors', async () => { const res = await request(app).post('/issues').type('form').send({ title: '', building: '', priority: '' }); assert.equal(res.status, 400); assert.match(res.text, /Title must be between 3 and 200 characters/);}); test('POST /issues redirects to the new issue (Post/Redirect/Get)', async () => { const res = await request(app) .post('/issues') .type('form') .send({ title: 'Water leak by the staff entrance', building: 'Dublin Offices', priority: 'low' }); assert.equal(res.status, 303); assert.match(res.headers.location, /^\/issues\/\d+$/);}); test('the list still has the three starting issues', async () => { const res = await request(app).get('/api/issues'); assert.equal(res.body.length, 3);});import { test } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
test('GET /api/issues lists the starting issues as JSON', async () => {
const res = await request(app).get('/api/issues');
assert.equal(res.status, 200);
assert.match(res.headers['content-type'], /application\/json/);
assert.equal(res.body.length, 3);
assert.equal(res.body[0].title, 'Lift stuck between floors 2 and 3');
});
test('GET /api/issues/:id returns 404 JSON for an unknown id', async () => {
const res = await request(app).get('/api/issues/99');
assert.equal(res.status, 404);
assert.deepEqual(res.body, { error: 'Issue not found' });
});
test('POST /api/issues rejects invalid input with field errors', async () => {
const res = await request(app).post('/api/issues').send({ title: 'Hi', priority: 'extreme' });
assert.equal(res.status, 400);
assert.ok(res.body.errors.title);
assert.ok(res.body.errors.priority);
assert.ok(res.body.errors.building);
});
test('POST /api/issues creates an issue', async () => {
const res = await request(app)
.post('/api/issues')
.send({ title: 'Broken light in stairwell B', priority: 'low', building: 'Cork Apartments' });
assert.equal(res.status, 201);
assert.match(res.headers.location, /^\/api\/issues\/\d+$/);
assert.equal(res.body.status, 'open');
});
test('GET /issues renders the list page', async () => {
const res = await request(app).get('/issues');
assert.equal(res.status, 200);
assert.match(res.text, /<h1>Maintenance issues<\/h1>/);
assert.match(res.text, /Lift stuck between floors 2 and 3/);
});
test('POST /issues re-renders the form with errors', async () => {
const res = await request(app).post('/issues').type('form').send({ title: '', building: '', priority: '' });
assert.equal(res.status, 400);
assert.match(res.text, /Title must be between 3 and 200 characters/);
});
test('POST /issues redirects to the new issue (Post/Redirect/Get)', async () => {
const res = await request(app)
.post('/issues')
.type('form')
.send({ title: 'Water leak by the staff entrance', building: 'Dublin Offices', priority: 'low' });
assert.equal(res.status, 303);
assert.match(res.headers.location, /^\/issues\/\d+$/);
});
test('the list still has the three starting issues', async () => {
const res = await request(app).get('/api/issues');
assert.equal(res.body.length, 3);
});
npm test
> caretaker@1.0.0 test
> NODE_ENV=test node --test --test-reporter=spec
✔ GET /api/issues lists the starting issues as JSON (10.789875ms)
✔ GET /api/issues/:id returns 404 JSON for an unknown id (2.521667ms)
✔ POST /api/issues rejects invalid input with field errors (3.654625ms)
✔ POST /api/issues creates an issue (1.717583ms)
✔ GET /issues renders the list page (11.270417ms)
✔ POST /issues re-renders the form with errors (2.995041ms)
✔ POST /issues redirects to the new issue (Post/Redirect/Get) (2.104417ms)
✖ the list still has the three starting issues (2.799333ms)
ℹ tests 8
ℹ suites 0
ℹ pass 7
ℹ fail 1
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 128.754
✖ failing tests:
test at test/issues.test.js:59:1
✖ the list still has the three starting issues (2.799333ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly equal:
5 !== 3
at TestContext.<anonymous> (file:///Users/you/code/caretaker/test/issues.test.js:61:10)
at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
at async Test.run (node:internal/test_runner/test:1054:7)
at async Test.processPendingSubtests (node:internal/test_runner/test:744:7) {
generatedMessage: true,
code: 'ERR_ASSERTION',
actual: 5,
expected: 3,
operator: 'strictEqual',
diff: 'simple'
}
Reveal Why it fails
Two earlier tests created issues in the same array, so the list has 5 entries. Tests that depend on the order they run in are fragile: reorder them and different tests fail. To make every test start from a known state we need storage we can reset, which an array inside a running module does not give us.
Remove the experiment test:
assert.match(res.headers.location, /^\/issues\/\d+$/);}); test('the list still has the three starting issues', async () => { const res = await request(app).get('/api/issues'); assert.equal(res.body.length, 3);});
Show the whole test/issues.test.js after this change
import { test } from 'node:test';import assert from 'node:assert/strict';import request from 'supertest';import { app } from '../src/app.js'; test('GET /api/issues lists the starting issues as JSON', async () => { const res = await request(app).get('/api/issues'); assert.equal(res.status, 200); assert.match(res.headers['content-type'], /application\/json/); assert.equal(res.body.length, 3); assert.equal(res.body[0].title, 'Lift stuck between floors 2 and 3');}); test('GET /api/issues/:id returns 404 JSON for an unknown id', async () => { const res = await request(app).get('/api/issues/99'); assert.equal(res.status, 404); assert.deepEqual(res.body, { error: 'Issue not found' });}); test('POST /api/issues rejects invalid input with field errors', async () => { const res = await request(app).post('/api/issues').send({ title: 'Hi', priority: 'extreme' }); assert.equal(res.status, 400); assert.ok(res.body.errors.title); assert.ok(res.body.errors.priority); assert.ok(res.body.errors.building);}); test('POST /api/issues creates an issue', async () => { const res = await request(app) .post('/api/issues') .send({ title: 'Broken light in stairwell B', priority: 'low', building: 'Cork Apartments' }); assert.equal(res.status, 201); assert.match(res.headers.location, /^\/api\/issues\/\d+$/); assert.equal(res.body.status, 'open');}); test('GET /issues renders the list page', async () => { const res = await request(app).get('/issues'); assert.equal(res.status, 200); assert.match(res.text, /<h1>Maintenance issues<\/h1>/); assert.match(res.text, /Lift stuck between floors 2 and 3/);}); test('POST /issues re-renders the form with errors', async () => { const res = await request(app).post('/issues').type('form').send({ title: '', building: '', priority: '' }); assert.equal(res.status, 400); assert.match(res.text, /Title must be between 3 and 200 characters/);}); test('POST /issues redirects to the new issue (Post/Redirect/Get)', async () => { const res = await request(app) .post('/issues') .type('form') .send({ title: 'Water leak by the staff entrance', building: 'Dublin Offices', priority: 'low' }); assert.equal(res.status, 303); assert.match(res.headers.location, /^\/issues\/\d+$/);});import { test } from 'node:test';
import assert from 'node:assert/strict';
import request from 'supertest';
import { app } from '../src/app.js';
test('GET /api/issues lists the starting issues as JSON', async () => {
const res = await request(app).get('/api/issues');
assert.equal(res.status, 200);
assert.match(res.headers['content-type'], /application\/json/);
assert.equal(res.body.length, 3);
assert.equal(res.body[0].title, 'Lift stuck between floors 2 and 3');
});
test('GET /api/issues/:id returns 404 JSON for an unknown id', async () => {
const res = await request(app).get('/api/issues/99');
assert.equal(res.status, 404);
assert.deepEqual(res.body, { error: 'Issue not found' });
});
test('POST /api/issues rejects invalid input with field errors', async () => {
const res = await request(app).post('/api/issues').send({ title: 'Hi', priority: 'extreme' });
assert.equal(res.status, 400);
assert.ok(res.body.errors.title);
assert.ok(res.body.errors.priority);
assert.ok(res.body.errors.building);
});
test('POST /api/issues creates an issue', async () => {
const res = await request(app)
.post('/api/issues')
.send({ title: 'Broken light in stairwell B', priority: 'low', building: 'Cork Apartments' });
assert.equal(res.status, 201);
assert.match(res.headers.location, /^\/api\/issues\/\d+$/);
assert.equal(res.body.status, 'open');
});
test('GET /issues renders the list page', async () => {
const res = await request(app).get('/issues');
assert.equal(res.status, 200);
assert.match(res.text, /<h1>Maintenance issues<\/h1>/);
assert.match(res.text, /Lift stuck between floors 2 and 3/);
});
test('POST /issues re-renders the form with errors', async () => {
const res = await request(app).post('/issues').type('form').send({ title: '', building: '', priority: '' });
assert.equal(res.status, 400);
assert.match(res.text, /Title must be between 3 and 200 characters/);
});
test('POST /issues redirects to the new issue (Post/Redirect/Get)', async () => {
const res = await request(app)
.post('/issues')
.type('form')
.send({ title: 'Water leak by the staff entrance', building: 'Dublin Offices', priority: 'low' });
assert.equal(res.status, 303);
assert.match(res.headers.location, /^\/issues\/\d+$/);
});
The second problem is worse. Start the server, create an issue, and count:
npm start
> caretaker@1.0.0 start
> node src/server.js
Caretaker listening on http://localhost:3000
curl -s http://localhost:3000/api/issues -H "Content-Type: application/json" -d '{"title":"Radiator leaking in hall","priority":"medium","building":"Cork Apartments"}'
{"id":4,"title":"Radiator leaking in hall","priority":"medium","building":"Cork Apartments","status":"open","occurredAt":"2026-11-28T14:39:14.674Z"}
curl -s http://localhost:3000/api/issues | grep -o '"id"' | wc -l
4
Four issues. Now restart the server, as you would after a deploy or a crash:
npm start
> caretaker@1.0.0 start
> node src/server.js
Caretaker listening on http://localhost:3000
curl -s http://localhost:3000/api/issues | grep -o '"id"' | wc -l
3
The issue is gone. The array lives in the memory of one process; when the process ends, so does the data. A second server process (for more capacity) would also have its own separate array, so two users could see two different lists.
Checkpoint
npm test
> caretaker@1.0.0 test
> NODE_ENV=test node --test --test-reporter=spec
✔ GET /api/issues lists the starting issues as JSON (9.518583ms)
✔ GET /api/issues/:id returns 404 JSON for an unknown id (2.426292ms)
✔ POST /api/issues rejects invalid input with field errors (3.670084ms)
✔ POST /api/issues creates an issue (1.120042ms)
✔ GET /issues renders the list page (11.019834ms)
✔ POST /issues re-renders the form with errors (3.261167ms)
✔ POST /issues redirects to the new issue (Post/Redirect/Get) (1.508209ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 120.350209
git add -A
git commit -m "Add HTTP tests with node:test and Supertest"
[main c1be2d8] Add HTTP tests with node:test and Supertest
5 files changed, 432 insertions(+), 120 deletions(-)
create mode 100644 src/app.js
create mode 100644 test/issues.test.js
Symptom Error: listen EADDRINUSE when running tests
A test imported src/server.js instead of src/app.js. Tests must import the app, never the server.
Symptom SyntaxError: The requested module '../src/app.js' does not provide an export named 'app'
src/app.js must say export const app = express();.
Symptom 'NODE_ENV' is not recognized as an internal or external command
You are in Windows cmd or PowerShell. Run the course in WSL, where the NAME=value command syntax works.
Recap and next step
Splitting app.js from server.js made the app importable. Supertest sends real HTTP requests to it; node:test organises and reports them. The tests revealed two limits of in-memory data: tests cannot start from a clean state, and data dies with the process.
In Module 2 we fix both with PostgreSQL: data that survives restarts, constraints that protect it, and a test database we can reset before every test file.
Open the checkpoint files for lesson 1.5 (separate page; only files from this lesson and earlier)