0
0
Expressframework~30 mins

Testing GET endpoints in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Testing GET endpoints
📖 Scenario: You are building a simple Express server that has a GET endpoint to return a list of books. You want to write tests to make sure this endpoint works correctly.
🎯 Goal: Create a basic Express app with a GET endpoint at /books that returns a list of books. Then write a test using a testing library to check that the endpoint returns the correct data and status code.
📋 What You'll Learn
Create an Express app with a GET endpoint /books
The endpoint should return a JSON array of book objects
Write a test that sends a GET request to /books
The test should check that the response status is 200
The test should check that the response body matches the expected books array
💡 Why This Matters
🌍 Real World
Testing GET endpoints is essential for backend APIs to ensure they return the correct data and status codes before deploying to production.
💼 Career
Backend developers and QA engineers often write tests like these to maintain API quality and prevent bugs.
Progress0 / 4 steps
1
Create the books data array
Create a constant array called books with these exact objects: { id: 1, title: '1984' } and { id: 2, title: 'Brave New World' }.
Express
Need a hint?

Use const books = [ ... ] to create the array with two objects inside.

2
Set up the Express app and import modules
Import express and create an app variable called app by calling express().
Express
Need a hint?

Use const express = require('express') and const app = express().

3
Create the GET endpoint for /books
Use app.get with path '/books' and a callback with parameters req and res. Inside the callback, send the books array as JSON using res.json(books).
Express
Need a hint?

Use app.get('/books', (req, res) => { res.json(books); }).

4
Write a test for the GET /books endpoint
Import supertest and use it to create a request object with supertest(app). Write a test named 'GET /books returns books list' that sends a GET request to /books and expects status 200 and the JSON body to equal the books array.
Express
Need a hint?

Use supertest to send a GET request and check status and body with expect.