Unit Testing with Mocha.js and Chai.js (part 1 - basics)

With the growth in digitalization, the requirements of a user and type of applications one uses daily on web has become more and more complex. So has become the development, testing, maintenance for such applications. Removing bugs and making sure that removing the bugs in one part of the application doesn't affects the other parts is really a tedious and prudent job.

So to overcome this bizzare/cumbersome situations, we can take the help of Unit Testing aka automated testing/verification of a block of code to ensure that the piece of code is working reliably as per expectations. Unit Testing not only solves the above issue but also :-

  1. Encourages to write modular code which enhances low coupling aka less dependence.
  2. Helps a developer to get clear overview of the feature he/she is developing as a test case is more or less a reflection of your requirement.
  3. Gives assurity that your software is verified programatically, almost demolishing the needs for manual testing which further gives rise to various other issues.

So today, through this post I will cover the unit testing with a library Mocha.js, which is really easy to setup and use ofcourse.

##Environment setup ###npm (Node Package Manager) Install npm following instructions here how to install npm.

###mocha Install with npm globally: $ npm install --global mocha

##Create a basic project Create a new directory called test_basics. In the command prompt, navigate to the directory and initialize a new project using following command which will create a new package.json file for our program. npm init

You will be prompted to enter the package name, version, description, and other common package details. We can enter the name test_basics, and continue along pressing ENTER. When you reach test command, type mocha, which is the testing framework we will be using.

test command: mocha

Continue entering the defaults until the walkthrough is complete. The script will create a package.json file that looks like this:

{
  "name": "test_basics",
  "version": "1.0.0",
  "description": "writing example tests",
  "main": "index.js",
  "scripts": {
    "test": "mocha"
  },
  "author": "",
  "license": "ISC"
}

install chai.js as development dependency, which is our assertion library of choice.

npm install --save chai

Now create a new file add.js in the directory with the following content

const add = (num1, num2) => {
  if (!num1) {
    return num2;
  } else if (!num2) {
    return num1;
  }
  return num1 + num2;
};

module.exports = {
  add
};

So finally we are ready to write the tests.

Thinking what to Test

Before I give the exact code, thinking what to test is another dilemma which most developers (including me) faces. So for that I try to stick to basics :-

NOTE : Module here can be anything a function/class/file etc.

  1. Think about what are all the use cases of your module ?
  2. What part of the module, if broken, can gives issues ?

So while thinking of these 2 points, one can get enough test cases to cover for the module which ensures the dignity/correctness of the module.

Writing Tests

So now is the fun part, the actual code part for the unit tests.

//const assert = require('assert');
const expect = require('chai').expect;
const myFunctions = require('./add.js');
const { add } = myFunctions;

1. // Wrap your module you wanna test with describe block
describe('myFunctions', function() {

  describe('add', function() {

    2. // it block describes the purpose of test
    it('should give me sum of 2 numbers', function() {
      // assert.equal(4, add(2, 2));

      3. // Testing for affirmation of results.
      expect(add(2, 2)).to.equal(4);
    });

    it('should return first num, when both the numbers are not present', function() {
      // assert.equal(4, add(4, ''));
      expect(add(4, '')).to.equal(4);
    });

    it('should return second num, when both the first is not present', function() {
      // assert.equal(5, add('', 5));
      expect(add('', 5)).to.equal(5);
    });
  });
});

As I have explained the basic process of tests in the comments itself. Just reiterating, we generally wrap our code module inside of the describe block and then uses it block to explain the purpose of our tests. Inside of it block we write assertion code to verify the expected results we got from the code with the actual results we get.

We can use the native module (assert) of Node.js for asserting the data, but I stick with chai.js as it offers better readability and also there are not much reasons to prefer one assertion library over the other, so feel free to use any.

For next part of this series, I will try to cover more advanced cases with asynchronous code testing. Stay tuned for it.