Subscribe
How to Unit Test Node.js Express.js Applications with Jest
4 mins read

By: vishwesh

How to Unit Test Node.js Express.js Applications with Jest

If you are building web applications with Node.js and Express.js, it is essential to write unit tests to ensure your code is working correctly. Unit tests help you to catch errors and bugs before they make it to production, allowing you to deliver high-quality code with confidence. Jest is a popular testing framework that is easy to set up and use, making it an excellent choice for testing your Node.js and Express.js applications.

In this article, we will cover how to set up and write unit tests for your Node.js Express.js application using Jest.

Installing Jest

To get started with Jest, you first need to install it as a dev dependency in your project. Open your terminal or command prompt and navigate to your project's root directory, then run the following command:

npm install --save-dev jest

This command installs Jest and adds it as a dev dependency in your package.json file.

Setting Up Your Test Environment

Before you can start writing tests, you need to set up your test environment. Create a new folder in your project's root directory called __tests__. This folder will contain all of your test files.

Inside the __tests__ folder, create a new file called app.test.js. This file will contain your first test. In the app.test.js file, add the following code:

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

describe("Test the root path", () => {
  test("It should respond with a 200 status code", async () => {
    const response = await request(app).get("/");
    expect(response.statusCode).toBe(200);
  });
});

In this code, we are using supertest to simulate HTTP requests to our Express.js application. We are also requiring our app.js file, which contains our Express.js application.

The describe block is used to group related tests together. In this case, we are testing the root path of our application. The test block contains the actual test. In this case, we are testing that the root path returns a 200 status code.

Running Your Tests

To run your tests, open your terminal or command prompt and navigate to your project's root directory. Then run the following command:

npm test

This command runs all of your Jest tests. You should see output similar to the following:

 PASS  __tests__/app.test.js
  Test the root path
    ✓ It should respond with a 200 status code (6 ms)

Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        1.824 s, estimated 2 s
Ran all test suites.

Congratulations! You have written and run your first Jest test.

Writing More Tests

Now that you have your test environment set up, it's time to write more tests. Here are some examples of tests you can write for your Node.js Express.js application:

Testing a GET Request

describe("Test the GET /users path", () => {
  test("It should respond with a list of users", async () => {
    const response = await request(app).get("/users");
    expect(response.statusCode).toBe(200);
    expect(response.body.length).toBeGreaterThan(0);
  });
});

In this test, we are testing a GET request to the /users path. We expect the response to return a 200 status code and a non-empty list of users.

Testing a POST Request

describe("Test the POST /users path", () => {
  test("It should create a new user", async () => {
    const newUser = {
      name: "John Doe",
      email: "john.doe@example.com",
      password: "password123"
    };

    const response = await request(app).post("/users").send(newUser);

    expect(response.statusCode).toBe(201);
    expect(response.body).toMatchObject(newUser);
  });
});

In this test, we are testing a POST request to the /users path. We are sending a new user object in the request body and expecting the response to return a 201 status code and the same user object that we sent.

Testing Error Handling

describe("Test error handling", () => {
  test("It should return a 404 status code for an invalid path", async () => {
    const response = await request(app).get("/invalid-path");
    expect(response.statusCode).toBe(404);
  });

  test("It should return a 400 status code for a bad request", async () => {
    const response = await request(app).post("/users").send({});
    expect(response.statusCode).toBe(400);
  });
});

In this test, we are testing error handling in our Express.js application. We are testing that an invalid path returns a 404 status code and that a bad request returns a 400 status code.

Conclusion

In this article, we have covered how to set up and write unit tests for your Node.js Express.js application using Jest. We have covered the basics of Jest and demonstrated how to write tests for GET and POST requests, as well as error handling.

Writing unit tests is an essential part of building high-quality web applications. By testing your code, you can catch errors and bugs early in the development process and deliver a more reliable product to your users.

If you are new to unit testing, we recommend that you start with simple tests and gradually add more complex tests as you become more familiar with the process. With Jest, writing unit tests for your Node.js Express.js applications is easy and straightforward, so start testing your code today!

Recent posts

Don't miss the latest trends

    Popular Posts

    Popular Categories