One of the most used javascript libraries based on Chrome’s V8 JavaScript engine for developing server-side applications is web development is Node.js. Unit testing node js is a software that is used for testing methods where individual units are tested alone. A unit is known as the smallest testable part of the code in an application. Unit testing node js is a task that is carried out by the developers during the development phase of an application.

Unit testing node js

There are many frameworks available in Node.js for running unit tests. Here are some of them.

  • Mocha
  • Jest
  • Jasmine
  • AVA

Also Read: Node.js with typescript: Everything you need to know

Unit testing node js application using these frameworks

1: Mocha

One of the oldest and most used testing frameworks for node applications is Mocha. Also, supports asynchronous operations like promises, callbacks, and async/await. It also is highly extensible and has a customizable framework that supports different assertions and mocking libraries.

It is very easy to install Mocha all you have to do is open the command prompt and then type the command given below.

# Installs globally
npm install mocha -g

# installs in the current directory
npm install mocha --save-dev

How to use Mocha?

If you want to use this framework in your application follow the steps given below.

  • Firstly, open the root folder of your project and then make a new folder called test in it.
  • Then inside the test folder, create a new file and let us call it test.js which will have all the code related to testing.
  • Lastly, all you need to need to do is open package.json and the add the lines of command given below
"scripts": {
"test": "mocha --recursive --exit"
}

Let us give you an example:

// Requiring module
const assert = require('assert');
  
// We can group similar tests inside a describe block
describe("Simple Calculations", () => {
  before(() => {
    console.log( "This part executes once before all tests" );
  });
  
  after(() => {
    console.log( "This part executes once after all tests" );
  });
      
  // We can add nested blocks for different tests
  describe( "Test1", () => {
    beforeEach(() => {
      console.log( "executes before every test" );
    });
      
    it("Is returning 5 when adding 2 + 3", () => {
      assert.equal(2 + 3, 5);
    });
  
    it("Is returning 6 when multiplying 2 * 3", () => {
      assert.equal(2*3, 6);
    });
  });
  
  describe("Test2", () => {
    beforeEach(() => {
      console.log( "executes before every test" );
    });
      
    it("Is returning 4 when adding 2 + 3", () => {
      assert.equal(2 + 3, 4);
    });
  
    it("Is returning 8 when multiplying 2 * 4", () => {
      assert.equal(2*4, 8);
    });
  });
});

Copy the above code and then paste it into the test.js that you have created before. Now run these tests, open the command prompt in the project’s root directory, and type the following command.

npm run test

Out of the code given above:

Unit testing node js

What is Chai?

Chai is often the library that is mostly used along with the Mocha. It is used as TTD (Test Driven Development)/ BDD (Behaviour Driven Development). Chai is an assertion library for Node.js that can be coupled with any testing framework based on JavaScript. Similar to assert.equal() statement in the above code, you can easily use Chai to write tests like English sentences.

To install chai, open your command prompt in the project’s root directory and then type the following command.

npm install chai

Example for Chai:

const expect = require('chai').expect;
  
describe("Testing with chai", () => {
    it("Is returning 4 when adding 2 + 2", () => {
      expect(2 + 2).to.equal(4);
    });
  
    it("Is returning boolean value as true", () => {
      expect(5 == 5).to.be.true;
    });
      
    it("Are both the sentences matching", () => {
      expect("This is working").to.equal('This is working');
    });
 });

Output:

Unit testing node js

2: Jest

Jest is also one of the most famous frameworks which are known for clarity. It is regularly maintained and developed by Facebook. The most important feature of jest is that it is well documented and it supports parallel test running. That is each test will run its own process to maximize the performance. Also, it includes some different features like snapshots, watching, and coverage.

You can easily install Jest through the following command.

npm install --save-dev jest

Note: Jest default action is that it excepts to find all the test files in a folder known as “_tests_” in your root folder.

Example:

describe("Testing with Jest", () => {
  test("Addition", () => {
    const sum = 2 + 3;
    const expectedResult = 5;
    expect(sum).toEqual(expectedResult);
  });
    
  // Jest also allows a test to run multiple
  // times using different values
  test.each([[1, 1, 2], [-1, 1, 0], [3, 2, 6]])(
  'Does %i + %i equals %i', (a, b, expectedResult) => {
    expect(a + b).toBe(expectedResult);
  });
});

Output:

Unit testing node js

3: Jasmine

Jasmine is known to be one of the most powerful testing frameworks and has been around since 2010. Jasmine is a  Behaviour Driven Development(BDD) framework for testing JavaScript code. It is also known for its compatibility and then flexibility with other frameworks like Chai and Sinon. The test files must have a specific suffix (*spec.js).

You can easily install Jasmine using the command given below.

npm install jasmine-node

Example:

describe("Test", function() {
  it("Addition", function() {
    var sum = 2 + 3;
    expect(sum).toEqual(5);
  });
});

4: AVA

AVA is the newest of them all in the list of frameworks here. AVA is also the minimalistic framework that allows you to run your JavaScript tests concurrently. Same as the Jest framework AVA also supports parallel processing and snapshots which makes it relatively fast compared to the other frameworks. The important feature of AVA includes no implicit globals and built-in support for asynchronous functions.

You can install the AVA using the command given below.

npm init ava

Example:

Example:

import test from 'ava';
  
test('Addition', t => {
  t.is(2 + 3, 5);
});

Conclusion:

Here we go then in this blog Unit testing node js. How there are different frameworks for unit testing. Which ones are the best. Hope you find this information useful. Thank you for the read.

Categorized in:

Tagged in: