Skip to content

Commit

Permalink
Remove configuration via 'mocha.opts' (#4175)
Browse files Browse the repository at this point in the history
  • Loading branch information
juergba committed Mar 12, 2020
1 parent 6aeeb33 commit 2f26478
Show file tree
Hide file tree
Showing 18 changed files with 42 additions and 488 deletions.
54 changes: 4 additions & 50 deletions docs/index.md
Expand Up @@ -36,7 +36,6 @@ Mocha is a feature-rich JavaScript test framework running on [Node.js][] and in
- [auto-exit to prevent "hanging" with an active loop](#-exit)
- [easily meta-generate suites](#markdown) & [test-cases](#list)
- [config file support](#-config-path)
- [mocha.opts file support](#-opts-path)
- clickable suite titles to filter test execution
- [node debugger support](#-inspect-inspect-brk-inspect)
- [node native ES modules support](#nodejs-native-esm-support)
Expand Down Expand Up @@ -75,7 +74,6 @@ Mocha is a feature-rich JavaScript test framework running on [Node.js][] and in
- [Running Mocha in the Browser](#running-mocha-in-the-browser)
- [Desktop Notification Support](#desktop-notification-support)
- [Configuring Mocha (Node.js)](#configuring-mocha-nodejs)
- [`mocha.opts`](#mochaopts)
- [The `test/` Directory](#the-test-directory)
- [Error Codes](#error-codes)
- [Editor Plugins](#editor-plugins)
Expand Down Expand Up @@ -865,8 +863,6 @@ Reporting & Output
Configuration
--config Path to config file [string] [default: (nearest rc file)]
--opts Path to `mocha.opts` (DEPRECATED)
[string] [default: "./test/mocha.opts"]
--package Path to package.json for config [string]
File Handling
Expand Down Expand Up @@ -1070,11 +1066,7 @@ By default, Mocha will search for a config file if `--config` is not specified;

### `--opts <path>`

> _Deprecated in v7.0.0._
Specify a path to [`mocha.opts`](#mochaopts).

By default, Mocha looks for a `mocha.opts` in `test/mocha.opts`; use `--no-opts` to suppress this behavior.
> _Removed in v8.0.0. Please use [configuration file](#configuring-mocha-nodejs) instead._
### `--package <path>`

Expand Down Expand Up @@ -1738,16 +1730,14 @@ tests as shown below:

> _New in v6.0.0_
In addition to supporting the deprecated [`mocha.opts`](#mochaopts) run-control format, Mocha now supports configuration files, typical of modern command-line tools, in several formats:
Mocha supports configuration files, typical of modern command-line tools, in several formats:

- **JavaScript**: Create a `.mocharc.js` (or `mocharc.cjs` when using [`"type"="module"`](#nodejs-native-esm-support) in your `package.json`)
in your project's root directory, and export an object (`module.exports = {/* ... */}`) containing your configuration.
- **YAML**: Create a `.mocharc.yaml` (or `.mocharc.yml`) in your project's root directory.
- **JSON**: Create a `.mocharc.json` (or `.mocharc.jsonc`) in your project's root directory. Comments &mdash; while not valid JSON &mdash; are allowed in this file, and will be ignored by Mocha.
- **package.json**: Create a `mocha` property in your project's `package.json`.

Mocha suggests using one of the above strategies for configuration instead of the deprecated `mocha.opts` format.

### Custom Locations

You can specify a custom location for your configuration file with the `--config <path>` option. Mocha will use the file's extension to determine how to parse the file, and will assume JSON if unknown.
Expand All @@ -1770,12 +1760,11 @@ If no custom path was given, and if there are multiple configuration files in th

### Merging

Mocha will also _merge_ any options found in `package.json` _and_ `mocha.opts` into its run-time configuration. In case of conflict, the priority is:
Mocha will also _merge_ any options found in `package.json` into its run-time configuration. In case of conflict, the priority is:

1. Arguments specified on command-line
1. Configuration file (`.mocharc.js`, `.mocharc.yml`, etc.)
1. `mocha` property of `package.json`
1. `mocha.opts`

Options which can safely be repeated (e.g., `--require`) will be _concatenated_, with higher-priorty configuration sources appearing earlier in the list. For example, a `.mocharc.json` containing `"require": "bar"`, coupled with execution of `mocha --require foo`, would cause Mocha to require `foo`, then `bar`, in that order.

Expand All @@ -1790,45 +1779,10 @@ Configurations can inherit from other modules using the `extends` keyword. See [
- For options containing a dash (`-`), the option name can be specified using camelCase.
- Aliases are valid names, e.g., `R` instead of `reporter`.
- Test files can be specified using `spec`, e.g., `"spec": "test/**/*.spec.js"`.
- Flags to `node` are _also_ supported in configuration files, like in `mocha.opts`. Use caution, as these can vary between versions of Node.js!
- Flags to `node` are _also_ supported in configuration files. Use caution, as these can vary between versions of Node.js!

**For more configuration examples, see the [`example/config`][example-mocha-config] directory on GitHub.**

## `mocha.opts`

> _`mocha.opts` file support is DEPRECATED and will be removed from a future version of Mocha. We recommend using a configuration file instead._
Mocha will attempt to load `"./test/mocha.opts"` as a run-control file of sorts.

Beginning-of-line comment support is available; any line _starting_ with a
hash (`#`) symbol will be considered a comment. Blank lines may also be used.
Any other line will be treated as a command-line argument (along with any
associated option value) to be used as a default setting. Settings should be
specified one per line.

The lines in this file are prepended to any actual command-line arguments.
As such, actual command-line arguments will take precedence over the defaults.

For example, suppose you have the following `mocha.opts` file:

```bash
# mocha.opts
--require should
--reporter dot
--ui bdd
```

The settings above will default the reporter to `dot`, require the `should`
library, and use `bdd` as the interface. With this, you may then invoke `mocha`
with additional arguments, here changing the reporter to `list` and setting the
slow threshold to half a second:

```bash
$ mocha --reporter list --slow 500
```

To ignore your `mocha.opts`, use the `--no-opts` option.

## The `test/` Directory

By default, `mocha` looks for the glob `"./test/*.js"`, so you may want to put
Expand Down
1 change: 0 additions & 1 deletion example/config/.mocharc.js
Expand Up @@ -7,7 +7,6 @@
module.exports = {
diff: true,
extension: ['js'],
opts: false,
package: './package.json',
reporter: 'spec',
slow: 75,
Expand Down
1 change: 0 additions & 1 deletion example/config/.mocharc.json
Expand Up @@ -5,7 +5,6 @@
{
"diff": true,
"extension": ["js"],
"opts": false,
"package": "./package.json",
"reporter": "spec",
"slow": 75,
Expand Down
1 change: 0 additions & 1 deletion example/config/.mocharc.jsonc
Expand Up @@ -5,7 +5,6 @@
{
"diff": true,
"extension": ["js"],
"opts": false,
"package": /* 📦 */ "./package.json",
"reporter": /* 📋 */ "spec",
"slow": 75,
Expand Down
1 change: 0 additions & 1 deletion example/config/.mocharc.yml
Expand Up @@ -28,7 +28,6 @@ ignore:
inline-diffs: false
# needs to be used with grep or fgrep
# invert: false
opts: false
recursive: false
reporter: spec
reporter-option:
Expand Down
1 change: 0 additions & 1 deletion lib/cli/config.js
Expand Up @@ -2,7 +2,6 @@

/**
* Responsible for loading / finding Mocha's "rc" files.
* This doesn't have anything to do with `mocha.opts`.
*
* @private
* @module
Expand Down
89 changes: 5 additions & 84 deletions lib/cli/options.js
Expand Up @@ -2,7 +2,7 @@

/**
* Main entry point for handling filesystem-based configuration,
* whether that's `mocha.opts` or a config file or `package.json` or whatever.
* whether that's a config file or `package.json` or whatever.
* @module
*/

Expand All @@ -15,7 +15,6 @@ const mocharc = require('../mocharc.json');
const {list} = require('./run-helpers');
const {loadConfig, findConfig} = require('./config');
const findUp = require('find-up');
const {deprecate} = require('../utils');
const debug = require('debug')('mocha:cli:options');
const {isNodeFlag} = require('./node-flags');

Expand Down Expand Up @@ -143,71 +142,6 @@ const parse = (args = [], defaultValues = {}, ...configObjects) => {
return result.argv;
};

/**
* - Replaces comments with empty strings
* - Replaces escaped spaces (e.g., 'xxx\ yyy') with HTML space
* - Splits on whitespace, creating array of substrings
* - Filters empty string elements from array
* - Replaces any HTML space with space
* @summary Parses options read from run-control file.
* @private
* @param {string} content - Content read from run-control file.
* @returns {string[]} cmdline options (and associated arguments)
* @ignore
*/
const parseMochaOpts = content =>
content
.replace(/^#.*$/gm, '')
.replace(/\\\s/g, '%20')
.split(/\s/)
.filter(Boolean)
.map(value => value.replace(/%20/g, ' '));

/**
* Given filepath in `args.opts`, attempt to load and parse a `mocha.opts` file.
* @param {Object} [args] - Arguments object
* @param {string|boolean} [args.opts] - Filepath to mocha.opts; defaults to whatever's in `mocharc.opts`, or `false` to skip
* @returns {external:yargsParser.Arguments|void} If read, object containing parsed arguments
* @memberof module:lib/cli/options
* @see {@link /#mochaopts|mocha.opts}
* @public
*/
const loadMochaOpts = (args = {}) => {
let result;
let filepath = args.opts;
// /dev/null is backwards compat
if (filepath === false || filepath === '/dev/null') {
return result;
}
filepath = filepath || mocharc.opts;
result = {};
let mochaOpts;
try {
mochaOpts = fs.readFileSync(filepath, 'utf8');
debug(`read ${filepath}`);
} catch (err) {
if (args.opts) {
throw new Error(`Unable to read ${filepath}: ${err}`);
}
// ignore otherwise. we tried
debug(`No mocha.opts found at ${filepath}`);
}

// real args should override `mocha.opts` which should override defaults.
// if there's an exception to catch here, I'm not sure what it is.
// by attaching the `no-opts` arg, we avoid re-parsing of `mocha.opts`.
if (mochaOpts) {
deprecate(
'Configuration via mocha.opts is DEPRECATED and will be removed from a future version of Mocha. Use RC files or package.json instead.'
);
result = parse(parseMochaOpts(mochaOpts));
debug(`${filepath} parsed succesfully`);
}
return result;
};

module.exports.loadMochaOpts = loadMochaOpts;

/**
* Given path to config file in `args.config`, attempt to load & parse config file.
* @param {Object} [args] - Arguments object
Expand Down Expand Up @@ -267,19 +201,18 @@ module.exports.loadPkgRc = loadPkgRc;
* 1. Command-line args
* 2. RC file (`.mocharc.c?js`, `.mocharc.ya?ml`, `mocharc.json`)
* 3. `mocha` prop of `package.json`
* 4. `mocha.opts`
* 5. default configuration (`lib/mocharc.json`)
* 4. default configuration (`lib/mocharc.json`)
*
* If a {@link module:lib/cli/one-and-dones.ONE_AND_DONE_ARGS "one-and-done" option} is present in the `argv` array, no external config files will be read.
* @summary Parses options read from `mocha.opts`, `.mocharc.*` and `package.json`.
* @summary Parses options read from `.mocharc.*` and `package.json`.
* @param {string|string[]} [argv] - Arguments to parse
* @public
* @memberof module:lib/cli/options
* @returns {external:yargsParser.Arguments} Parsed args from everything
*/
const loadOptions = (argv = []) => {
let args = parse(argv);
// short-circuit: look for a flag that would abort loading of mocha.opts
// short-circuit: look for a flag that would abort loading of options
if (
Array.from(ONE_AND_DONE_ARGS).reduce(
(acc, arg) => acc || arg in args,
Expand All @@ -291,7 +224,6 @@ const loadOptions = (argv = []) => {

const rcConfig = loadRc(args);
const pkgConfig = loadPkgRc(args);
const optsConfig = loadMochaOpts(args);

if (rcConfig) {
args.config = false;
Expand All @@ -301,19 +233,8 @@ const loadOptions = (argv = []) => {
args.package = false;
args._ = args._.concat(pkgConfig._ || []);
}
if (optsConfig) {
args.opts = false;
args._ = args._.concat(optsConfig._ || []);
}

args = parse(
args._,
mocharc,
args,
rcConfig || {},
pkgConfig || {},
optsConfig || {}
);
args = parse(args._, mocharc, args, rcConfig || {}, pkgConfig || {});

// recombine positional arguments and "spec"
if (args.spec) {
Expand Down
1 change: 0 additions & 1 deletion lib/cli/run-option-metadata.js
Expand Up @@ -51,7 +51,6 @@ exports.types = {
'config',
'fgrep',
'grep',
'opts',
'package',
'reporter',
'ui',
Expand Down
14 changes: 7 additions & 7 deletions lib/cli/run.js
Expand Up @@ -163,13 +163,6 @@ exports.builder = yargs =>
group: GROUPS.OUTPUT,
hidden: true
},
opts: {
default: defaults.opts,
description: 'Path to `mocha.opts` (DEPRECATED)',
group: GROUPS.CONFIG,
normalize: true,
requiresArg: true
},
package: {
description: 'Path to package.json for config',
group: GROUPS.CONFIG,
Expand Down Expand Up @@ -285,6 +278,13 @@ exports.builder = yargs =>
);
}

if (argv.opts) {
throw createUnsupportedError(
`--opts: configuring Mocha via 'mocha.opts' is DEPRECATED and no longer supported.
Please use a configuration file instead.`
);
}

// load requires first, because it can impact "plugin" validation
handleRequires(argv.require);
validatePlugin(argv, 'reporter', Mocha.reporters);
Expand Down
1 change: 0 additions & 1 deletion lib/mocharc.json
@@ -1,7 +1,6 @@
{
"diff": true,
"extension": ["js", "cjs", "mjs"],
"opts": "./test/mocha.opts",
"package": "./package.json",
"reporter": "spec",
"slow": 75,
Expand Down
11 changes: 1 addition & 10 deletions package-scripts.js
Expand Up @@ -80,8 +80,7 @@ module.exports = {
'test.node.jsapi',
'test.node.requires',
'test.node.reporters',
'test.node.only',
'test.node.opts'
'test.node.only'
].join(' ')}`,
description: 'Run Node.js tests'
},
Expand Down Expand Up @@ -120,14 +119,6 @@ module.exports = {
description: 'Run Node.js integration tests',
hiddenFromHelp: true
},
opts: {
script: test(
'opts',
'--opts test/opts/mocha.opts test/opts/opts.spec.js --no-config'
),
description: 'Run tests concerning mocha.opts',
hiddenFromHelp: true
},
jsapi: {
script: 'node test/jsapi',
description: 'Run Node.js Mocha JavaScript API tests',
Expand Down
1 change: 0 additions & 1 deletion test/integration/fixtures/options/help/test/mocha.opts

This file was deleted.

5 changes: 0 additions & 5 deletions test/integration/fixtures/options/opts.fixture.js

This file was deleted.

0 comments on commit 2f26478

Please sign in to comment.