Performing NodeJS Unit testing using Jest

Learn Node.js unit testing with Jest, using mocking, snapshots, and best practices to ensure reliable and efficient application performance.

Get Started free
NodeJS Unit testing using Jest
Home Guide Performing NodeJS Unit testing using Jest

Performing NodeJS Unit testing using Jest

Unit testing is essential for ensuring the reliability and performance of Node.js applications. Jest simplifies this process by providing tools to test individual components effectively and catch bugs early in the development cycle.

Overview

What is Jest in Node.JS

Jest is a fast, lightweight JavaScript testing framework widely used in Node.js environments for unit and integration testing. It helps developers with built-in features like mocking, snapshot testing, and code coverage.

Key Features of Jest:

  • Simple Setup: Jest requires minimal configuration, making it easy to integrate into Node.js projects.
  • Mocking Capabilities: Easily mock functions, modules, or timers to test components in i solation.
  • Snapshot Testing: Capture the output of components and compare them over time to catch UI changes.
  • Built-in Coverage Reports: Generate detailed test coverage reports without additional setup.
  • Zero Dependencies: Jest runs out of the box with no additional dependencies for most projects.
  • Works with Popular Frameworks: Compatible with Babel, TypeScript, React, Angular, and Vue.
  • Parallel Test Execution: Runs tests in parallel to speed up execution and improve efficiency.

Why Use Jest for Node.js Testing?

  • Speed: Jest ensures quick test execution, enhancing development efficiency.
  • Reliability: It provides a consistent and dependable testing framework.
  • Ease of Use: Jest simplifies the testing process with minimal setup.
  • Early Bug Detection: It helps catch bugs early, maintaining code quality.
  • Versatility: Suitable for both frontend and backend projects.

This guide offers a quick overview of Jest in Node.js, showcasing its speed, simplicity, and built-in tools for effective testing.

What is NodeJS Unit testing?

Node.js unit testing involves testing individual units of code (such as functions or modules) in isolation to ensure they work as expected. It helps catch bugs early, improve code quality, and ensure reliable application behavior. For your NodeJS applications, Jest framework can be used for Unit Testing.

NodeJS Unit testing is the method of testing small pieces of code/components in isolation in your NodeJS application. This improves the code quality and find bugs early in the development life cycle. This also provides an added advantage to the users in the way that they can add any new features without breaking any other part of their application.

Benefits of Node.js Unit Testing

Node.js unit testing continues to provide many benefits in 2025, just as in previous years. Some of the critical benefits of Node.js unit testing include:

  1. Ensuring code quality: Unit testing helps ensure that code works as intended and meets quality standards. This is especially important in Node.js, often used for mission-critical applications.
  2. Fast and scalable: NodeJS is built on top of Google’s V8 JavaScript engine, which makes it very fast and efficient. It is also designed to be highly scalable, making it a popular choice for building large-scale, high-traffic applications.
  3. Cross-platform: It is a cross-platform environment, which means it can run on various operating systems, including Windows, macOS, and Linux..
  4. Enabling continuous integration and delivery: Unit testing can be integrated with CI/CD pipelines to ensure that code is tested automatically whenever it is changed. This helps catch errors and regressions quickly before they become production.
  5. Huge ecosystem: NodeJS has a vast and growing ecosystem of open-source libraries and frameworks that can be used to build a wide range of applications, from web servers to desktop applications.
  6. Improving maintainability: Unit tests serve as a form of documentation for the code, making it easier to understand and maintain over time.

What is Jest in NodeJS?

Jest is a popular JavaScript testing framework primarily used for testing code written in Node.js and React applications. It was developed and is maintained by Meta. It primarily focuses on simplicity and support for large web applications. Jest was built on top of Jasmine with multiple layers.

What is Jest Framework?

Jest is an open-source Javascript testing framework developed by Facebook. It was mainly built for React, Node, Babel, TypeScript, Angular, Vue, and JavaScript-based applications. It primarily focuses on simplicity and support for large web applications. Jest was built on top of Jasmine with multiple layers.

Features of Jest Framework

Here are the features of Jest Framework:

  • Built-in module and function mocking
  • Snapshot testing for UI regression
  • Automatic generation of detailed code coverage reports
  • Wide range of matchers for precise assertions
  • Integrations with Node.js and popular frameworks
  • Offers Watch mode to re-run tests on file changes
  • Optimized for fast and parallel test execution

Use Cases of Jest

