Testing the API
Testing an API is the habit of asking each route for its answer and checking it. A small script runs the checks, so a change cannot break a route quietly.
One check
A check pairs a name with a true-or-false test.
function check(name, ok) {
console.log(name + ': ' + (ok ? 'pass' : 'fail'));
}A passing check
The list holds three notes, so the check passes.
check('GET /api/notes returns 3 notes', notes.length === 3);A failing check
A wrong guess prints fail beside its name.
check('GET /api/notes returns 9 notes', notes.length === 9);Example
import express from 'express';
import mongoose from 'mongoose';
await mongoose.connect('mongodb://localhost:27017/notes');
const noteSchema = new mongoose.Schema({ title: String, done: Boolean });
const Note = mongoose.model('Note', noteSchema);
await Note.create({ title: 'Buy milk', done: false });
await Note.create({ title: 'Ship MERN', done: true });
await Note.create({ title: 'Read a book', done: false });
const app = express();
app.use(express.json());
app.get('/api/notes', async (req, res) => {
const notes = await Note.find().sort({ title: 1 });
res.json(notes.map((n) => ({ title: n.title, done: n.done })));
});
app.post('/api/notes', async (req, res) => {
const note = await Note.create(req.body);
res.status(201).json({ title: note.title, done: note.done });
});
app.get('/api/notes/:id', async (req, res) => {
const note = await Note.findById(req.params.id);
if (!note) {
res.status(404).json({ error: 'Note not found' });
return;
}
res.json({ title: note.title, done: note.done });
});
const server = app.listen(0);
const port = server.address().port;
const base = `http://localhost:${port}`;
function check(name, ok) {
console.log(`${name}: ${ok ? 'pass' : 'fail'}`);
}
const listRes = await fetch(`${base}/api/notes`);
const notes = await listRes.json();
check('GET /api/notes returns 3 notes', notes.length === 3);
const createRes = await fetch(`${base}/api/notes`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: 'Water plants', done: false }),
});
const created = await createRes.json();
check('POST /api/notes creates a note', created.title === 'Water plants');
const saved = await Note.findOne({ title: 'Water plants' });
const oneRes = await fetch(`${base}/api/notes/${saved._id}`);
const one = await oneRes.json();
check('GET /api/notes/:id returns one note', one.title === 'Water plants');
server.close();
await mongoose.disconnect();Key points
- A test asks a route a question and checks the answer.
- Each check has a name, so a failure points at one route.
- The script starts the real server and calls its own routes.
- A passing check prints pass beside its name.
- A failing check prints fail, and the script keeps going.
In this example, the script connects to the notes database and saves the three notes. It builds an Express app with the list, create, and get-one routes. A small check helper prints pass or fail beside a name. The script runs three checks, one per route. All three print pass, so the API answers as planned.
Note
Run the tests after every change to the routes.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a passing check print?