Features of Mocha
Mocha is a feature-rich test framework; it comes with a wide range of features allowing us to create illustrative automated tests, robust reports, and even execute our automated tests every time you change a file locally.
In this article, we will discuss some of the most prominent features available in Mocha with the help of examples.
Hooks
Mocha provides several built-in hooks that you can use to set up preconditions and clean up after your tests.
From all the hooks available in the Mocha framework, the four hooks that developers use most commonly are: before(), after(), beforeEach(), and afterEach().
All hooks can be synchronous or asynchronous.
The basic syntax for all four of these hooks is quite similar and looks something like this:
before(name, fn): Optional string for description as the name and a function to run once before the first test case.
In the place of running once before the test, the function runs once after the last test or before/after each test depending on the hook.
Here is a syntax example:
Program:
before("optional description", function () {
// runs once before the first test in this block
});
after("optional description", function () {
// runs once after the last test in this block
});
beforeEach("optional description", function () {
// runs before each test in this block
});
afterEach("optional description", function () {
// runs after each test in this block
});

You can also try this code with Online Javascript Compiler
Run Code
Configuring Mocha
The Mocha framework supports configuration files. Configuration is typical in modern command-line tools in several formats. These include:
- JavaScript: You can create a .mocharc.js (or .mocharc.cjs when using "type"="module" in your package.json) in your project’s root directory, and export an object (module.exports = {/* ... */}) containing your configuration.
- JSON: You can create a .mocharc.json (or .mocharc.jsonc) in your project's root directory. While not valid in JSON, Comments are allowed in this file and will be ignored by Mocha.
- YAML: You can create a .mocharc.yaml (or .mocharc.yml) in your project’s root directory.
- package.json: You can create a mocha property in your project’s package.json.
Asynchronous Code Support
Mocha will know that it should wait for the program to call a function to complete the test by adding an argument (usually naming done) to it() to a test callback. This callback accepts an Error instance (or subclass thereof), a falsy value, or both; anything else is considered invalid usage and throws an error (usually causing a failed test).
Alternatively, you can use the done() callback directly, which handles an error argument if it exists.
Parallel Tests
You can find a significant performance benefit if you run tests in parallel using the --parallel flag, depending on the number and nature of your tests.
For many use cases, parallel tests should work out-of-the-box. However, you must be aware of some crucial implications of using this behavior.
- Reporter Limitations: Due to the nature of reporters like markdown, progress, json-stream, they cannot work while running tests in parallel. These reporters expect Mocha to know how many tests it plans to run before execution, which is unavailable in parallel mode, as Mocha loads test files only when they are about to be run.
- Exclusive Tests are Disallowed: Mocha does not load all files and suites into memory before running tests in parallel mode, so you cannot use it.only, describe.only, this.only(), etc., in parallel mode.
- File Order is Non-Deterministic: Mocha does not guarantee the order in which test files run in parallel, nor which worker process runs them. Because of this, the –file, –sort, and –delay options, which depend on order, cannot be used in parallel mode.
- Test Duration Variability: Running tests in parallel mode naturally uses more system resources. The OS usually takes extra time to schedule and complete some operations depending on system load. For this reason, the timeouts of individual tests may increase either globally or otherwise.
Example
We can finish off this introduction with an example of an elementary Mocha test suite.
Before looking at the test code, we can see the structure of the project.
Program:

You can see that we have placed all of our tests in a test folder in our project directory from where Mocha will automatically search for test suites to run.
You can also see the package.json file which contains our project configurations.
Configuration:
{
"name": "mocha_project",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "mocha"
},
"author": "",
"license": "ISC",
"devDependencies": {
"mocha": "^9.2.1"
},
"dependencies": {
"esm": "^3.2.25"
}
}
Finally, we can write our test code to run in Mocha. This is a very elementary test, which returns -1 if a given value is not present in an array.
Program:
var assert = require("assert");
describe("Array", function () {
describe("#indexOf()", function () {
it("has to return -1 when the value is not present", function () {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});

You can also try this code with Online Javascript Compiler
Run Code
Output:

FAQs
-
What is Mocha and chai?
Mocha is a JavaScript test framework that runs on Node.js and browsers. On the other hand, Chai is a Test Driven Development(TDD) assertion library for NodeJS and the browser. You can easily pair Chai with any javascript testing framework like Mocha.
-
What is describe() in Mocha?
We can nest our tests in groups as deep as we deem necessary in Mocha using describe(). describe() is a straightforward a way to group our tests in Mocha. It takes two arguments, the name of the test group and a callback function as the second argument.
-
What is an Assertion library?
In simple terms, Assertion libraries are tools to verify if given things or conditions are correct. You don't have to use multiple if statements, making testing your code more manageable.
-
What are Integration Tests?
We use Integration tests to verify how functions work together within or across modules. When Mocha runs your test, all the tests within a describe block run under the "integration test" group. For example, you can create a grouping for your integration tests like this:
describe("integration test", function () {
});

You can also try this code with Online Javascript Compiler
Run Code
Key Takeaways
Mocha is a beneficial tool for unit testing, and the feature-rich framework is easy to use and learn. We have scratched the surface when it comes to the features and implementations of the Mocha framework, and there is a lot more to cover in this framework.
But before we move forward, be sure to check out other tools in the spectrum of unit testing with our excellent articles like Getting Started with Jest and JUnit Introduction with Eclipse.
We hope that this blog has helped you enhance your knowledge regarding Unit Testing. If you would like to learn more, head over to our practice platform Coding Ninjas Studio to practice top problems, attempt mock tests, read interview experiences, and much more. Do upvote our blog to help other ninjas grow. Happy Coding!