Sunday, 24 February 2019

How to write Mocha and Chai unit tests for your Node.js app?

Background

Testing is an important part of the development lifecycle. Testing can be of many types - unit testing, integration testing, manual testing, QA automation testing. In this tutorial, I am going to show how you can write unit tests for your Node.js application using Mocha and Chai frameworks.  

Mocha is a javascript test framework and Chai is an assertion library. 

Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun. Mocha tests run serially, allowing for flexible and accurate reporting while mapping uncaught exceptions to the correct test cases.

Chai is a BDD / TDD assertion library for node and the browser that can be delightfully paired with any javascript testing framework.


Sample Node.js App

Let's start by writing a simple Node.js app that does addition and subtraction and then we will see how we can write tests for it using Mocha and Chai.

Create a directory called mochatest and navigate to that directory using the following commands -
  • mkdir mochatest
  • cd mochatest
Now initialize it as npm module using -
  • npm init -y



You can see the package.json content initialized with default values. Now let's install our dependencies - mocha, and chai. Execute following command -

  • npm install mocha chai --save-dev
Notice we are saving it as dev dependency and not actual dependency since we need this for testing only.




This should create a node_module directory in your current mochatest directory and install your dependencies there. You can also see dependencies added in package.json.



Now let's create our main app. You can see in the package.json above the main file is called index.js. At this point, I would request you to open your application in your favorite IDE. I will be using visual studio code for this. 

Now create a file called index.js in mochatest folder. and add the following content to it


var addition = function(a,b) {
    return a + b;
}
var subtraction = function(a,b) {
    return a - b;
}


module.exports = {
    add: addition,
    subtract: subtraction
}

This essentially exports 2 functions -
  • add 
  • subtract
that does exactly what the name says - adds and subtracts two numbers. Now let's see how we can write mocha tests for these.


How to write Mocha and Chai unit tests for your Node.js app?

In the mochatest folder create a folder called test. We will have test files in this folder. It is recommended to have same file structure as your actual app. Since we just have a single file called index.js in our app, create a file called indexTest.js in your test folder and add following content to it.


const assert = require('chai').assert;
const index = require("../index");

describe("Index Tests", function(){

    describe("Addition", function(){
        it("Addition functionality test", function() {
            let result = index.add(4,5);
            assert.equal(result,9);
        });
        it("Addition return type test", function() {
            let result = index.add(4,5);
            assert.typeOf(result,'number');
        });
    });

    describe("Subtraction", function(){
        it("Subtraction functionality test", function() {
            let result = index.subtract(5,4);
            assert.equal(result,1);
        });
        it("Subtraction return type test", function() {
            let result = index.subtract(5,4);
            assert.typeOf(result,'number');
        });
    });   

});

Let me explain this before we go and test this out. Like I mentioned before chai is an assertion library, so we get a reference to it. Then you get a reference to the actual app file - index.js. Remember it exports two functions -

  • add
  • subtract
Then we have "describe" keyword. Each describe is a logical grouping of tests and you can cascade them further. For example in the above case, we start a grouping on the basis if file meaning these group has tests for file index.js. Inside it, we have cascaded describe for each method - add and subtract. Each "describe" takes 2 arguments - 1st one is the string that defines what the grouping is for and the 2nd one is the function that has the logic of what that group does. It could have other subgroups as you see above.

Inside describe you can define actual tests inside "it" method. This method also takes 2 arguments - 1st one says what the test does and the 2nd one is a function that gets executed to test it. Inside it we use the assert reference we got from chai module. In this case, we have used
  • equal
  • typeof
You can see others in https://www.chaijs.com/guide/styles/



NOTE: By default, mocha looks for the glob "./test/*.js", so you may want to put your test methods in test/ folder.

Now let's run it. Use the following command -


  • mocha




And you can see the results. You can change the logic in index.js to see that tests fail. For example, lets change add method to return a-b instead of a+b and rerun this test. You will see the following output -


Finally, let's plug this in the npm system. package.json already has test script as follows -

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },


change this to


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


and you can simply run following command to execute tests -

  • npm run test



Let me know if you have any questions. Thanks.


Related Links



t> UA-39527780-1 back to top