Jest caters to a wide range of testing scenarios, making it a versatile tool for ensuring application reliability. Its features allow developers to test individual components, verify module interactions, validate APIs, and detect regression issues. It leverages built-in mocking and snapshot capabilities for efficient testing workflows.

Here are some of the common use cases of Jest:

  • Unit Testing: Test individual components or functions in isolation.
  • Integration Testing: Verify the interaction between different modules or services.
  • UI Testing: Perform snapshot tests to ensure consistent UI rendering.
  • API Testing: Validate server-side logic and RESTful endpoints.
  • Mocking and Spying: Test behavior by simulating dependencies and observing function calls.
  • Regression Testing: Detect unintended changes in application behavior over time.

Different Types of Unit Testing with Jest

Jest supports various styles and techniques of unit testing, depending on what you are testing and how much isolation you need.

  • Basic Function Testing: This type of test checks whether a standalone function returns the expected output for given inputs. It’s used to validate the core logic of pure functions without involving any external dependencies.
  • Mock Function Testing: Jest allows you to create mock functions to test whether a function is called, how many times it’s called, and with what arguments. This is useful when testing functions that use callbacks or event handlers.
  • Module Mocking: Instead of relying on actual modules (like a database or API), Jest lets you mock entire modules to return controlled data. This ensures that the unit test doesn’t depend on external services and can run in isolation.
  • Dependency Injection Testing: This involves passing mocked dependencies into a function or class manually. It’s commonly used in testing services or controllers where you want to control the behavior of internal logic or external modules.
  • Async and Timer Testing: Jest supports testing asynchronous code that uses Promises, async/await, or timers like setTimeout. You can simulate and control the flow of time using Jest’s fake timers to test delayed or time-based logic.
  • Snapshot Testing: Although often used in UI testing, snapshot testing can also be used in unit tests to capture a function’s output and compare it over time. This helps detect unexpected changes in the output.
  • Code Coverage Testing: While not a type of test itself, code coverage helps identify which parts of your code are tested. Jest can generate reports showing how much of the codebase your unit tests exercise.

Key Methods of Jest for BDD-Style Testing

Jest uses BDD-style tests. Each test suite has one main describe block and can have multiple test blocks. These test blocks can have nested describe blocks as well.

There are three main methods in this test file:

  1. describe() – It is a suite of Test scripts that gives an outer description for the test suite
  2. test() – It is the smallest unit test case written to be executed. String in quotes represents the test name
  3. expect() – It is an assertion. Every test() statement has an expect() function, which takes a value and expects a return in true form.

Apart from the above methods, several Jest Matchers assert certain conditions.

Types of Jest Matchers

Jest assertions use matches to assert on a condition in different ways. Jest uses matchers from the expect API. For the full list, see the Expect API doc.

Jest Matchers:

  1. Equality
  2. Truthiness Assertion
  3. Numeric Comparison Matchers
  4. String Matchers

Let’s walk through some of the most commonly used matchers along with Jest tests:

1. Equality

This is the most commonly used matcher. This is used for arithmetic operations and for checking equality or inequality.

For Example

test("Exact value matchers", () => {

   expect(2*2).toBe(4);

   expect(4-2).not.toBe(1);

 })

toBe and not.toBe are analogous to equals and not equals, respectively.

2. Truthiness Assertion

This is used for null, falsy, and truthy i.e. false and true values. Anything that is not logically true is falsy. number 0, null, empty string, and NaN are all examples of falsy concerning JavaScript.

test("truthiness Assertion", () => {

   var test="Software Testing demo"

   var n = null

   expect(n).toBeNull()

   expect(name).not.toBeNull

   // test should have a valid value

   expect(test).toBeTruthy()

   //fail - as null is unsuccess

   expect(n).toBeTruthy()

   // pass - null worked as false or negative

   expect(n).toBeFalsy()

   // 0 - work as false

   expect(0).toBeFalsy()

 })

3. Numeric Comparison Matchers

This is generally used for arithmetic operations such as greaterThan, lessThan, greaterThanOrEqual etc.

For Example:

test("numeric comparison", () => {

   var number1 = 100;

   var number2 = -20;

   var number3 = 0; 

   // validate greater than

   expect(number1).toBeGreaterThan(10) 

   // validate less than or equal

   expect(number2).toBeLessThanOrEqual(0)

   // validate greater than or equal

   expect(number3).toBeGreaterThanOrEqual(0)

 })

4. String Matchers

This provides matchers for strings to be matched against a regular expression.

For Example:

test("string matchers",() => {

   var string1 = "BrowserStack - Automation tool" 

   // test for match the string - Success

   expect(string1).toMatch(/tool/);




   // test for not match the string - Failure

   expect(string1).not.toMatch(/abc/)


 })

