How To Test An Application Running On Node.js Using Mocha and Chai
Tags: javascript, node, testing, mocha
Published: 2022-11-23 19:34:16

---
title: How To Test An Application Running On Node.js Using Mocha and Chai
published: true
date: 2022-11-23 19:09:00 UTC
tags: #javascript #node #testing #mocha
canonical_url: https://www.thebackendblog.com/2022/11/how-to-test-application-running-on.html
---

## What are Mocha and Chai?

Mocha is a JavaScript test framework used by developers around the world. It's an open-source library that anyone can freely use to create their own setup and playback system for automated and manual testing. Mocha runs tests in a sequence, which delivers flexible and accurate reports. Mocha provides functions that execute in a specific order, logging the results in the terminal.

Before starting with the test topic, it is essential to note that this article is only meant for those familiar with Node.js and its underlying technologies.

In this article, you will learn how to create a test suite from scratch using Mocha and Chai, how to run your tests on the command line, and more.

### Installing mocha using npm

- Using npm
```
npm i --global mocha \\ installing globally  
npm i --save-dev mocha \\ installing as dev dependency

```
- Using yarn

```
yarn add mocha  
yarn install

```

## Writing tests with Mocha

For writing test cases, we need to have a project or code to test. Let's create a node project using npm.

```
npm init

```

### Folder Structure 🗂
<center><a target="_blank" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRayqvF4jCS7JwlaF2yCilQTWgV-qnq7zgwF7xmYyM02sq9daYFcT-afHivs3NWNuWGGCepUv1ho2P6Bte8g195OqVoYmPowu5F0qwRMJNxgUQQxSYXiyBC1_NrAPhqwlqek9A8zBACv7uyWDHhONcBP3UplPoI9boQG9zNEWOGg0uA0yIxfvvJR5p8w/s428/Screenshot%20from%202022-11-23%2022-48-50.png"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669231280118/cRb2v-Mpl.png" alt></a></center>

let's put some sample functions to test in index.js

```
function sum(a, b) {  
  console.log("adding values ", a, " ", b);  
  return a + b;  
}  

function diff(a, b) {  
  console.log("diff between values ", a, " ", b);  
  return a - b;  
}  

function mul(a, b) {  
  console.log("multiplying values ", a, " ", b);  
  return a \* b;  
}  

function div(a, b) {  
  console.log("dividing values ", a, " ", b);  
  return a / b;  
}  

function mod(a, b) {  
  console.log("modulus values ", a, " ", b);  
  return a % b;  
}  

module.exports = {  
  sum: sum,  
  diff: diff,  
  mul: mul,  
  div: div,  
  mod: mod  
};

```

Now we can write our first test for our **index.js** file in the test directory. Mocha tests expect to be placed in the test/.test.js file. Mocha automatically looks for tests inside the test directory of our project.

In the **test/** directory, we will create a file named index.test.js to create a test for our index.js.

For assertions, we need another module called **chai.**

```
npm i --save-dev chai

```
<center>
<a target="_blank" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhQycmVTyqbbq7XU0VmvB_zule7I1cL05-x1pZBn-77e2XFz7GaW9AsDhGt-FG4S3NFex2z65yrYqtw51G7Ni1g6J7AIP9MWzAAJhcpQnxw2mvOweU0mANB5F5kgOslldP6GfyRUDG2oVTg4u_3DJ9GCYa3N0uYYavDcBnTmWisitXZv9l01qZebwAiMg/s1076/Screenshot%20from%202022-11-24%2000-14-15.png"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669231281699/78Eapm_hM.png" alt></a> 
</center>
### writing test 💻 for the index file function

#### index.test.js file

```
const cal = require('../index');  
const expect = require('chai').expect;  

// creating test suite for one or more tests  
describe('testing functions in index.js', function () {  

  // test a functionality  
  it('should add numbers : sum function', function () {  
    let response = cal.sum(1, 2);  
    expect(response).to.equal(3);  
  });  
  it('should diff numbers : diff function', function () {  
    let response = cal.diff(1, 2);  
    expect(response).to.equal(-1);  
  });  
});

```

For running the mocha test. Let's configure package.json for running the mocha test, inside the script field.

```
"scripts": {  
    "test": "mocha"  
  },

```

### Running the test from terminal

```
npm run test

```
<center>
<a target="_blank" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg51fRuihqEz_h_3CZVaJQM-sjVcaI6rvu3gO_Xi7VXCtbiOfZlWKwKT6D70MxXgKe2iMzhyIySdf8xBtCTNrHgQhrBMxSCE1UZUyqRzshcKTuxk-r37_7BIh18RaFqBZYSj8wVUD0lkIS0By4xAbAYi-_RdP_HerkCiXvjLMSaK6Ldnjbk8LDipqXU5A/s729/Screenshot%20from%202022-11-24%2000-29-12.png"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669231283686/4lMs2Mg6R.png" alt></a>
</center>

we run our first test, and everything works fine. but the value of a, and b is hardcoded, we will use the **Math.floor(Math.random() \* 11)** function for generating a and b. For Repeating SetUp we will use the beforeEach hook, Which is used if we have some work we need to do repeatedly for many tests.

```
beforeEach(function () {  
    a = Math.floor(Math.random() \* 11);  
    b = Math.floor(Math.random() \* 11);  
  });

```

## <center> Complete Testing Code </center>

```
const cal = require('../index');  
const expect = require('chai').expect;  

// creating a test suite for one or more tests  
describe('testing functions in index.js', function () {  
  let a;  
  let b;  
  beforeEach(function () {  
    a = Math.floor(Math.random() \* 11);  
    b = Math.floor(Math.random() \* 11);  
  });  
  // test a functionality  
  it('should add numbers : sum function', function () {  
    let response = cal.sum(a, b);  
    expect(response).to.equal(a + b);  
  });  
  it('should diff numbers : diff function', function () {  
    let response = cal.diff(a, b);  
    expect(response).to.equal(a - b);  
  });  
});

```
<center>
<a target="_blank" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhW9fQfp-O44H2qf4pzZTk2j9jxO2ikRoZK_ng0lbUJmE8t9cIh1hnQk4L70Q5roPl32uTzLNtjTj8vxBZzdBdcx4wbLq3bP9LrndViyFG3OHw3L4VRtqenh7Nw25AegPKlE7ctGdEpiik5MjMDJusOwNew65a-qHDkv0E58x6urX7kiSpJNOHU7R-_dQ/s729/Screenshot%20from%202022-11-24%2000-35-14.png"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1669231285493/WyPC9jNzF.png" alt></a>
</center>