Testing API Routes
Supertest, which we previously used to test HTML routes, is a great way to test API routes we create.
Here's an example:
import request from 'supertest'import server from '../server.ts'test('/users route returns an object containing an array of users', async() => {// Arrangeconst expected = true// Actconst res = await request(server).get('/users')// Assertexpect(res.headers["Content-Type"]).toMatch(/json/)expect(res.status).toBe(200)const users = res.body.usersexpect(Array.isArray(users)).toBeTruthy()})
Here Supertest is using its API testing tools (expect
) to check the headers and HTTP status code it receives from its GET request to /users
. It gives us the response to test from the resolved promise. The test checks that there is a property named users
on the response body, and that it is an array.
As it is written above, we can't test the exact content being returned from the route because it could be different each time. We'd have to have the exact same database records every time we ran the test to ensure predictable behaviour. Tests that examine a route in this way are often referred to as integration tests, because they use multiple parts of the system (the database, network and filesystem in particular) which are not mocked.