Paramclasses Academy - Blog

Tutorials Details

←
Post 35 of 40
→

Unit Testing Node.js Applications with Jest

 Unit Testing Node.js Applications with Jest

October 30, 2026

✦ Unit Testing Node.js Applications with Jest

When developing applications with Node.js, writing code is only one part of the development process. Developers also need to check whether their functions, modules, and application logic work correctly.

This is where Unit Testing becomes important.

Unit testing helps developers test individual parts of an application to identify errors before they become bigger problems. Jest is a popular JavaScript testing framework that makes it easier to write and run automated tests.

In this tutorial, you will learn how to install Jest, create test files, write test cases, use assertions, and test practical Node.js functions.

✦ 1. What Is Unit Testing in Node.js?

Unit testing is a software testing technique in which individual units of code are tested independently.

A unit can be:

  • A JavaScript function.

  • A calculation module.

  • A validation function.

  • A utility method.

  • A small part of an application.

For example, imagine you have a function that adds two numbers.

function add(a, b) {
    return a + b;
}

You can write a test to check whether the function returns the correct result.

const result = add(10, 20);

console.log(result);

Expected output:

30

Instead of manually checking results every time, automated tests can verify them whenever you update your code.

✦ 2. What Is Jest?

Jest is a JavaScript testing framework used to test JavaScript and Node.js applications.

It provides several useful features:

  • Simple test syntax.

  • Built-in assertion methods.

  • Test grouping using describe().

  • Mock functions.

  • Code coverage reports.

  • Asynchronous testing support.

  • Automatic test discovery.

Jest helps developers automate repetitive testing tasks and identify problems during development.

✦ 3. Create a Node.js Project

First, create a new project folder.

Open your terminal and execute:

mkdir node-jest-project
cd node-jest-project

Initialize the Node.js project:

npm init -y

This command creates a package.json file.

The file stores project information, scripts, and dependencies.

✦ 4. Install Jest

Install Jest as a development dependency:

npm install --save-dev jest

After installation, open your package.json file and configure the test script:

{
    "name": "node-jest-project",
    "version": "1.0.0",
    "scripts": {
        "test": "jest"
    },
    "devDependencies": {
        "jest": "^30.0.0"
    }
}

The Jest version shown is illustrative. Your installed version may be different.

Now you can execute:

npm test

Jest will search for test files in your project.

✦ 5. Understand Jest Project Structure

Create the following project structure:

node-jest-project/
│
├── node_modules/
│
├── package.json
│
├── calculator.js
│
└── calculator.test.js

Here:

  • calculator.js contains the application functions.

  • calculator.test.js contains automated test cases.

  • package.json contains project configuration.

Jest commonly recognizes files ending with .test.js or .spec.js.

✦ 6. Create Your First Node.js Function

Open calculator.js and write the following code:

function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

function multiply(a, b) {
    return a * b;
}

function divide(a, b) {
    if (b === 0) {
        throw new Error("Cannot divide by zero");
    }

    return a / b;
}

module.exports = {
    add,
    subtract,
    multiply,
    divide
};

This module contains four mathematical functions.

The module.exports statement makes these functions available to other CommonJS files.

✦ 7. Write Your First Jest Test

Now open calculator.test.js.

Add the following code:

const {
    add,
    subtract,
    multiply,
    divide
} = require("./calculator");

test("Addition should return 30", () => {
    expect(add(10, 20)).toBe(30);
});

Run your test:

npm test

Expected result:

PASS ./calculator.test.js

✓ Addition should return 30

Congratulations! You have successfully written and executed your first Jest test.

✦ 8. Understand test() and expect()

Jest provides several important functions for writing tests.

❖ test()

The test() function defines an individual test case.

test("Check addition", () => {
    expect(5 + 5).toBe(10);
});

The first argument describes the test, while the second argument contains the code that Jest executes.

❖ expect()

The expect() function creates an expectation about a value.

expect(10).toBe(10);

This checks whether the actual value matches the expected value.

❖ toBe()

Used for exact equality checks, particularly primitive values.

expect(5).toBe(5);

❖ toEqual()

Used to compare objects and arrays by their values.

expect({
    name: "Rahul",
    age: 22
}).toEqual({
    name: "Rahul",
    age: 22
});

❖ toBeTruthy() and toBeFalsy()

These matchers check whether a value is truthy or falsy.

expect(true).toBeTruthy();

expect(false).toBeFalsy();

✦ 9. Test Multiple Functions Using describe()

When an application contains many test cases, grouping related tests makes them easier to understand.

Jest provides describe() for grouping tests.

Update calculator.test.js:

const {
    add,
    subtract,
    multiply,
    divide
} = require("./calculator");

describe("Calculator Testing", () => {

    test("Addition", () => {
        expect(add(10, 20)).toBe(30);
    });

    test("Subtraction", () => {
        expect(subtract(20, 10)).toBe(10);
    });

    test("Multiplication", () => {
        expect(multiply(5, 5)).toBe(25);
    });

    test("Division", () => {
        expect(divide(20, 5)).toBe(4);
    });

});

Run:

npm test

Jest executes all four test cases.

✦ 10. Test Error Handling

Testing successful operations is important, but testing errors is equally necessary.

Our division function throws an error when the second number is zero.

Let's test it:

test("Division by zero should throw an error", () => {
    expect(() => {
        divide(10, 0);
    }).toThrow("Cannot divide by zero");
});

