Now comes my favorite part of the test, the high level API integration test. This is where we call the API endpoint directly as if we are posing as a real client.
The idea here is to set the application up with an open port and build a new database along with some fake seed data.
Then, make the API call programmatically with an HTTP library like fetch.
Finally, we make an assertion and check if the response is what we would expect from the client.
Here is how we'll be setting this test up.
File: tests/api/auth/register.test.js
constfetch=require('node-fetch')constapi=require('../../../src/server')constapiPort=Math.round(Math.random() *65535)constbaseURL=`http://localhost:${apiPort}/api/v1`constdb=require('../../../src/utils/db')let dbConnectionconstdbTestUtils=require('../../../tests/testUtils/dbTestUtil')/** * 1. Arrange * - setup the world */beforeAll(async () => {awaitapi.listen(apiPort) // start the application dbConnection =awaitdb() // start the database})beforeEach(async () => {awaitdbTestUtils.setUpDatabase()})afterEach(async () => {awaitdbTestUtils.clearDatabase()})afterAll(async () => {awaitapi.close()awaitdbConnection.disconnect()})/** * 2. Act * - make the http call * 3. Assert * - response check */describe('API Test - Register User', () => {// Tests go here})
The Passing Test
The first test is our happy path, so no errors. This is simple, make sure all the input requests are correct and that when we call the API, the user is successfully registered.