Resource Center  >  Blog

Mocha Testing: 4 Key Features and a Quick Tutorial

September 14, 2022
Nedim Maric

What is Mocha Testing Framework?

Mocha.js is an open source JavaScript unit testing framework that runs in Node.js and executes tests directly in the browser. Mocha supports most assertion libraries, but is typically used in conjunction with Chai for Node.js. 

Its key capabilities include:

  • Ability to test synchronous and asynchronous code with a simple interface.
  • Flexible and accurate reporting
  • Ability to run tests sequentially while detecting uncaught exceptions and mapping them to test cases.
  • Ability to run functions in a specific order and log the results to a terminal window.
  • Automatically cleaning software state so test cases run independently of each other.

In this article:

4 Mocha Features and Functions

1. Configuring Mocha

You can configure Mocha using configuration files in several formats:

  • JavaScript—you can create a .mocharc.js file in your project directory and export an object with your configuration using module.exports.
  • JSON—you can create a .mocharc.json file in your project directory. Mocha allows adding comments in this file, even though they are normally not valid in JSON.
  • YAML—you can create a .mocharc.yaml file with your configuration in your project directory.
  • package.json—you can provide Mocha configuration by adding a mocha property to your package.json manifest.

2. Mocha Hooks

Mocha lets you set up code that defines preconditions for a test, and code that automatically cleans up after your tests. You can do this using synchronous or asynchronous hooks. The most commonly used hooks in Mocha are: before(), after(), beforeEach(), and afterEach().

The basic syntax for Mocha hooks looks like this. You provide an optional description and a function to run at a specified time during the test lifecycle.

before("hook description", function () {
   // runs once before the first test in the block

after("hook description", function () {
// runs once after the last test in the block

3. Mocha Test Features

Mocha lets you specify in which circumstances tests should or should not be executed. There are three ways to do this:

  • Exclusive tests—append .only() to a function to run only the specified suite or test case.
  • Inclusive tests—append .skip() to a function to ignore certain suites or test cases.
  • Pending tests—test cases that do not have a callback are still included in the test results, but marked as “pending”, to remind the team that someone needs to write these tests. Pending tests are not considered failed. 

4. Mocha Parallel Tests

Mocha provides the –parallel flag, which allows you to run tests in parallel to improve performance. However, there are a few important considerations you should be aware of:

  • Reporter limitations—some reporters do not work when tests are run in parallel, because they need to know in advance how many tests Mocha plans to run (which is not available in parallel mode). In particular, markdown, progress, and json-stream will not work when tests run in parallel. 
  • Exclusive tests not supported—you cannot use .only() when running tests in parallel mode.
  • No guarantee on test order—when running in parallel, Mocha does not guarantee the order in which tests run, and which worker will process them. Options like -file, -sort, and -delay will therefore not work.
  • Test duration—when you run tests in parallel, it might take more time to perform certain operations, and typically more time will be needed to run individual tests.

Related content: Read our guide to cypress testing.

Mocha Tutorial: Unit Testing with Mocha and Chai

Chai is an assertion library that comes in handy when unit testing with Mocha. Tests can use functions from Chai to check the expected output of functions against what it is currently returning.

Installing Node.js and Mocha

To install Node.js and Mocha on the machine:

  1. Download and install Node.js with the package manager npm from this official link.
  2. Check for successful installation of Node.js and npm through the following command. It shows the installed versions of both technologies.

node -v
npm -v

  1. Use npm to install Mocha and Chai through the following command. The –save-dev flag installs required dependencies of the libraries.

npm install mocha --save-dev
npm install chai --save-dev

Setting Up Test Files And Folders

To create and organize test files:

  1. Create a dedicated folder called /tests in the project’s root directory. This folder will contain all the test module files and code functions.
  2. The main codebase files should be in the project’s root directory. This tutorial creates a demo multiplication function for testing purposes, shown below. This function is in a file called multiply.js.

function multiply(number_1, number_2){
    return number_1 + number_2;

  1. Create your tests in the /tests directory. The tutorial uses a sample test function in a file named multiplyTest.js that tests the demo multiplication function.

var assert_function = chai.assert;
describe("multiply", function() {
  it("multiplies numbers", function() {
       assert_function.equal(multiply(6, 3), 18);

The assertion here specifies what inputs to pass for multiplication and what output to check for.

Related content: Read our guide to junit testing.

Running Tests

To run your tests and see results on a test page:

  1. Create an HTML page where you can run tests and see the outcome through a browser. Code for a sample test page is shown below.

<!DOCTYPE html>
    <title>Demo Testing Page With Mocha</title>
    <link rel="stylesheet" href="node_modules/mocha/mocha.css">
    <div id="mocha_div"></div>
    <script src="node_modules/mocha/mocha.js"></script>
    <script src="node_modules/chai/chai.js"></script>
    <script src="tests/multiplyTest.js"></script>
    <script src="multiply.js"></script>

This HTML page uses Mocha’s provided CSS files. The line runs Mocha and the scripts we have specified. The code with setup() specifies that test functions use the Behavior-Driven Development (BDD) approach. This approach requires naming the function and describing it. Then, the expected behavior of the function is specified for testing.

  1. Put the HTML page code above in a file title testPage.html and place it in the root directory.
  2. Go to a browser and open testPage.html. It will run Mocha, Chai, and the test scripts specified in the HTML code. The outcome on the HTML page is categorized according to test functions.

Note: This tutorial shows sample code that describes how to arrange files and write tests with Mocha and Chai. However, when working on production-level code, one should ensure that their test functions are comprehensive and offer optimal coverage. Always check the expected behavior of the code in different environments and edge cases. 

Security Unit Testing with Bright Security 

Bright is a developer-first Dynamic Application Security Testing (DAST) scanner, the first of its kind to integrate into unit testing, letting you shift security testing even further left. 

You can now start to test every component / function at the speed of unit tests, baking security testing across development and CI/CD pipelines to minimize security and technical debt, by scanning early and often, spearheaded by developers. 

With NO false positives, start trusting your scanner when testing your applications and APIs (SOAP, REST, GraphQL), built for modern technologies and architectures. 

Sign up now for a free account or read our docs to learn more.

Related topics

Understanding the Emerging Threat to Your Applications and APIs In today’s digital-driven world, applications and APIs are the linchpins of

See more

Artificial intelligence (AI) has emerged as a transformative force in today’s business landscape, touching virtually every industry with its disruptive

See more

Laravel is growing and becoming one of, if not the most popular PHP framework present today. In fact, Cloudways ranks

See more

Test Your Web App for 10,000+ Attacks

  • Find & fix vulnerabilities fast
  • Zero false positives
  • Developer friendly
See Our Dynamic Application Security Testing (DAST) in Action
and see how easy AppSec can be
Get Started
Read Bright Security reviews on G2