DEV Community

Shreyash Pingle
Shreyash Pingle

Posted on

Mocha and Chai Unit Testing (node js)

Let's start by understanding unit testing and why you need to test your code before deploying to production!

_Unit Testing _- It is a form of testing where individual components of the codebase is tested before deploying. To verify that each piece of code in the codebase works properly.

Test-driven development includes writing a particular test before production and checking whether it’s working. The idea is basically to get a little bit of assurance from the initial test.

Behaviour-driven development is a subtopic of test-driven development but instead uses simple and human-readable descriptions of software user requirements as the basis for tests.

There are various tools with which you can perform unit testing in node js.

  1. Mocha js
  2. Chai js
  3. Jest
  4. Enzyme
  5. SinonJS
  6. Cypress

Now let's test our piece of code :

index.html:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Mocha Tests</title>
  <link href="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.css" rel="stylesheet"/>
</head>
<body>
  <div id="mocha"></div>
  <script src="https://cdn.rawgit.com/Automattic/expect.js/0.3.1/index.js"></script>
  <script src="https://cdn.rawgit.com/chaijs/chai/3.5.0/chai.js"></script>
  <script src="https://cdn.rawgit.com/mochajs/mocha/2.2.5/mocha.js"></script>

  <script src="problems.js"></script>
  <script>
    const mocha = window.mocha;
    mocha.setup('bdd');
  </script>
  <script src="tests.js"></script>
  <script>
    mocha.checkLeaks();
    mocha.run();
  </script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

So index.html is just a boilerplate code and few script tags.

Problems.js - where we will write our piece of code

function cube(numberarray){
    const newnumberarray = numberarray.filter(val => val%2!=0);
    return newnumberarray.map(val => val**3);
}

//numberarray=[2,3,4,5,6,7,8]
//newnumberarray=[27,125,343]
Enter fullscreen mode Exit fullscreen mode

Here we have taken an array named numberarray and we are filtering even numbers from numberarray and storing the odd numbers in a new array called newnumberarray & taking the cube of odd numbers stored in newnumberarray
using map function in javascript.

Tests.js

const chai = window.chai;
const assert = chai.assert;
describe("cube", () => {
    it("cube of odd numbers", () => {
        assert(cube([2,3,4,5,6,7,8]),([27,125,343]));
    });
});
Enter fullscreen mode Exit fullscreen mode

here we define describe which takes two arguments "title" and a function.
Then we have defined it which takes 2 arguments "explanation" and a function.
assert is used to compare input and output

so we give an array filter the even numbers and take the cube of odd numbers.

Image description

This is just a basic method which I learned today & I wanted to share it with you guys. Would love any feedbacks!

Top comments (0)