How to Unit Test your Express Js API With Jest?
Hello 👋🏼, This is the third part of my Unit Testing Tutorial.
In this occasion, we'll learn how to test an Express Js API.
The goal here is to test the request and responses of our API and
ensure that it runs smoothly.
Our working environment is Express Js, Axios, Express Validator, and Jest for Unit Testing.
Set Up your Express Js Server.
- We'll start by creating an empty folder and initializing our project there.
mkdir express-tutorial cd express-tutorial npm init -y
- Once the project has been initialized, install the Express Js library and the Express Validator.
npm i express express-validator
Go to the project root, create a
folder, and inside create
file will hold all our routes. Learn more about the
mkdir routes cd routes touch routes.js
- Open this file in your favorite editor and copy the following code.
index.jsin the project root and copy the following code.
Run your first API test.
Let's get ready to run our first test; install Jest, Axios, and the Nodemon library; all in development mode. Soon, Node will be able to watch for file changes, so in the future, you will not need to install Nodemon.
npm i -D jest nodemon axios
Add the scripts to
package.json, so we
don't have to type the commands constantly. If you want the test to
restart on every file change, add
--watchAll to Jest.
__test__folder in the project root, and inside create
mkdir __test__ cd __test__ touch index.test.js
Run your server with
npm run dev, then
on a separate terminal, run the test with
make sure that the status code return from the server is 200 and the data is the
Hello World! string.
Test a simple Login route.
Let's build a simple login route to test a POST http request.
First, add the following code to
index.test.jsand test your login route.
How to Test the Express Validator?
In the last part of this testing tutorial, we'll use the
to test the login route. First, go to
routes.js and modify
the login route. Return status code 400 if the validation fails.
index.test.js and test the
Express Validator. When testing APIs, don't forget to check
error codes and messages. See you next time!