๐Ÿ“Š We use cookies & analytics to improve your experience. Learn more
Latest

Full-Stack Web Development Bootcamp Module 5 ยท Lesson 13 of 15

0% Exit to course

Module 5 ยท Testing, security and shipping Lesson 13 of 15

Tests for the API you just built

Learning objective

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.

JavaScript
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.

Create free account or sign in

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.

Next recommended course Data Analytics with SQL & Excel