How to Install and Set up Jest for NodeJS Unit Testing?

Follow the steps below to install and set up Jest for NodeJS testing:

Step 1: Create a new directory for your project file:

mkdir JestApp

Step 2: Go to the new directory and execute the below command to initialize a project with Default configurations:

cd JestApp

npm init --y

Step 3: The above step creates a package.json file. Launch this project in any of the source-code editors (Using VS Code in my case)

Step 4: Create two folders named src and test respectively. src stores the main file where the program’s source code is written. test is where test cases for unit testing are stored.

Install and Set up Jest Framework for Unit Testing

Step 5: Create a calculator.js file under the src folder and calculator.test.js file under the test folder (as shown in the screenshot above)

Step 6: Open the package.json file and change the “scripts” block to “jest” using the below code.

{

  "name": "jest",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

  "test": "jest"

  },

  "keywords": [],

  "author": "",

  "license": "ISC"

  }

Step 7: In the terminal, type the following for installing Jest:

npm install --save-dev jest

The package.json file will look like this once Jest is installed. You could also add configuration in the package.json file to see the code coverage report of your test cases later.

{

  "name": "jest",

  "version": "1.0.0",

  "description": "",

  "main": "index.js",

  "scripts": {

    "test": "jest"

  },

  "keywords": [],

  "author": "",

  "license": "ISC",

  "dependencies": {

    "jest": "^29.7.0"

  }

}

Creating a Simple NodeJS App

Once done with setting up unit testing Node js with Jest, let us start by creating a Simple NodeJS application that performs addition, subtraction, multiplication, and division of two numbers just like a calculator.

For the source code, enter the following snippet under the calculator.js file:e:

const CalculationOperations = {

    Add: function(a,b) {

    return a + b;

    },

   

    subtract: function(a,b) {

    return a - b;

    },

    multiple: function(a,b) {

    return a * b;

    },

    divide: function(a,b) {

    return a / b;

    }

    }

    module.exports = CalculationOperations

Run NodeJS Unit Test using Jest: Example

For the test cases, enter the following snippet under the calculator.test.js file:

const CalculationOperations = require('../src/calculator');

 

describe("Calculation TestCases", () => {

 test("Add 2 numbers", () => {

    //Call function of Add

   var sum = CalculationOperations.Add(1,2)

   // assertions

   expect(sum).toBe(3);

 });

 test("Subtract 2 numbers", () => {

    //Call function of Subtract

   var subtract = CalculationOperations.subtract(10,2)

   // assertion

   expect(subtract).toBe(8);

 });

 test("Multiple 2 numbers", () => {

   // Call function of Subtract

   var multiple = CalculationOperations.multiple(2,8)

   // assertion

   expect(multiple).toBe(16);

 });

 test("Divide 2 numbers", () => {

  // Call function to divide the number

  var divide = CalculationOperations.divide(24,8)

  // assertion

  expect(divide).toBe(3);

});

})

Now, let’s break our test on purpose. Update the calculator.test.js file to the following code snippet:

const CalculationOperations = require('../src/calculator');

 

describe("Calculation TestCases", () => {

 test("Add 2 numbers", () => {

    //Call function of Add

   var sum = CalculationOperations.Add(1,2)

   // assertions

   expect(sum).toBe(3);

 });

 test("Subtract 2 numbers", () => {

    //Call function of Subtract

   var subtract = CalculationOperations.subtract(10,2)

   // assertion

   expect(subtract).toBe(21); //Update the value to failure purpose

 });

 test("Multiple 2 numbers", () => {

   // Call function of Subtract

   var multiple = CalculationOperations.multiple(2,8)

   // assertion

   expect(multiple).toBe(10); //Update the value to failure purpose

 });

 test("Divide 2 numbers", () => {

  // Call function to divide the number

  var divide = CalculationOperations.divide(24,8)

  // assertion

  expect(divide).toBe(3);

});

})

The second and third tests were updated to throw an error. Rerun the test using the below command

npm run test

A failed result will look something like this:

Failed Test Result for Unit Test in Jest

Similarly, multiple Unit test cases can be written for your NodeJS application using Jest.

