How to Test Express APIs With Jest

Testing, while it can be time-consuming, is an important step in the development cycle of any application. It ensures you catch bugs and issues early on before you push code to production.

You can use Jest to test an Express Rest API. After you’ve created a simple CRUD API, discover how to write tests for each endpoint.

4

What Is Jest?

There are many JavaScript testing libraries that you can choose from, butJestis the easiest to start with. It is a testing library developed by Facebook, mostly used to test React projects. However, you can also use it to test Node and other JavaScript-based projects. It was developed on top of Jasmine, another testing tool, and comes bundled with its own assertion library.

While you won’t need an assertion library to write tests in Jest, you will need to use a tool to make HTTP requests. This article uses SuperTest.

The

What Is SuperTest?

SuperTestis a Node testing library for HTTP calls. It extends the superagent testing library and allows you to make requests like GET, POST, PUT, and DELETE.

SuperTest provides a request object you can use to make HTTP requests.

Soundbar and TV

Here, you pass the base URL of the API to the request object and then chain the HTTP method with the rest of the URL. Theend()method calls the API server and the callback function handles its response.

Once you get the response from the API, you can use Jest to validate it.

Mint Mobile SIM Protection Number Lock with SIM cards on table

Create an Express API

To test your own API endpoints, you need to createa REST APIfirst. The API you will create is quite simple. It inserts, retrieves, updates, and deletes items from an array.

Begin by creating a new directory called node-jest and initializing npm.

check mark on yellow sticky note

Next, create a new file calledindex.jsandcreate the Express server.

Test the GET /todos Endpoint

The first endpoint you will create is the GET /todos endpoint. It returns all the items in the array. In index.js, add the following.

Note the response has a status code of 200 and a JSON object containing the to-dos item in an array called data and an error message. This is what you will test using Jest.

Now, install Jest and SuperTest:

Then, add a test script inpackage.jsonas follows:

Before you start writing your own tests, you should understand how to write a basic test in Jest.

Consider the following function:

In the test file, you need to:

Thedescribekeyword specifies the group of tests and theteststatement specifies the specific test. If the value returned from the function matches the value passed totoBe, the test passes.

When testing API endpoints, you won’t be calling a function but sending a request using SuperTest or another HTTP client library.

Returning to the GET endpoint, create a new file calledapi.test.js. This is where you will write all the endpoint tests. Naming the test file with a.testinfix ensures that Jest recognizes it as a test file.

In api.test.js, import supertest and set the base URL like so:

Next, create the first test in the describe block:

Before running the tests, you will need to define setup and teardown functions. These functions will populate the todo array with an item before the test and delete the dummy data after each test.

The code that runs before all the tests is in the beforeAll() function. The code that runs after all the tests is in the afterAll() function.

In this example, you are simply hitting the POST and DELETE endpoints for each. In a real application, you would probably connect to a mock database containing the test data.

In this test, you first made a request to the GET /todos endpoint and compared the response sent back to the expected results. This test suite will pass if the response has anHTTP status codeof 200, the data is not empty, and the error message is null.

Test the POST /todo Endpoint

In index.js, create the POST /todo endpoint:

In this test, you will need to send the todo details in the request body using the send() method.

The POST /todo request should return a 201 status code and the todos array with the new item added at the end. Here is what the test might look like:

Here, you are passing the todo data to the send() method as an argument. The response should have a 201 status code and also contain all the todo items in a data object. To test whether todo was actually created, check whether the last entry in the returned todos matches the one you sent in the request.

The PUT /todos/:id endpoint should return the updated item:

Test the response as follows:

The completed value in the response body should be true. Remember to include the id of the item you want to update in the URL.

Test the DELETE /todos/:id Endpoint

In index.js, create the DELETE endpoint. It should return the todo data without the deleted item.

To test the endpoint, you can check whether the deleted item still exists in the returned data:

The data returned from the DELETE endpoint should not contain the deleted item. Since the returned items are in an array, you can use Array[id] to check whether the API deleted the item correctly. The result should be false.

Creating REST APIs

In this article, you learned how to test an Express Rest API using Jest API. You wrote tests for the GET, PUT, POST, and DELETE HTTP requests and saw how to send data to the endpoint in the URL and the request. You should be able to apply this knowledge when testing your own Rest API.

Get to grips with APIs by understanding the importance of RESTful APIs and how to use them in Node.js.

Now, I actually finish the books I start.

Your phone’s camera app doesn’t show this, so it’s easy to miss.

Quality apps that don’t cost anything.

Freeing up vital memory on Windows only takes a moment, and your computer will feel much faster once you’re done.

These plugins will make you wonder why you used Photoshop in the first place.

Technology Explained

PC & Mobile