Tutorial testing web application
with Mocha and Chai
get rich reports and analytics

In this guide, we took you through the basics of testing Mocha with Chai on Node.js We also demonstrate how to combine all your tests manual and automated ones under one roof, run them together in mixed runs and generate a rich test report for your JavaScript application.

Olga Sheremeta
Olga Sheremeta

Testing is crazily important for finding bugs, verifying the functionality and improving the general stability of the software. Almost all if not all software vendors test their programs in some way.

One way is to check the program manually to try out all the features to see if everything is working as expected. Another, much better way, is to write automated test script scenarios that run tests. Automation testing is especially helpful in regression testing when a couple of new features are added to the system. Having the test automation set up that can be run with a single command — helps to find bugs a new release introduces. It allows free up time on more priority tasks. Thus, automated testing deals with routine. But there’s also another reason👇

Code covered by auto-tests is easier to modify and improve. It should be organized in such a way that every function has a clearly described task, well-defined input and output. That means perfect application architecture from the beginning.

Sure in real life it’s not always that easy. From the start, it may seem that it takes a lot of time to write automated tests, but it is definitely worth it.

There are a lot of automated test frameworks written in various programming languages. In particular, in the world of JavaScript testingWebdriwerIO, Playwright, Cypress, CodeceptJS, Jest are popular nowadays. But the foundation of some of them – is the Mocha and Chai tandem.

What is Mocha?

Mocha is a feature-rich JavaScript testing framework that runs on Node.js and in the browser. It’s designed to test synchronous and asynchronous code with a very similar syntax. Mocha interface is simple with logging the results in the terminal window. Also Mocha cleans the state of the software being tested to ensure that test cases run independently of each other.

Writing tests with Mocha and Chai

But Mocha is not enough for testing. With Mocha we actually have the environment for making our tests, to verify the result matches the expected result, for given a defined input we need an assertion library. While it can be used with most assertion libraries, Mocha is commonly used with Chai.

Mocha is the program we use to run the tests and Chai.js is a library that we use to write the test assertions.

Using a combination of Mocha and Chai is a great option that provides Living Documentation for the specifications of the features of your products, you may follow through the link and meet implementation Living Docs with our test management.

Moreover, these libraries are suitable for both in-browser and server-side testing.

What is Chai?

As we mention before Chai is a popular assertion library for Node.js and the browser. Chai.js implements three different assertion styles. Which one you choose is just a matter of your preference and project needs. Chai allows the freedom of choosing the style interface we prefer: “should”, “expect” and “assert” are all available.

You can learn more about the assertions and assertion styles Chai provides in the official Chai documentation.

But of course, you can use any assertion library you like, for instance, Expect.js, Should.js and more.

What makes Mocha better JS testing frameworks?

  • Seamlessly integrates with NodeJS. Mocha is a test framework that runs on NodeJS itself. As a result, it makes testing the Node.js apps easy and speedy. Moreover, Mocha has many plugins and extensions to test unique scenarios of front-end frameworks such as Angular. Vue.js, React, Flutter etc.
  • Easy to use and flexible. Provides Mocha’s simple syntax to create descriptive auto-tests. It uses describe a method to group your tests and it method to run your tests. Also, Mocha use with third-party assertions, mocking, before, after, before each, after each hooks, reporting and spying tools. It also provides running automated tests each time the file was changed locally. Eventually, meet the official Docs website shows a long list of great capabilities.
  • Сover needs front-end and back-end testing. Mocha JS does both, including various types of testing Unit testing, e2e testing, RESTful API testing.
  • Various Browser support. Can be used to run test cases seamlessly on all major web browsers and provides many browser-specific methods and options.
  • Variety of reporting options. It provides users with a variety of reporting options like list, progress and JSON, to choose from with default reporter displaying the output based on the hierarchy of test cases.
  • Works in both TDD and BDD environments. Mocha supports both Behaviour Driven Development (BDD) and Test Driven Development (TDD) allowing to write of high-quality test cases and enhancing test coverage.
  • Living Documentation or Tests As Docs – the titles of describe and it tell what the function does. It is efficient as possible in a way it achieves relevant goals and reduces risks in agile software development projects.
  • Have a great support community as open-source testing tool.

