Home > backend > How to Use Jest to Test a RESTful API Built with Express.js and Node.js

How to Use Jest to Test a RESTful API Built with Express.js and Node.js

JestJs and Supertest are essential tools to test API endpoint.

By :Thomas Inyangđź•’ 18 Jan 2025

Jest_expressjs

Introduction

If you’ve ever interacted with an app that fetches data, sends a message, or processes a transaction—chances are, you’ve witnessed a REST API in action. But building and testing a RESTful API is not just functional but it's a skill set every backend developer should have.

In this guide, I’ll walk through

  1. Creating a REST API with Node.js and ExpressJS.
  2. How to implement and use testing strategies using Jest, SuperTest, and more.


Whether you’re an experienced backend developer or someone just breaking into full-stack development, this is your one-stop playbook for writing clean, testable, and scalable APIs.

Prerequisite

  1. NodeJs, ExpressJs, Nodemon, Jestjs, and Supertest should be installed.

What is a RESTful API and Why Does It Matter?

An API (Application Programming Interface), acts as a bridge between systems (Backend and Frontend). A RESTful API follows a set of architectural constraints like stateless communication, client-server separation, and resource-based URIs, and acts as a foundation of numerous web applications.

Understanding REST is essential not just for building APIs, but for testing and maintaining them as your app grows.

Node.js & Express: The Backbone of Modern REST APIs

This combo has built lots of tech companies' backend architecture.

Node.js enables developers to write server-side logic using JavaScript, while ExpressJS is a lightweight framework that simplifies routing, middleware integration, and API structuring.

See Also: What you Need to know About NodeJs.

Here's a quick setup:

Enter this to set up the environment from the terminal and answer the prompt that follows.

npm init -y


Step1: install the following

npm i supertest expressjs
npm install --save-dev jest
npm install --save-dev nodemon

Step2

Update your package.json file with this.

"scripts": {
"start": "nodemon index.js",
"test": "jest"
},
"nodemonConfig": {
"ignore": [
"**/test/**",
"**/docs/**"
],
"delay": 2500
},

If you use nodemon, include this nodemonConfig object. It will ensure nodemon ignores the test and docs folder.


Step 3: Create an index.js file in the root dir and enter this code.

