ScanSkill
Sign up for daily dose of tech articles at your inbox.
Loading

Learn About Unit Testing In Node.js Using Jest

Learn About Unit Testing In Node.js Using Jest
Learn About Unit Testing In Node.js Using Jest

Let’s look into unit testing in Node.js using Jest. We will look into writing test cases using the Jest framework for Node.js.

Introduction

Before getting into unit testing using the Jest framework, let’s first know what unit testing is, unit testing is a method for testing small parts of a code, generally a function. It makes it possible that each function and component of a code base are tested in isolation. The main benefits it provides are bugs and errors in code that can be traced and tracked during the application development phase.

In unit testing Jest framework is one of the most popular frameworks used for Node.js. Jest is an open-source testing framework created by Facebook. It is built for testing JavaScript-based applications like Node.js, React, Vue, Angular, etc. The benefits that the Jest framework provides over other libraries are that it is extremely fast, testing takes place in its own sandbox environment, and the testing happens in parallel.

Prerequisites

Unit testing in Node.js using Jest

Let us start the journey of unit testing in node.js using jest. For that create a node project, and install the jest package.

$ mkdir JestTesting

$ cd JestTesting && npm init --y

$ touch index.js

$ code .

Now that a node project is initialized, let’s install the jest package. This npm package is installed as a dev dependency because it is used during the development phase, and is not used in production.

$ npm install --save-dev jest

$ touch index.test.js

So, now that the package is installed let’s create a test script that tests out the code. The file index.test.js is the file where test cases are written. In the script section of package.json file, update the test keys value.

"script": {
  "test": "jest"
}

Now, that the test script is complete, the test will run when the following is put in the terminal.

$ npm test

Now let’s write the code to perform testing in.

//* index.js

const checkOperations = {
  add: function (a, b) {
    return a + b;
  },

  subtract: function (a, b) {
    return a - b;
  },
  multiply: function (a, b) {
    return a * b;
  },
  divide: function (a, b) {
    return a / b;
  },
  compare: function (a, b) {
    return a == b;
  }
};
module.exports = checkOperations;

The above code has all math-related functionality and also now, let us write the test cases in index.test.js.

//* index.test.js

const checkOperations = require("./index");

describe("Operator Tests", () => {
  test("Add two numbers", () => {
    const result = checkOperations.add(1, 5);

    expect(result).toBe(6);
  });

  test("Subtract two numbers", () => {
    const result = checkOperations.subtract(20, 2);

    expect(result).toBe(18);
  });

  test("Multiply two numbers", () => {
    const result = checkOperations.multiply(5, 5);

    expect(result).toBe(25);
  });

  test("Divide two numbers", () => {
    const result = checkOperations.divide(2, 2);

    expect(result).toBe(1);
  });

  test("compare two number", () => {
    const result = checkOperations.compare(15, 15);

    expect(result).toBeTruthy();
  });
});
Unit Testing in Node.js Using Jest
Running test cases

All test cases pass in the above example. Now let’s fail a test case on comparing two numbers. So, now the above code was edited to:

  test("compare two number", () => {
    const result = checkOperations.compare(5, 1);

    expect(result).toBeTruthy();
  });

Failing test case
Failing test case

We see that during the execution of the code the test case fails because 5 is not equal to 1.

After all, function testing our code is condensed into 1 file one testing file.

Our files after test case
Our files after test case

That’s the way Jest runs the code, and we also just looked at toBe() and toBeTruthy(). Where one checks if it is equal to the output received from the result, and the other checks if the output is true respectively. Finally, let’s look into some of the matchers provided by Jest.

Jest Matchers

Jest uses “matchers” to let you test values in different ways. This document will introduce some used matches. So, let’s look at different commonly used matchers provided by the Jest testing framework.

Equality

This is used most commonly. It is used to check equality and non-equality.

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

   // checks equal to
   expect(1*1).toBe(2)

   // checks not equal to
   expect(15*15).not.toBe(225)

 })

Truthiness

This is used to check for false and true data.

test("Thruthiness operators", () => {

	 // Checks if the provided data is true
          expect(true).toBeTruthy()

	 // 1 is also treated as true
         expect(1).toBeTruthy()


	// Checks if the provided is false
          expect(false).toBeFalsy();

	 // 0 is also treated as false
          expect(0).toBeFalsy()

 })

Number

This is used to check arithmetic operations.

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

   // is greater than
   expect(15).toBeGreaterThan(10)

 

   // less than or equal

   expect(-1).toBeLessThanOrEqual(0)

 

   // greater than or equal
   expect(12).toBeGreaterThanOrEqual(0)

 })

String

This is used to check the provided strings against a regular expression.

test("string matchers",() => {
 
   // checks for success match
   expect("Hello World").toMatch(/Hello/)

 

   // checks for failure match
   expect("Hello World").not.toMatch(/scanskill/)

 })

So, they were all the matchers provided by the Jest Framework. One thing to note is that Jest does not test all the cases concurrently, but one by one.

Conclusion

So, in this article, we learned, how to write unit testing in node.js using Jest, and also how it works.

Sign up for daily dose of tech articles at your inbox.
Loading