How I use Mocha Js, Chai Js for testing

Monica Danesa
3 min readMar 30, 2018

--

What is Mocha ? Mocha is one feature javascript framework that runs on node js and it could be run on browser too, and how about Chai ? Chai is an assertion library for node. let say Mocha is a framework to describes the test suites and chai is a library to provides all kind assertion result on my javascript test.

Ok, firstly to help understand Mocha and Chai I will write a simple function, and create on one file (Calculator.js)

function plus_calculator(x) {
return result = x+5
}
exports.adding_calculator=adding_calculator;

Nothing a fancy function, but we want to test the function using Mocha and Chai

Setting up the Environment

Navigate to your project folder

Create init and make sure package.json will be generated properly :

npm init

package.json

Let’s start installing mocha globally via terminal :

npm install mocha -g

more information about mocha installation

after installing mocha, we continue installing chai via terminal :

npm install chai

more information about chai installation

The next step after ‘installation’ section is to set up and script into the package.json :

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

So, I can use npm test on your terminal and script on test.js file will run :

Okay, Mocha is running well then let create a sample script test, we are going back to my previous file (Calculator.js/plus_calculator) and let create a simple script on test.js :

var chai = require('chai'),
expect = chai.expect,
asserttype = require('chai-asserttype');
chai.use(asserttype);
var calculator = require('./calculator');describe('add Calculator',function(){
var number = 1;
it('result should be number',function(){
var result = calculator.plus_calculator(number)
expect(result).to.be.number();
}),
it ('should return 6',function(){
var result = calculator.plus_calculator(number)
expect(result).to.equal(6);
})
})

You can see in the script :

  1. Use chai module for testing the expresion.
  2. Expect is one of Bdd (Behaviour Driven Development) style from Chai.
  3. Asserttype is a simple chai plugin for assertions (hence I create test case for checking Number ).
  4. Call calculator file ( for checking plus_calculator function).
  5. Describe is syntax to help us for grouping the test and make the test readable.
  6. The test case consists of two scripts : input should contains a number and the result should return 6

If I try to run this script on terminal, this test will passes with following result :

That’s It! I hope my article can help you to understand of how to set up and use mocha js and chai js for testing.

Happy Testing!!

--

--