JavaScript Required

We're sorry, but we doesn't work properly without JavaScript enabled.

Looking for an Expert Software Development Team? Take two weeks Trial! Try Now

Tutorial to Write your Test with Mocha and Chai followed by Test Driven Development (TDD)

Mocha and Chai

Introduction of Test Driven Development (TDD)&Behavior Driven Development:

Test Driven Development (TDD) is one of the major key of Agile development techniques. TDD concept can increase the quality of code, faster the development process, helps to enhance programmer confidence and improve bug detection.

Earlier it was very hard to automate web applications due to lack of testing approaches and supportive tools and frameworks hence developers relied on manual testing only which was so tedious and lengthy process. But now it can be possible to test an entire standalone services and REST API by TDD. Even rich User Interface can also be tested automatically with the help of headless browsers and other most usable browsers as well.

Well, while talking about TDD one more concept which is striking on our mind that is Behavior Driven Development or in short BDD. BDD is based on TDD, it differs from TDD in language, which basically encourages collaboration between product owners and programmers.

In Software Development Life Cycle (SDLC) Testing is one of the major steps that has to be done before the end product is going to be deployed and available for use. A various kind of Software Testing Services is being applied on the product to achieve the quality and confidence, like Unit Testing, Integration Testing, Smoke, Sanity and Regression Testing etc. To achieve this Software Engineers need some framework which can maintain the test suites, run the test scripts and populate the test results.

Mocha and Chai : At a Glance

Mocha is one of the widely used JavaScript test framework which running on Node.js and in the browser. It’s making asynchronous testing simpler. It’s providing accurate test reports and also provides the stack-trace of any uncaught exceptions.

In other hand Chai is an assertion library which can be paired with any JavaScript testing frameworks.

Source code: In this entire article whatever examples we are going to discuss that is available on GitHub repository. Please clone the repository link and follow the below instructions to get better understanding.

Agenda: In this article we will discuss on the below topics.

  • Setup Mocha
  • Understanding a TDD based basic mocha spec
  • Understanding the actual code execution with mocha
  • Brief discussion on Hooks
  • Managing test suite in mocha
  • Getting started with Chai
  • Testing Promises with Chai
  • Mocha Reporter

Prerequisite: Before starting with mocha make sure that your machine should have node and npm installed.

You can install node LTS version from nodejs website and npm will install automatically with node.

To check the versions of installed node and npm, run the below commands.

npm -v // It will return installed npm version node -v // It will return installed node version

Setup to Install Mocha

To install mocha run the below two commands sequentially.

npm install - -global mocha npm install - -save-dev mocha
  • - -global helps to install mocha at global level in your system, that means mocha test can be run from command prompt
  • - -save-dev helps to add mocha as a dependency in package.json file for the perticular project.

Note: Mocha is compatible with Node.js v4 or newer.

Understanding a TDD based basic Mocha Spec

Mocha and Chai
  • assert : ‘assert’ helps to determine the test status. It determines the test failure.
  • describe : ‘describe’ is a function which holds the collection of tests or we could sat test suite. It’s having two parameters, first one is the meaningful name which describe the functionality under the method, and second on is the function which basically contains one or multiple test. A nested ‘describe’ can also be declared.
  • it : ‘it’ is a function, which holds the actual test or test steps that needs to be executed. It’s having two parameters as well, first one is the meaningful name to the test and second one is the function which contains the body or steps of the test.

Step to Execute the Mocha Scripts

  • Download or Clone the project from gitHub
  • Navigate into the project folder via command prompt
  • Run command ‘npm install ‘ to download all the require dependencies
  • Run command ‘npm test’ to run all the test scripts or specs

Note: commands called ‘mocha test’ or only ‘mocha’ can also be use to run the test specs. Those commands along with ‘npm test’ is working as below script is mentioned under ‘package.json’ file.

Mocha and Chai

Once the execution is completed below output displays on the console.

Mocha and Chai

Understanding the actual code execution with mocha

In this section we will discuss about actual code execution with mocha. Where we will see how mocha can perform test execution for various kind of functions in JavaScript.

  • Testing a function with mocha : Every function holds some specific instructions to complete a specific tasks. To test those task, defined function needs to be call from mocha specs along with required input parameters if applicable.

    Snapshot 1, the function which needs to be tested

    Mocha and Chai

    Snapshot 2, mocha test spec to test the function

    Mocha and Chai
  • Testing Asynchronous function using mocha : The basic difference of asynchronous function testing with mocha is that we need tell mocha once the test is completed because of the async nature of the function under test. So, we need to define a callback (i.e. ‘done’) to ‘it()’.
  • In the below example we can see mocha waits for ‘done()’ function to be called to complete the test.

Asynchronus function which needs to be tested

Mocha and Chai

Mocha specs to test asynchronus function

Mocha and Chai

Hooks Understanding:

  • We might need to execute few of our code before or after of the actual business logic validation, in such cases we can invoke mocha’s hooks like ‘before()’, ‘after()’, ‘beforeEach()’, ‘afterEach()’ which are by default BDD – style interfaces.
  • Hooks can be use to set up preconditions and clean up after the test execution
  • It describes each test steps with valid step definitions which is helpful to identify errors quickly.
  • Hooks will run in their order they are defined.
  • Steps defined under ‘before()’ will execute once
  • Steps defined under ‘beforeEach()’ will execute before each and every time when a new test step is about to start executing.
  • Steps defined under ‘afterEach()’ will execute after each and every time when a test step is completes execution.
  • Steps defined under ‘after()’ will execute once

Below example will demonstrate the mocha specs using mocha hooks.

Mocha and Chai

Output of the above spec looks like below

Mocha and Chai

Managing test suite in mocha