Is Mocha a BDD tool?

Mocha provides several interfaces for writing tests, BDD interface is the default.

The main sense of BDD (Behaviour Driven Development) is that BDD calls for writing test cases in a shared Gherkin language, which simplifies communication between technical and nontechnical stakeholders like developers, QA teams, and business leaders.

BDD is three things in one: tests, documentation and examples.

Examples (acceptance tests) explain and illustrate the rules. These examples can become tests (manual or automation code) and they document the use cases. When you have some complex scenarios, it can be hard to have discussions based on them. Examples are a lightweight form of describing the test scenario. Example mapping fits better for collaborative Tree Amigos discussion session.

To better understand BDD, we’ll examine a practical case of development. The code below demonstrates what a test suite defined using the BDD Mocha interface looks like:

// begin a test suite of one or more tests
describe('#sum()', function() {

  // add a test hook
  beforeEach(function() {
    // ...some logic before each test is run
  })

  // test a functionality
  it('should add numbers', function() {
    // add an assertion
    expect(sum(1, 2, 3, 4, 5)).to.equal(15);
  })

  // ...some more tests

})

Mocha produces the cleanest tests. In our test case, we’re describing the function of the sum

describe("title", function() { ... })

In the title of it we in a human-readable way describe the particular use case, and the second argument is a function that tests it. The code inside the it block, if the implementation is correct, should execute without errors.

it("use case description", function() { ... })

it should not be called more than once within an it()function block. Calling it multiple times will throw an error.

Functions expect.* are used to check whether  sum works as expected. Right here we’re using one of them – expect.to.equal, it compares arguments and yields an error if they are not equal. Here it checks that the result of sum(1, 2, 3, 4, 5) equals 15. There are other types of comparisons and checks as well.

expect.equal(value1, value2, value3, value4, value5)

Thus, this statement can be executed and it will run the test specified in the block.

In the future, we can add more it and describe We can set up before/after functions that execute before or after running tests and also  beforeEach  afterEach functions that execute it.

How does Mocha BDD Test Flow works:

The testing flow of our example of test case:

  1. Initial spec file and write tests for the required software functionality.
  2. Run tests for the software functionality. While the software functionality is not complete, errors are displayed.
  3. Implementation of the program functionality.
  4. Adding more use cases to the spec, probably not yet supported by the implementations. Tests start to fail.
  5. Fixing bugs and code refactoring until all tests give no errors.
  6. Repeat the cycle for any new functionality to be ready.

So, the SDLC (Software Development Lyfe Cycle) is iterative. QAs write the spec, implement it, make sure tests pass, then write more tests, make sure they work etc. In the end, we have both a working implementation of the current release.

Getting started first test with Mocha

In this part of our comprehensive tutorial, we will demonstrate how to launch the Mocha and Chai test framework, including writing the first test script and executing it with generating the rich test result report.

We will assume that you already have Node.js and npm installed. If you do not please download and install them before continuing. You can find them on the official Node.js website.

Check for successful installation and npm version through the following command. It shows the installed versions of both technologies.

node -v
npm -v

After then you will need to install Mocha either globally on your local machine or as a dependency for your project. The –save-dev flag installs the required dependencies of the libraries. You can do so with the respective codes below:

npm i --global mocha
npm i --save-dev mocha

Install Chai as a development dependency for your project as follows:

npm i --save-dev chai

In the directory of your project file using the following command create the package.json file:

npm init -y

Inside package.json, inside scripts, change the value of the test to mocha.

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

Go ahead and create this directory in your project root: It will output analytics information about the tests as well as generate a comprehensive report. Mocha automatically looks for tests inside the test directory of your project.

At the moment, we have everything set up for running our tests with Mocha, but we don’t have any tests to run yet. Let’s complete the Mocha test framework, you have to write the test for very simple functionality. So, add the following basic Mocha string of test to your test.js file:

import { expect } from 'chai';
import C from '../src/Calculator';

describe('calculate', function() {
  it('add', function() {
    let result = C.Sum(5, 2);
    expect(result).equal(7);
  });

  it('substract', function() {
    let result = C.Difference(5, 2);
    expect(result).equal(3);
  });
});

