Test REST APIs using Jest and Supertest

Rohan Thakur
Feb 12, 2022

--

Testing is an important practice that is often ignored. It helps to prevent bugs, reduce development costs, and improve performance. In this article, we are going to test a rest API using a testing framework called Jest.

Photo by mari lezhava on Unsplash

First, we will create a simple express application and will separate our app from the server so it won't listen to the port after testing.

app.js
server.js

We will install the required packages for testing our app.

We also need to add a test script in package.json.

package.json

We will create a POST route that will send us the reverse of the string passed in the request.

app.js

We will create a reverse.test.js file to test this route using jest and supertest.

reverse.test.js

Now, we will test the route.

Voilà! We have successfully tested our route.

Source code: https://github.com/Xebec19/jest-medium

--

--

No responses yet