Mocha — Migrating From mocha.opts to .mocharc.js Configuration File

Mocha supports a variety of configuration options. A typical approach configuring Mocha is the command line. Using Mocha from the CLI or via NPM scripts lets you pass down the desired options.

Mocha supports a dedicated configuration file besides the command line flags. Until Mocha v7, the supported configuration file was mocha.opts. Starting in Mocha v8, you must transition to a mocharc[.js|.json|.yaml] configuration file.

This tutorial shows you how to migrate from a mocha.opts to a .mocharc.js file.

Mocha Series Overview

The Old “mocha.opts” Configuration

The mocha.opts file until Mocha v7 was a list of command-line options. A sample mocha.opts file we’re using in one of our projects looks like this:


--slow 1000
--file ./test/pretest.js

Let’s migrate this file to the new configuration file format.

Translating to a Mocha Configuration File

Moving to a new configuration file is pretty straightforward. You must translate the individual configurations to either a JavaScript object, a JSON object, or to YAML options.

We’ll only look at Mocha’s JavaScript configuration object in this example. Please go ahead and translate it to your used format if you’re not using JavaScript.

Translating the Mocha configurations from above results in the following .mocharc.js file usable in Mocha v8 (and later):


'use strict'

module.exports = {  
  exit: true,
  bail: true,
  slow: 1000,
  recursive: true,
  file: ['./test/pretest.js']

You can basically follow some simple rules here:

  • each option that is only a flag translates to a boolean value
  • each option having a value assigned translates to the value
  • each option allowing more than one value translates to an array of values

That’s it!

Other Configuration Formats

Mocha supports configuration files in JSON and YAML format. If that’s your preference, choose one of those file formats.

You may also use a mocha property in your package.json to configure Mocha. When starting the test run, Mocha checks possible locations for a configuration and merges your custom configuration over the default one.

Enjoy testing!

Additional Resources

Explore the Library

Find interesting tutorials and solutions for your problems.