Allows the use of a variety of reporters and customization. Go ahead and create this directory in your project root: It will output analytics information about the tests as well as generate a comprehensive report.

Let’s run the test and see if it works! Do so by typing which works as a drop-in replacement for the mocha command.

npm run test

With Mocha, developers have a choice from multiple built-in test reporters.

Sync Mocha and Chai Tests With Manual Testing

If you already have auto-tests written with Mocha you can synchronize them with your manual tests and keep under the control running of all your tests. Let’s look at how it is in action.

Mocha and Chai Automated tests and Manual testing synchronization scheme

Launch Mocha and Chai report From Example

Our team prepared a bunch of Demo projects for success starting with the testomat.io TCMS. Besides WebdriverIO following through the link, you can find Cypress, Playwright, Cucumber, Jest, CodeceptJS and other examples of testing frameworks. Download the needed project there and try how it works by yourself.

A team consisting of testers and specialists without QA (BA, PM) experience can work in our TMS. If necessary, the product owner is also involved in the project. You just need to take a few simple steps to provide a foundation for teamwork.

Steps you need to follow to run the example on testomat.io test management:

#1: Create A New Mocha Test Project

When you Sign in to the TMS, you can find out two options for creating a project:

  • Classical Cypress project: test descriptions are presented in the markdown format
  • BDD Cypress project: tests are presented in Gherkin format


Once you make your choice — write the project title and easily create a new project with the Create button.

#2: Import Mocha Automated Tests Into TMS

As soon as you create a project, you will be able to import automated tests by selecting the appropriate menu on the test management interface.


Select the Mocha testing framework and a combination of JavaScript or TypeScript programming languages suitable to your project.


After then copy the generated by the test management app command with the API key and execute it in CMD. This will start importing tests from the source code into the test management system.


Look at the CMD, test management importer in this process analyzes code accurately and displays the number of found tests in the test framework

Go back to your project and look at the number of tests found. If necessary, you will be able to click on the desired test to view the steps it contains.

#3 How Do I Create Mocha Report?

To get a detailed report of the test results, you should first install testomat.io Reporter in the repository. To do this, copy and paste the following command into CMD:

#5 Execute Automated Mocha Scripts

As a result, you will have access to a real-time status report before the test run is completed. If something goes wrong, you can view the execution trace, analyze test scenarios, and examine the attachments to clearly understand the problem.

Once testing is complete, a link to the full report will be generated, which can be shared with stakeholders as needed.

Running Mocha Tests On CI\CD

Until this point, we locally tested the Node.js application, and this can be automated through a CI server. We at testomat.io implemented seamless integration with popular CI\CD tools, including GitHub, GitLab, Jenkins, Bamboo, and CircleCI.

Moreover, you do not need any complicated settings, such as only to establish the connection of the test management system with your CI\CD environment. The tests will be launched on CI\CD directly from the test management system.

Jest Playwright Mocha
Open-source tool Open-source tool Open-source tool
Supports JavaScript/TypeScript/ Angular/Vue/NodeJS Supports JavaScript/TypeScript/ Python/Java/ .NET Supports JavaScript/TypeScript
Chrome/Firefox/Safari//Internet Explorer/Opera are supported browsers Chrome /Microsoft Edge/Apple Safari/Mozilla Firefox are supported browsers Any browser is supported
Windows/Linux/macOS Windows/Linux/macOS Windows/Linux/macOS
Unit testing, snapshot testing Cross-browser testing, E2E testing, web testing, mobile testing, API testing, parallel testing, snapshot testing, unit testing Unit testing, integration testing, end-to-end testing
Strong community and active support Actively developing community Low community support

Jest has fewer features than Mocha and doesn’t support some valuable things like asynchronous tests.

Hopefully you now have a better idea of the differences among these three popular frameworks. As I mentioned, regardless of which framework you choose, all three are mature and effective choices and can work for you, depending on the need of your project and your preferences. Now you’re ready to get testing!

Accelerate App Testing
With centralized web-based test automation Agile, DevOps and CI\CD management solution ⚙️
Follow us