Testing REST APIs with Jest and Supertest

Souvik Kar Mahapatra
4 min readDec 14, 2024

--

source: souvikinator.xyz

How to Set Up Unit Tests for Your API Endpoints

Testing your API endpoints can save you a ton of time debugging issues down the line. In this guide, I’ll walk you through how to set up unit tests for API endpoints using Express, Jest, and Supertest.

Let’s get started! 🚀

Tools You’ll Need

We’ll use these NPM packages:

  • Express: For the server (though you can use any other framework).
  • Jest: For running our tests.
  • Supertest: To test our HTTP endpoints.

If you’re using VS Code, these extensions make life easier:

  • Jest
  • Jest Runner

Step 1: Install Dependencies

Run the following commands to install the required packages:

npm install express

For dev dependencies:

npm install -D jest supertest

Step 2: Set Up the Directory

Here’s what the directory structure looks like:

Don’t forget to set up your package.json:

{  
"name": "api-unit-testing",
"version": "1.0.0",
"scripts": {
"test": "jest api.test.js",
"start": "node server.js"
},
"dependencies": {
"express": "^4.18.1"
},
"devDependencies": {
"jest": "^28.1.2",
"supertest": "^6.2.3"
}
}

Step 3: Create a Simple Express Server

We’ll set up a basic Express server that accepts POST requests on the /post endpoint. If the request body doesn’t include both a title and body, it returns a 400 Bad Request status code.

Here’s the code:

// app.js  
const express = require("express");
const app = express();

app.use(express.json());

app.post("/post", (req, res) => {
const { title, body } = req.body;

if (!title || !body)
return res.sendStatus(400).json({ error: "title and body are required" });

return res.sendStatus(200);
});

module.exports = app;

And this is the server entry point:

const app = require("./app");  
const port = 3000;

app.listen(port, () => {
console.log(`http://localhost:${port} 🚀`);
});

Step 4: Write Your Test File

Let’s create the test file api.test.js to handle the tests.

// api.test.js  
const supertest = require("supertest");
const app = require("./app");

describe("Creating post", () => {
// Test cases go here
});

Using Supertest, we can simulate HTTP requests and compare responses without manually starting the server.

Step 5: Add Test Cases

We’ll write tests for three scenarios:

When both title and body are provided:

test("creating new post when both title and body are provided", async () => {  
const response = await supertest.agent(app).post("/post").send({
title: "Awesome post",
body: "Awesome post body",
});
expect(response.statusCode).toBe(200);
});

When either title or body is missing:

test("creating new post when either of the data is not provided", async () => {  
const response = await supertest.agent(app).post("/post").send({
title: "Awesome post",
});
expect(response.statusCode).toBe(400);
});

When both title and body are missing:

test("creating new post when no data is provided", async () => {  
const response = await supertest.agent(app).post("/post").send();
expect(response.statusCode).toBe(400);
});

And here’s the final test file:

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

describe("Creating post", () => {
test("creating new post when both title and body are provided", async () => {
const response = await supertest.agent(app).post("/post").send({
title: "Awesome post",
body: "Awesome post body",
});
expect(response.statusCode).toBe(200);
});

test("creating new post when either of the data is not provided", async () => {
const response = await supertest.agent(app).post("/post").send({
title: "Awesome post",
});
expect(response.statusCode).toBe(400);
});

test("creating new post when no data is provided", async () => {
const response = await supertest.agent(app).post("/post").send();
expect(response.statusCode).toBe(400);
});
});

Step 6: Run the Tests

To run the tests, use the command:

npm run test

Here’s how it looks when the tests pass:

If you’re using VS Code extensions like Jest or Jest Runner, you can run individual tests directly from the editor:

That’s It! 🎉

And there you have it — a simple way to test your API endpoints using Jest and Supertest. With this setup, you can confidently build and deploy your APIs, knowing they work exactly as expected.

Happy coding! 💪

--

--

Souvik Kar Mahapatra
Souvik Kar Mahapatra

Written by Souvik Kar Mahapatra

Building tools that matter | Notion-to-MD | Documenting at souvikinator.xyz | Automating the boring, sharing the journey.

No responses yet