In this section we will discuss about test suite management in mocha. Sometime it may require to run only few specific test specs or suite instead of running all at a time or we may want to skip some specific test spec or suites during execution, that can be achieved in mocha. 

Mocha has one exclusive feature called ‘only()’ which basically a function which allows user to specify a suite or test which they wants to test among other . That means instead of running entire test suites or entire test within a suite user can specify which particular test suite or test cases they want to execute by using this ‘only()’ function.

Below example will demonstrate the use of ‘only()

Mocha and Chai

Output of the above mocha specs shows up like below.

Mocha and Chai

Note: From the output we can see mocha consider only those test or suite which has been enabled by ‘only()’. 

Like ‘only()’ mocha has another inclusive feature called ‘skip()’, which is the inverse of ‘only()’. Instead of including test suites or individual test it simply tells to ignore that specific test suite or test case where ‘skip()’ function is appended. 

Below example will demonstrate the use of ‘skip()’ 

Mocha and Chai

Output of the above mocha specs shows up like below.

Mocha and Chai

Note: From the output we can see mocha ignored those test or suite where ‘skip()’ is appended

Getting Started with Chai

At the introduction we have got a sight of Chai assertion library. Here in this section we will talk about several interfaces of Chai, which are ‘Should’, ‘Expect’ and ‘Assert’. Chai provides an expressive and readable style of writing test followed by BDD, which is really helpful to understand the test flow and actual validation point. Let’s understand through examples.

Installation : Before started with the examples Chai needs to be installed into the system. So to install the chai run the below command on command prompt.

“npm install chai” // This command will install chai in the project and add as a dependency

Assertion Style: As per the Chai documentation assertion style divided into two category.

1. Assert

  • Exposed through ‘assert’ interface
  • Provides assert-dot notation
  • Allows you to provide an additional message as last parameter, which will include as error message.

Below example will demonstarte the use of ‘assert

Mocha and Chai

The output of above spec is below

Mocha and Chai

*In case some test is failed then the output will be like below

Mocha and Chai

2. BDD : BDD is the second type of assertion style in chai. BDD style comes in two flavors.

  • Expect : Expect is one of interfaces by which BDD style is exposed in chai. User can chain together natural language assertions.

Below example will demonstrate the use of ‘expect’.

Mocha and Chai

The output of above spec is below

Mocha and Chai

*expect also allows to add arbitrary messages which will be displayed as error message if the test is failed. Refer the example below.

The output of above spec is below

Mocha and Chai

The output of above spec is below

Mocha and Chai
  • Should : ‘Should’ style allows the same assertion as ‘expect’ interface, however it extends each object with a ‘should’ property to the the assertion chain.

Below example will demonstrate the use of ‘should’.

Mocha and Chai

The output of above spec is below

Mocha and Chai
  • Differences : The basic differences between ‘expect’and ‘should’are mentioned below.
    • ‘expect’ requires is just a reference to the ‘expect’ function, whereas with the ‘should’ require, the function is being executed.
    • var expect = require('chai').expect; var should = require('chai').should();
    • The ‘expect’ interface provides a function as a starting point for chaining your language assertions. It works on node.js and in all browsers. Whereas ‘should’  interface extends ‘Object.prototype’  to provide a single letter as the starting point for your language assertions. It works on node.js and in all modern browsers except Internet Explorer.

Testing Promises with Chai :

After testing a asynchronous function with callback here in this section we will talk about testing a promise with chai.

  • Promise is asynchronus is nature. In a simple note, promise is like, let say we are trying to get some value through some code once it is executed but instead of the actual value we are getting something else (i.e. Promise), which says we will get the actual value once it is ready.
  • To test promise we will install one more chai library called ‘chai-as-promised
  • Installation : To install chai-as-promised run the below command.
  • ‘npm install - -save-dev chai-as-promised’ // it will install as dev dependency

Let’s understand through an example:

Mocha and Chai

Output of the following specs is below

Mocha and Chai
  • Mocha Reporter : So in the last section of this article we are going to discuss about the mocha reporters. Mocha is coming with some default reporters which are discussed below.
  • SPEC

    Alias: SPEC, spec (it is the default reporter)

    Mocha and Chai

    Alias: DOT, dot (it displays failure status with ‘!’ and pending status with ‘,’ on the console)

    Mocha and Chai
  • NYAN

    Alias: Nyan, nyan

    Mocha and Chai
  • TAP

    Alian TAP, tap

    Mocha and Chai

    Alias: Landing, landing

    Mocha and Chai
  • LIST

    Alias: List, list (it displays a simple specifications list as test cases pass or fail)

    Mocha and Chai

    Alias: Progress, progress. (It implements a simple progress-bar)

    Mocha and Chai
  • JSON

    Alias: JSON, json (It displays a single large JSON object)

    Mocha and Chai

    Alias: JSONStream, json-stream

    Mocha and Chai
  • MIN

    Alias: Min, min (it displays only the summary on the console)

    Mocha and Chai
  • DOC

    Doc, doc (it outputs a hierarchical HTML body)

    Mocha and Chai

*Note : Apart from these reporters mocha also supports some third party HTML reporters as well, like mochawesome, mocha-junit-reporter etc.


In this article we have discussed about the concept of TDD and BDD along with the examples and we got to know about the mocha test framework along chai. 

In current situation where product quality is the major focus of any type of software development activity there correct testing is very necessary, that can be unit testing or integration or any other type of tests. To staisfy those requirements of testing test framework like mocha can be a very good choice specially when we are trying to implement Test Driven Development. 

So, at the end I wish this article is going to be helpful to you. 

Thank You for your patience!

Go through the What is the Impact of AI and ML in Software Testing Jobs?

Ast Note

Some of our clients