The toThrow() matcher checks whether a function throws an expected error.

This helps developers verify that their error-handling logic works correctly.

✦ 11. Test an Async Function in Node.js

Modern Node.js applications frequently use asynchronous functions to communicate with databases and external APIs.

Jest supports testing asynchronous code.

Create a file named user.js:

async function getUser() {
    return {
        id: 1,
        name: "Rahul",
        email: "rahul@example.com"
    };
}

module.exports = getUser;

Create user.test.js:

const getUser = require("./user");

test("Should return user details", async () => {

    const user = await getUser();

    expect(user.name).toBe("Rahul");

    expect(user.email).toBe(
        "rahul@example.com"
    );

});

Run:

npm test

Jest waits for the asynchronous test to finish because the test function returns a Promise through async.

✦ 12. Use beforeEach() and afterEach()

Sometimes developers need to execute common setup or cleanup operations before or after every test.

Jest provides two useful methods:

❖ beforeEach()

Runs before each test in its scope.

❖ afterEach()

Runs after each test in its scope.

Example:

let user;

beforeEach(() => {
    user = {
        name: "Rahul",
        age: 22
    };
});

afterEach(() => {
    user = null;
});

test("Check user name", () => {
    expect(user.name).toBe("Rahul");
});

test("Check user age", () => {
    expect(user.age).toBe(22);
});

These methods are useful when tests need fresh data or cleanup.

✦ 13. Understand Mock Functions in Jest

Mock functions allow developers to replace real functions with controlled test functions.

They are useful when testing code that depends on external services, database calls, or other modules.

Example:

test("Check mock function", () => {

    const sendEmail = jest.fn();

    sendEmail("rahul@example.com");

    expect(sendEmail).toHaveBeenCalled();

    expect(sendEmail).toHaveBeenCalledWith(
        "rahul@example.com"
    );

});

Here, jest.fn() creates a mock function.

The test checks whether it was called and whether it received the expected argument.

✦ 14. Generate Code Coverage Reports

Code coverage helps developers understand which parts of their code are executed during tests.

Run:

npm test -- --coverage

Jest generates a coverage summary.

Common coverage measurements include:

Coverage Type Meaning
Statements Percentage of executed statements
Branches Percentage of executed conditional branches
Functions Percentage of executed functions
Lines Percentage of executed lines

High coverage does not automatically mean that an application is bug-free. Tests must also verify meaningful expected behavior.

✦ 15. Complete Jest Testing Example

Let's combine our calculator tests into one complete test file.

calculator.js

function add(a, b) {
    return a + b;
}

function subtract(a, b) {
    return a - b;
}

function multiply(a, b) {
    return a * b;
}

function divide(a, b) {
    if (b === 0) {
        throw new Error("Cannot divide by zero");
    }

    return a / b;
}

module.exports = {
    add,
    subtract,
    multiply,
    divide
};

calculator.test.js

const {
    add,
    subtract,
    multiply,
    divide
} = require("./calculator");

describe("Calculator Unit Tests", () => {

    test("Addition test", () => {
        expect(add(10, 20)).toBe(30);
    });

    test("Subtraction test", () => {
        expect(subtract(20, 10)).toBe(10);
    });

    test("Multiplication test", () => {
        expect(multiply(5, 5)).toBe(25);
    });

    test("Division test", () => {
        expect(divide(20, 5)).toBe(4);
    });

    test("Division by zero test", () => {
        expect(() => divide(10, 0))
            .toThrow("Cannot divide by zero");
    });

});

Execute:

npm test

All five test cases should pass if the implementation is correct.

✦ 16. Best Practices for Jest Testing

Follow these practices when writing tests for professional Node.js applications:

  1. Write separate test files for different modules.

  2. Use meaningful test descriptions.

  3. Test both successful and unsuccessful scenarios.

  4. Test edge cases and invalid inputs.

  5. Use mock functions for external dependencies when appropriate.

  6. Keep tests independent from one another.

  7. Avoid relying on production databases during unit tests.

  8. Run tests after important code changes.

  9. Review code coverage without treating it as the only measure of quality.

  10. Include automated tests in your development workflow.

✦ Frequently Asked Questions (FAQs)

❖ Q1. What is Jest in Node.js?

Jest is a JavaScript testing framework used to write and execute automated tests for Node.js and JavaScript applications.

❖ Q2. How do I install Jest?

Run npm install --save-dev jest in your Node.js project directory.

❖ Q3. What is the difference between test() and describe()?

test() defines an individual test case, while describe() groups related test cases together.

❖ Q4. What is expect() in Jest?

expect() is used to create assertions that check whether the actual result matches the expected result.

❖ Q5. Can Jest test asynchronous functions?

Yes. Jest supports asynchronous tests using Promises, async/await, and other supported asynchronous patterns.

❖ Q6. What is code coverage in Jest?

Code coverage measures how much of your source code is executed by your test cases.

✦ Conclusion

Unit testing is an important part of professional Node.js development. It helps developers verify individual functions, identify bugs, test error handling, and maintain application quality.

Jest makes testing easier with simple functions such as test(), describe(), expect(), and toThrow(). It also supports asynchronous tests, mock functions, and code coverage reports.

At Param Classes, students can learn practical Node.js development, Express.js, backend programming, and testing techniques through hands-on examples and real-world projects.

Visit Param Classes: https://paramclasses.in/

←
Post 35 of 40
→