Integration Test on Express RESTful APIs using Jest and Supertest
--
We have seen how to do unit testing — for isolated function or unit — using jest testing framework in the introduction to Test Driven Development in JS/Node.js, Part 1 blog post. We assume that you are familiar with jest’s “describe” and “it” functions.
Testing multiple functions/units or testing that spans across different pieces of a web app is considered integration testing. Testing express web apis/endpoints or routes is an example of integration testing. We have seen how to build Restful api including CRUD operations using with node.js and express.js. You can find the simple express app and web apis we built in the github repo (see server.js file).
This blog illustrates how to do integration test on the simple express app, specifically the web apis/endpoints or routes. Before testing the api routes, we isolated all the CRUD operations into a server-routes.js file (like a stand-alone module). The testing file is server-routes.test.js.
GET request to actual endpoint
The block of code below shows how to test a get request to an actual endpoints, or database or as in our case, an external file(usStates.json file)
const express = require("express"); // import express
const serverRoutes = require("./server-routes"); //import file we are testing
const request = require("supertest"); // supertest is a framework that allows to easily test web apisconst app = express(); //an instance of an express app, a 'fake' express app
app.use("/states", serverRoutes); //routesdescribe("testing-server-routes", () => {
it("GET /states - success", async () => {
const { body } = await request(app).get("/states"); //uses the request function that calls on express app instance
expect(body).toEqual([
{
state: "NJ",
capital: "Trenton",
governor: "Phil Murphy",
},
{
state: "CT",
capital: "Hartford",
governor: "Ned Lamont",
},
{
state: "NY",
capital: "Albany",
governor: "Andrew Cuomo",
},
]);
});
});
The express, supertest modules are imported as express, request respectively. In addition to jest, the supertest module…