```javascript

const express = require('express');
const app = express();

app.use(express.json());

app.get('/api/status', (req, res) => {
res.json({ status: 'API is working' });
});

app.listen(3000, () => console.log('Server is running on port 3000'));

In the same terminal, enter npm start to start the server.

See Also: RESTful API With BunJs and MongoDB.

Now that we’ve laid the foundation, let’s talk about ensuring this API doesn’t break under real-world conditions.

REST API Testing Basics: What You Need to Know

Testing isn’t optional. It’s how we build trust into our systems. I have had my fair share of not writing Test Scripts before deployment.

API testing focuses on checking whether your endpoints return the expected data under various conditions. The 3 core types are:

  1. Unit Testing: Test individual functions or modules.
  2. Integration Testing: Test multiple modules working together (e.g., database + controller).
  3. End-to-End Testing (E2E): Test the full flow from user input to database output.


Tools & Frameworks for Testing Node.js APIs

There are a lot of testing tools (manual or automatic), they come as extensions/ plugins or packages. I have used both Postman (Application & Extension) and ThunderClient (Extension) for manual testing for automated testing, tools like Jest, Mocha, and SuperTest shine.

⇒Jest: is developed by Facebook. It is a fast, zero-config testing tool with snapshot capabilities, ideal for unit and integration testing.

⇒SuperTest: Works seamlessly with Jest or Mocha it focuses on HTTP assertions, streamlining API integration testing workflows

⇒Mocha: Flexible and extensible test framework with BDD-style syntax, making it suitable for modular testing setups

⇒Chai : It's an assertion library used often with Mocha that enhances test readability with expressive assertion syntax for structured testing.

How to Setup Jest and Supertest to Test RESTful API.

I often use Jest and Supertest for testing my REST API automatically.


Step1.

Create the following folders and files :

  1. routes/taskRoutes.js.
  2. tests/task.test.js.
  3. app.js.
  4. index.js

This is how your folder structure will look like.

folder-structure


Step2.

In the taskRoutes.js file, enter this.

const express = require("express");
const router = express.Router();

let tasks = [
{ id: 1, task: "Learn Jest", completed: false },
{ id: 2, task: "Write Tests", completed: false },
];

router.get("/", (req, res) => {
res.status(200).json(tasks);
});

router.get("/:id", (req, res) => {
const { id } = req.params;
const task = tasks.find((t) => t.id === parseInt(id));
if (!task) {
return res.status(404).json({ error: "Todo not found" });
}
});
module.exports = router;

This file defines the API endpoints and a mock array of task objects is created to achieve the testing without connecting to a DB (can be connected later)


Step3.

In the app.js file, enter this.

const express = require("express");
const taskRoutes = require("./routes/taskRoutes");

const app = express();

app.use(express.json());
app.use("/api/todos", taskRoutes);

module.exports = app;

This file will be used to carry out the testing and also be used in the project entry point for running the server index.js.


Step4.

Set Up the server in the index.js file.

const express = require("express");
const taskRoutes = require("./routes/taskRoutes");

const app = express();

app.use(express.json());
app.use("/api/tasks", taskRoutes);
const PORT = 10000;

app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

This file will start the local server when you enter "npm run start“


Step5.

Start up the server. In the project terminal, enter this.

npm run start

This will start up the server.

See Also: How to Implement Cookies In GO (Gin-web)

Step6.

In the task.test.js file, write the test case for the rest api.

const request = require("supertest");
const app = require("../app");

describe("Tasks API Tests", () => {
it("should fetch all todos", async () => {
const res = await request(app).get("/api/tasks");
expect(res.statusCode).toBe(200);
expect(Array.isArray(res.body)).toBeTruthy();
});

it("should fetch a todo by ID", async () => {
const res = await request(app).get("/api/tasks/1");
expect(res.statusCode).toBe(200);
expect(res.body).toHaveProperty("id", 1);

expect(res.body).toHaveProperty("task", "Learn Jest");
});
});

In this code, the supertest package is imported for use.

The following methods: describe, it, expect, toBe, toBeTruthy, and toHaveProperty are all predefined methods of Jestjs to carry out effective testing.

  1. describe: it is used to create a block that contains several related tests. In this case "Tasks API Tests".
  2. expect: it is a function to test a value and it's used with a matcher.
  3. toBe: it is used to compare primitive values or to check the referential identity of object instances. This matcher is better than using strict "===" comparison.
  4. toBeTruthy: it is used when you don't really know the value but to enforce a true boolean context.
  5. toHaveProperty: it is used to check if property at provided reference key exists in an object.


Step7:

Running the test via the project dir terminal. Enter

npm run test

If everything runs fine, you will get this output.

JestJs

With these steps you can set up and test your preferred RESTful API.


The above steps can be done manually. Manual API testing involves using tools like Postman, Thunder Client, or Insomnia to create requests for each endpoint and validate status codes, response structure, and headers.


Open Postman or Thunder Client extension/plugin in your IDE (VsCode) and enter the URL with the HTTP method (GET, POST, PATCH, Or DELETE).


Both automatic and manual testing doesn't require much time to learn. With daily practice within 5–10 days is enough to cover basics.

Conclusion

In this post, you learned how to set up Jestjs to test a RESTful API using mock data.


As backend developers, writing test scripts is highly recommended, especially as your API tends to scale. Scaling often requires refactoring existing logic, which can introduce bugs.


Implementing proper tests ensures that changes won’t break your application in production. This makes testing an essential part of maintaining reliable and scalable backend systems.

Please Share

You may also like