Table of contents
1.
Introduction
2.
Implementation
3.
Specifications
3.1.
Custom Locations
3.2.
Ignoring Config Files
3.3.
Priorities
3.4.
Merging
3.5.
Configuring Format
4.
Examples
4.1.
Program
4.2.
Program
5.
FAQs
6.
Key Takeaways
Last Updated: Mar 27, 2024
Easy

Configuring Mocha in Node.js

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Configuration is an integral part of Node.js. It allows you to define a default configuration file that you intend to repeat across environments, then extends the default configuration to other environments, such as development. 

Before v6.0.0, the way you would "configure" Mocha for command-line use was by creating a mocha.opts file. This file had actual command-line flags, which would essentially graft onto the Node.js process.argv array. These flags would then be combined with any user-supplied command-line arguments and passed to the secondary _mocha executable. That was a highly complex and unusual method of configuring a command-line application.

Mocha started supporting configuration files, typical of modern command-line tools with version 6.0.0. Through this article, we will explore the implementation of the Mocha configuration in Node.js in several formats and some examples of the configuration file.

Implementation

Mocha recommends using one of the implementations given below for configuration in the given formats rather than using the legacy mocha.opts format. 

  • JavaScript: You should create a .mocharc.js file in the root directory of your project and then export an object (module.exports = {/* ... */}) that contains your configuration.
  • JSON: You should make a .mocharc.json or .mocharc.jsonc in the root directory of your project. Though comments are not valid JSON, Mocha ignores them and allows them in this file.
  • YAML: You should make a .mocharc.yaml or .mocharc.yml in the root directory of your project.

Specifications

The configuration file in Mocha gives you multiple options and specifications to configure your test suite and project in Node. Here we will explain some options available to the developers in the configuration file.

Custom Locations

You can use the --config <path> option to specify a custom location for your configuration file. Mocha uses the file extension to determine how to parse it and assumes JSON if unknown.

You can also designate a custom package.json location using the --package <path> option.

Ignoring Config Files

You can use the --no-config option to skip looking for configuration files. Similarly, the --no-package will stop Mocha from looking for configuration in a package.json.

Priorities

In case no custom path is given, and there are multiple configuration files in the same directory. Mocha searches for only one file to use for configuration. This search follows a particular priority, which is:

  1. .mocharc.js
  2. .mocharc.yaml
  3. .mocharc.yml
  4. .mocharc.jsonc
  5. .mocharc.json

Merging

Mocha will also merge any options it finds in package.json as well as mocha.opts into its run-time configuration. In case there is a conflict while merging, mocha follows the following priority:

  1. Arguments you specify on the command-line.
  2. Configuration files like .mocharc.js or .mocharc.yml.
  3. The mocha property of the package.json.

Options like –require which can repeat safely, will concatenate, with higher-priority configuration sources appearing earlier in the list. 

For example, a .mocharc.json that contains "require": "bar", coupled with the mocha --require foo execution, will cause Mocha to require foo, then bar, in that order.

Configuring Format

Various configurations in a config file often use different formats. It is advantageous to know such formatting options while configuring Mocha in Node.

  • For example, any "boolean" flag that does not require a parameter, such as --bail, a boolean value can specify.: "bail": true.
  • Any “array”-type option can be a single string value. You can use mocha --help for a list of such options.
  • You can use camelCase for options containing a dash (-) to specify the option name.
  • Aliases like R instead of reporter are valid names.
  • You can specify test files using spec, For example, "spec": "test/**/*.spec.js".
  • Configuration files also support flags to Node. These can differ between versions of Node.js, so use caution.

Examples

Now that we have understood the core concepts behind Configuring Mocha in Node, we can see a few examples of the configuration files in Mocha to understand the implementation better. Below is an example of a .mocharc.json file.

Program

// This config file contains Mocha's defaults.
// You can provide this same configuration in the `mocha` property of your
// project's `package.json`.
{
 "diff": true,
 "extension": ["js", "cjs", "mjs"],
 "package": "./package.json",
 "reporter": "spec",
 "slow": "75",
 "timeout": "2000",
 "ui": "bdd",
 "watch-files": ["lib/**/*.js", "test/**/*.js"],
 "watch-ignore": ["lib/vendor"]
}

 

Here is another similar example of a mocha config file.

Program

{
   "spec": "src/__tests__/**/*.spec.ts",
   "require": "ts-node/register",
   "extension": ["ts"],
   "inline-diffs ": true,
   "full-trace": true,
   "recursive": true,
   "diff": true,
   "exit": true,
   "slow": 300,
   "retries": 3,
   "timeout": 0,
   "ignore": ["node_modules", "dist", "swaggers", "seeds", "migrations", ".devcontainer", ".vscode"]
}

FAQs

1. What is Mocha Reporter?

Ans: Custom Reporters are helpful for user-specific requirements with the test report. Mocha allows you to define and use custom reporters installed with the help of npm. 

For example, suppose mocha-foo-reporter is published to the npm registry. In that case, you could install it using npm install mocha-foo-reporter --save-dev command and then use it with the mocha --reporter mocha-foo-reporter command.

 

2. How can you run a single test file in Mocha?

Ans:  You can easily specify an exact or wildcarded pattern you want to run using the mocha cli. That is done with the help of the grep option when running the mocha command.

For example, if you only want to run a test suite that tests the "api", you can do something like this:

$ mocha --grep api

Although, keep in mind that the spec must contain a describe or it that matches the grep pattern.

describe("api", (_) => {
  // ...
});
You can also try this code with Online Javascript Compiler
Run Code

 

3. What is the difference between the describe and it call in Mocha?

Ans: You can use the it call to identify each test, but by itself, it does not tell Mocha anything about how your test suite is structured. How you implement the describe call gives structure to your test suite. 

 

4. What is the use of the package.json file?

Ans: We use the package.json file to give information to npm that allows it to identify the project and handle the project's dependencies. All npm packages contain this file, usually in the project root, which holds various metadata relevant to the project.

Key Takeaways

In this article, we have extensively discussed Configuring Mocha and its implementation in Node.js. Configuration file support is a vital feature that Mocha introduced in v6.0.0. It gives excellent control to the developer while performing unit tests in the Mocha framework. The specifications and implementations discussed here are just the starting point to configuring Mocha; you will learn to configure your project according to your requirements as you get familiar with working on Mocha.

If you are new to Mocha and Unit Testing in Javascript, be sure to check out our introductory articles like Introduction to MochaMocha Installation and Getting started, and Getting Started with Jest.

We hope that this blog has helped you enhance your knowledge regarding testing using Mocha. 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!

 

Live masterclass