Module 5 ยท Testing, security and shipping Lesson 13 of 15
Tests for the API you just built
A few API tests turn "it works when I click it" into something a machine checks on every change. Test the routes, the happy path and the failures.
The concept
Test against a separate test database the suite creates and drops, so a run never touches the data you are using to develop.
Test status codes and the body together; an endpoint that returns 200 with an error message inside is a bug the front end will trip over.
import request from 'supertest';
import app from '../app.js';
test('POST /api/jobs creates a job', async () => {
const res = await request(app)
.post('/api/jobs')
.send({ title: 'Data Analyst', city: 'Pune' });
expect(res.status).toBe(201);
expect(res.body).toHaveProperty('id');
});
test('POST /api/jobs rejects a missing title', async () => {
const res = await request(app).post('/api/jobs').send({ city: 'Pune' });
expect(res.status).toBe(400);
});Worked example
A test that posts a bad payload and asserts 400 guards the validation you wrote and prevents a later "small change" from removing it.
Your practice task
Write three tests for your API: a successful request, a missing field, and an unauthorised request.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
Test against a separate test database the suite creates and drops, so a run never touches the data you are using to develop.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task โ do them and the final project brief writes itself.