Testing with Supertest

Supertest, which we previously used to test HTML routes, is a great way to test API routes we create.

Here's an example:

const request = require('supertest')
const server = require('../server.js')
test('/users route returns an object containing an array of users', () {
// Arrange
const expected = true
// Act
return request(server)
.get('/users')
.expect('Content-Type', /json/)
.expect(200)
.then(res => {
const users = res.body.users
// Assert
expect(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 in 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.