Unit Testing in Node.js: The Basics and a Quick Tutorial

Oliver Moradov

What is Unit Testing in Node.js?

Node.js is a popular JavaScript library based on Chrome’s V8 JavaScript engine. It is used to develop server-side components of web applications.

Unit testing is a software testing method that tests individual units/components individually. A unit can be described as the smallest piece of code that can be tested in an application. Unit tests are typically performed by developers during the application development phase.

To do unit testing in Node.js, you will typically use a JavaScript unit testing framework. Common frameworks include Mocha, Jest, Jasmine, and Cypress. We’ll show how to do Node.js unit testing in Jest.

Related content: Read our guide to unit testing in Javascript

In this article:

Why Is Unit Testing Important?

In Node.js, like in other programming languages, unit tests can help you ensure that your program works as expected, identify bugs early in the development process, and improve the stability of your software. Good testing ensures your program meets user requirements and maintains high code quality as development progresses.

A major benefit of unit tests is that they can help you catch regressions. A regression is a new change to the codebase that causes problems with pre-existing code or functionality. Without unit tests, to catch regressions you would have to comprehensively test the entire application every time it changes, which is very difficult to do. A comprehensive set of unit tests, run  automatically every time your codebase changes, is highly effective at catching regressions.

How to Choose a Node.js Testing Framework

There are many JavaScript testing frameworks. Here are a few things you should look when evaluating a Node.js testing framework for your project:

  • Setup time—the framework should require minimal effort to get your tests up and running.
  • Support—the framework should have comprehensive documentation and an active community to support you if there are issues.
  • Feature set—ensure the framework has advanced unit testing features such as mocking/stubbing, matchers (functions that test the relation between objects), and spiers (which gather execution information unavailable to the test code).
  • Performance—unit tests need to run fast, otherwise they will interrupt your development process and reduce productivity. Ensure your framework can run your unit tests quickly.
  • Reporting—the framework should have reporting of test coverage and execution results. If your organization needs customized reporting, check if the framework provides it.
  • Integration—test libraries should be easy to integrate into your continuous integration (CI) process. Preferably, your CI system should support the framework out of the box.

Related content: Read our guide to unit testing frameworks

Quick Tutorial: Node.js Unit Testing with Jest

Jest is a popular framework for unit-testing Node.js applications. It’s popular for its testing functionality that uses parallelism techniques for improved performance. Additionally, it gives an output that shows the piece of code causing failed tests.

Jest requires no configuration except for its installation. Once installed, you can start writing tests and testing your Node.js applications immediately.

Creating a Demo Node.js Application

To create a demo Node.js application for testing:

  1. Use the following commands to create and start a directory for a demo Node.js application.

    mkdir string-multiplier
    cd string-multiplier
    npm -y
  1. Add the following code to a file called index.js in the root folder. 

const http = require('http')
const query_string = require('querystring')
const multiplication = require('./multiplication')

const demo_server = http.createServer(function(request, response) {
  console.dir(request.param)
  if (request.method == 'POST') {
    console.log('POST')
    var request_body = ''
    request.on('data', function(data) {
      request_body += data
    })

    request.on('end', function() {
      const post_request = query_string.parse(request_body)
      const input_numbers = post_request.numbers
     const product = multiplication.multiply(input_numbers)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('Result: ' + product)
    })
  } else {
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Numbers: 
                        <input type="text" name="numbers" />
                        <input type="submit" value="Multiply" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'}
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
demo_server.listen(port, host
console.log(`Listening at http://${host}:${port}`)

This Node.js application will display a form and ask for numbers as input. Next, it will forward the input string it receives to the multiplication function. The application displays the product of comma-separated numbers when the user presses Multiply. Run the following command and go to the address it returns as output to see the HTML page working.

node index.js

  1. This tutorial will test a simple multiplication function. Create a file called multiplication.js and add the function shown below.

    function multiply(numbers) {
        return numbers
            .split(',')
            .map(x => parseInt(x))
            .reduce((a, b) => a * b)
    }

exports.multiply = multiply;

  1. Create a package.json file for this Node.js application and add the following specifications.

    {
    "name": "string-multiplier",
    "version": "1.0.0",
    "description": "",
    "main": "index.js",
    "scripts": {
    "test": "echo \"Error: no tests or frameworks specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC"
    }

Installing the Jest Framework

To download and install Jest:

  1. Navigate to the root directory of your project through the terminal.
  1. Install Jest by running the following command. The --save-dev flag installs all the needed dependencies and the framework itself.

    npm install jest --save-dev
  2. Go to the package.json file also present in the root directory. Replace the line with "test:" with the following code.

    "test": "jest"

Now, npm will run the Jest unit tests whenever you want to test your Node.js application. 

Writing and Running Tests for Node.js Application

To create unit tests for a Node.js application:

  1. Create a separate file for your tests in the project’s folder. A unit test for the multiplication function from the demo Node.js application looks like as shown below. This code is in a file called multiplication.test.js.

    const multiplication = require('./multiplication)

test('string with a single number should result in the number itself', () => {
    expect(multiplication.multiply('1')).toBe(1);
  });

test('string with two numbers should result in the product of the numbers', () => {
    expect(multiplication.multiply('5,5')).toBe(25);
  });

This code is in a file called multiplication.test.js. Here, the code first imports the module it will test. Then, it describes the test by providing a helpful string. Finally, it specifies what inputs to pass and the expected outcome that will determine a successful or failed test.

  1. Navigate to the terminal and use any of the two following commands to run the test:
    • npm test
    • jest

Security Unit Testing with Bright Security 

Bright is a developer-first Dynamic Application Security Testing (DAST) scanner, the first of its kind to integrate into unit testing, letting you shift security testing even further left. 

You can now start to test every component / function at the speed of unit tests, baking security testing across development and CI/CD pipelines to minimize security and technical debt, by scanning early and often, spearheaded by developers. 

With NO false positives, start trusting your scanner when testing your applications and APIs (SOAP, REST, GraphQL), built for modern technologies and architectures. 
Sign up now for a free account or read our docs to learn more.

Secure your app with every build

Sign up for a FREE Bright account.
Related Articles
Categories