The quality of your NodeJS applications can be easily improved with Unit Testing since it helps find bugs and defects in your code. Moreover, the early discovery of Code bugs in the SDLC reduces the overall development cost because less time is spent on bug fixing in the later stage of the project.

  • Once the unit testing is done, it is suggested to test the application end to end on real devices and browsers to identify bottlenecks in the user experience.
  • Using a real device cloud, like BrowserStack, allows you to test on 3500+ browser device combinations under real user conditions.
  • BrowserStack is compatible with automation frameworks like SeleniumCypress, Playwright, Puppeteer, etc. It is also compatible with CI/CD tools like Jenkins, Travis CI, CircleCI, Bamboo, etc.
  • With the latest BrowserStack Test Observability, test reporting, precision debugging, flaky test detection and more are available on a single dashboard.
  • File rich bug reports with relevant context, stack traces and more on Jira in a single click.

Advanced NodeJS Unit Tests with Jest

As your application grows, you’ll encounter more complex scenarios like asynchronous functions, external dependencies, error handling, and the need to measure test coverage.

Mastering these aspects helps ensure your application remains stable and bug-free.

1. Testing Asynchronous Code

Modern Node.js apps often deal with asynchronous operations using Promises or async/await. Jest supports both styles.

Code Sample for Using async/await

// fetchData.js

const fetch = require('node-fetch');

async function fetchData() {

  const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');

  return response.json();

}

module.exports = fetchData;
// fetchData.test.js

const fetchData = require('./fetchData');




test('fetches post data', async () => {

  const data = await fetchData();

  expect(data).toHaveProperty('id', 1);

});

Here, Jest will wait for the async function to resolve before finishing the test.

2. Mocking Functions

Mocking is useful to test code without hitting real services like databases or APIs. Jest lets you create mock functions or mock modules.

Code Sample Mocking a Dependency

// sendEmail.js

const emailService = require('./emailService');

function sendEmailToUser(user) {

  return emailService.send(user.email, 'Welcome!');

}

module.exports = sendEmailToUser;
// sendEmail.test.js

jest.mock('./emailService'); // Auto-mock the module

const emailService = require('./emailService');

const sendEmailToUser = require('./sendEmail');




test('calls email service with correct arguments', () => {

  const user = { email: 'test@example.com' };

  sendEmailToUser(user);

  expect(emailService.send).toHaveBeenCalledWith('test@example.com', 'Welcome!');

});

Here, you can use jest.fn() or jest.mock() to control dependencies and verify behavior.

3. Testing Error Handling

You should test how your code handles invalid input, failed promises, or thrown errors to ensure stability under failure conditions.

Code Sample Expecting a Function to Throw:

// divide.js

function divide(a, b) {

  if (b === 0) throw new Error('Cannot divide by zero');

  return a / b;

}

module.exports = divide;
// divide.test.js

const divide = require('./divide');




test('throws an error when dividing by zero', () => {

  expect(() => divide(10, 0)).toThrow('Cannot divide by zero');

});

4. Running Tests with Coverage

Jest can generate a code coverage report showing how much of your code is exercised by tests. This helps identify untested or dead code.

npx jest --coverage

Output

File            | % Stmts | % Branch | % Funcs | % Lines 

----------------|---------|----------|---------|---------

all files       | 95.45   | 90.91    | 85.71   | 94.44

Note: Ensure coverage is high across branches, statements, and functions for reliability.

Conclusion

Performing Node.js unit testing using Jest ensures a robust, efficient, and streamlined testing process. With its powerful features like mocking, snapshot testing, and built-in assertions, Jest simplifies the validation of individual components and their interactions.

Its seamless integration with Node.js enables developers to identify and fix issues early, ensuring reliable and maintainable code. By leveraging Jest for unit testing, teams can enhance code quality, boost development productivity, and deliver a stable application experience.

Elevate your Node.js testing strategy with BrowserStack Automate. It enables smooth cross-browser and device testing in real environments, ensuring reliable and comprehensive test coverage.

Also, enhance your testing pipeline with Test Observability, which provides deep insights into debugging, optimizing, and maintaining high-quality tests. This ensures stability and efficiency in your Node.js unit testing workflow with Jest.

Start Testing on BrowserStack

Frequently Asked Questions

1. What is the best unit test framework for node JS?

The best unit test framework for Node.js depends on your project size, style, and requirements, but Jest is widely considered for most Node.js projects.

2. What is the difference between unit test and integration test in node JS?

In Node.js, unit tests test individual modules or functions in isolation (e.g., a utility function). In contrast, integration tests check how multiple modules (like a service, database, and API) interact together in the application.

Useful Resources for Jest

Tags
Automation Testing Unit Testing

Get answers on our Discord Community

Join our Discord community to connect with others! Get your questions answered and stay informed.

Join Discord Community
Discord