Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

refactor!: replace yargs with Node.js util.parseArgs (#6164)

Mark Wiemer21a39022861e
diff --git a/lib/cli/cli.js b/lib/cli/cli.js
index f52216fd..1a509137 100755
--- a/lib/cli/cli.js
+++ b/lib/cli/cli.js
@@ -1,26 +1,101 @@
/**
* Contains CLI entry point and public API for programmatic usage in Node.js.
- * - Option parsing is handled by {@link https://npm.im/yargs yargs}.
+ * - Option parsing is handled by {@link module:lib/cli/parse-args}.
* - If executed via `node`, this module will run {@linkcode module:lib/cli.main main()}.
* @public
* @module lib/cli
*/
import debugModule from "debug";
-import yargs from "yargs";
import { fileURLToPath } from "node:url";
-import { loadOptions, YARGS_PARSER_CONFIG } from "./options.cjs";
+import { loadOptions } from "./options.cjs";
import { run, init } from "./commands.js";
import pc from "picocolors";
import { logSymbols } from "../utils.cjs";
import packageJson from "../../package.json" with { type: "json" };
+import { getRunOptionDefinitions } from "./run-option-metadata.cjs";
const __filename = fileURLToPath(import.meta.url);
const debug = debugModule("mocha:cli:cli");
+const hasFlag = (args, longName, shortName) =>
+ args.includes(`--${longName}`) || args.includes(`-${shortName}`);
+
+const formatOption = (option) => {
+ const aliases = option.aliases.map((alias) =>
+ alias.length === 1 ? `-${alias}` : `--${alias}`,
+ );
+ return [`--${option.name}`].concat(aliases).join(", ");
+};
+
+const printVersion = () => {
+ console.log(packageJson.version);
+};
+
+const printHelp = () => {
+ const options = getRunOptionDefinitions()
+ .filter((option) => option.description)
+ .map(
+ (option) => ` ${formatOption(option).padEnd(34)} ${option.description}`,
+ )
+ .join("\n");
+
+ console.log(`Usage: mocha [spec..]
+ mocha init <path>
+
+Commands:
+ init <path> ${init.description}
+
+Options:
+${options}
+ --help, -h${"".padEnd(24)} Show usage information & exit
+ --version, -V${"".padEnd(21)} Show version number & exit
+
+Mocha Resources
+ Chat: ${packageJson.discord}
+ GitHub: ${packageJson.repository.url}
+ Docs: ${packageJson.homepage}`);
+};
+
+const fail = (msg, err) => {
+ debug("caught error before command handler: %O", err);
+ printHelp();
+ console.error(`\n${logSymbols.error} ${pc.red("ERROR:")} ${msg}`);
+ if (!msg && err) {
+ // Log raw error and stack when an unexpected error is encountered, to
+ // make debugging easier (instead of an inactionable "ERROR: null").
+ console.error(err);
+ }
+ process.exit(1);
+};
+
+const failRunPreparation = (err) => {
+ console.error(`\n${logSymbols.error} ${pc.red("ERROR:")}`, err);
+ process.exit(1);
+};
+
+const runCommand = async (args) => {
+ args.spec = args.spec || (args._ && args._.length ? args._ : ["test"]);
+
+ try {
+ run.normalizeRunOptions(args);
+ run.validateRunOptions(args);
+ } catch (err) {
+ fail(err && err.message, err);
+ }
+
+ try {
+ await run.prepareRunOptions(args);
+ } catch (err) {
+ failRunPreparation(err);
+ }
+
+ return run.handler(args);
+};
+
/**
* - Accepts an `Array` of arguments
* - Modifies {@link https://nodejs.org/api/modules.html#modules_module_paths Node.js' search path} for easy loading of consumer modules
@@ -39,43 +114,29 @@ export function main(argv = process.argv.slice(2), mochaArgs) {
debug("unable to set Error.stackTraceLimit = Infinity", err);
}
- const args = mochaArgs ?? loadOptions(argv);
-
- yargs()
- .scriptName("mocha")
- .command(run)
- .command(init)
- .updateStrings({
- "Positionals:": "Positional Arguments",
- "Options:": "Other Options",
- "Commands:": "Commands",
- })
- .fail((msg, err, yargs) => {
- debug("caught error sometime before command handler: %O", err);
- yargs.showHelp();
- console.error(`\n${logSymbols.error} ${pc.red("ERROR:")} ${msg}`);
- if (!msg) {
- // Log raw error and stack when an unexpected error is encountered, to
- // make debugging easier (instead of an inactionable "ERROR: null").
- console.error(err);
- }
- process.exit(1);
- })
- .help("help", "Show usage information & exit")
- .alias("help", "h")
- .version("version", "Show version number & exit", packageJson.version)
- .alias("version", "V")
- .wrap(process.stdout.columns ? Math.min(process.stdout.columns, 80) : 80)
- .epilog(
- `${pc.reset("Mocha Resources")}
- Chat: ${pc.magenta(packageJson.discord)}
- GitHub: ${pc.blue(packageJson.repository.url)}
- Docs: ${pc.yellow(packageJson.homepage)}
- `,
- )
- .parserConfiguration(YARGS_PARSER_CONFIG)
- .config(args)
- .parse(args._);
+ try {
+ const args = mochaArgs ?? loadOptions(argv);
+ if (hasFlag(argv, "help", "h") || args.help || args.h) {
+ printHelp();
+ process.exit(0);
+ }
+
+ if (hasFlag(argv, "version", "V") || args.version || args.V) {
+ printVersion();
+ process.exit(0);
+ }
+
+ const command = (args._ && args._[0]) || argv[0];
+ if (command === "init") {
+ const commandArgs =
+ args._ && args._[0] === "init" ? args._.slice(1) : argv.slice(1);
+ return init.handler(init.parse(commandArgs));
+ }
+
+ return runCommand(args);
+ } catch (err) {
+ fail(err && err.message, err);
+ }
}
// allow direct execution
diff --git a/lib/cli/commands.js b/lib/cli/commands.js
index 549e9b09..5b5d8323 100644
--- a/lib/cli/commands.js
+++ b/lib/cli/commands.js
@@ -1,6 +1,5 @@
/**
- * Exports Yargs commands
- * @see https://github.com/yargs/yargs/blob/main/docs/advanced.md
+ * Exports Mocha CLI commands.
* @private
* @module
*/
diff --git a/lib/cli/init.js b/lib/cli/init.js
index d490f2b8..30df24a9 100644
--- a/lib/cli/init.js
+++ b/lib/cli/init.js
@@ -12,11 +12,13 @@ export const command = "init <path>";
export const description = "create a client-side Mocha setup at <path>";
-export const builder = (yargs) =>
- yargs.positional("path", {
- type: "string",
- normalize: true,
- });
+export const parse = (args) => {
+ const [pathArg] = args;
+ if (!pathArg) {
+ throw new Error("Not enough non-option arguments: got 0, need at least 1");
+ }
+ return { _: [], path: path.normalize(pathArg) };
+};
export const handler = (argv) => {
const destdir = argv.path;
diff --git a/lib/cli/options.cjs b/lib/cli/options.cjs
index f28c1450..48a6663a 100644
--- a/lib/cli/options.cjs
+++ b/lib/cli/options.cjs
@@ -32,18 +32,7 @@ const debug = debugModule("mocha:cli:options");
*/
/**
- * Base yargs parser configuration
- * @private
- */
-const YARGS_PARSER_CONFIG = {
- "combine-arrays": true,
- "short-option-groups": false,
- "dot-notation": false,
- "strip-aliased": true,
-};
-
-/**
- * Wrapper around `parseArgs` which applies our settings
+ * Wrapper around `parseMochaArgs` which applies Mocha's CLI parsing behavior.
* @param {string|string[]} args - Arguments to parse
* @param {Object} defaultValues - Default values of mocharc.json
* @param {...Object} configObjects - Objects to merge into parsed arguments
@@ -68,7 +57,7 @@ const parse = (args = [], defaultValues = {}, ...configObjects) => {
* @param {string|boolean} [args.config] - Path to config file or `false` to skip
* @public
* @alias module:lib/cli.loadRc
- * @returns {external:yargsParser.Arguments|void} Parsed config, or nothing if `args.config` is `false`
+ * @returns {external:parseArgs.Arguments|void} Parsed config, or nothing if `args.config` is `false`
*/
const loadRc = (args = {}) => {
if (args.config !== false) {
@@ -84,7 +73,7 @@ const loadRc = (args = {}) => {
* @param {string|boolean} [args.config] - Path to `package.json` or `false` to use default
* @public
* @alias module:lib/cli.loadPkgRc
- * @returns {external:yargsParser.Arguments|void} Parsed config. Throws if unparsableF. Empty object if file not found.
+ * @returns {external:parseArgs.Arguments|void} Parsed config. Throws if unparsableF. Empty object if file not found.
*/
const loadPkgRc = (args = {}) => {
let result;
@@ -142,7 +131,7 @@ const loadPkgRc = (args = {}) => {
* @param {string|string[]} [argv] - Arguments to parse
* @public
* @alias module:lib/cli.loadOptions
- * @returns {external:yargsParser.Arguments} Parsed args from everything
+ * @returns {external:parseArgs.Arguments} Parsed args from everything
*/
const loadOptions = (argv = []) => {
let args = parse(argv);
@@ -190,7 +179,6 @@ const loadOptions = (argv = []) => {
return args;
};
-exports.YARGS_PARSER_CONFIG = YARGS_PARSER_CONFIG;
exports.loadRc = loadRc;
exports.loadPkgRc = loadPkgRc;
exports.loadOptions = loadOptions;
diff --git a/lib/cli/parse-args.js b/lib/cli/parse-args.js
index f35c133f..c2e165c4 100644
--- a/lib/cli/parse-args.js
+++ b/lib/cli/parse-args.js
@@ -74,6 +74,24 @@ const toArray = (value) => {
// Array-type options should have unique values, with comma-delimited values
// split unless the option is a glob where commas can be part of the pattern.
const coerceArrayOption = (name, value) => {
+ if (
+ name === "reporter-option" &&
+ value &&
+ typeof value === "object" &&
+ !Array.isArray(value)
+ ) {
+ return value;
+ }
+
+ if (
+ name === "reporter-option" &&
+ Array.isArray(value) &&
+ value.every(
+ (item) => item && typeof item === "object" && !Array.isArray(item),
+ )
+ ) {
+ return Object.assign({}, ...value);
+ }
const values = toArray(value);
return Array.from(
new Set(globOptions.includes(name) ? values : list(values)),
diff --git a/lib/cli/run-option-metadata.cjs b/lib/cli/run-option-metadata.cjs
index 6b3bcb4a..c54799bd 100644
--- a/lib/cli/run-option-metadata.cjs
+++ b/lib/cli/run-option-metadata.cjs
@@ -8,7 +8,7 @@
*/
/**
- * Dictionary of yargs option types to list of options having said type
+ * Dictionary of option types to list of options having said type
* @type {Record<string, string[]>}
* @private
*/
@@ -95,6 +95,67 @@ const aliases = {
watch: ["w"],
};
+const descriptions = {
+ "allow-uncaught": "Allow uncaught errors to propagate",
+ "async-only":
+ "Require all tests to use a callback (async) or return a Promise",
+ bail: 'Abort ("bail") after first test failure',
+ "check-leaks": "Check for global variable leaks",
+ color: "Force-enable color output",
+ config: "Path to config file",
+ delay: "Delay initial execution of root suite",
+ diff: "Show diff on failure",
+ "dry-run": "Report tests without executing them",
+ exit: "Force Mocha to quit after tests complete",
+ extension: "File extension(s) to load",
+ "fail-hook-affected-tests":
+ "Report tests as failed when affected by hook failures (before/beforeEach)",
+ "fail-zero": "Fail test run if no test(s) encountered",
+ "pass-on-failing-test-suite": "Not fail test run if tests were failed",
+ fgrep: "Only run tests containing this string",
+ file: "Specify file(s) to be loaded prior to root suite execution",
+ "forbid-only": "Fail if exclusive test(s) encountered",
+ "forbid-pending": "Fail if pending test(s) encountered",
+ "full-trace": "Display full stack traces",
+ global: "List of allowed global variables",
+ grep: "Only run tests matching this string or regexp",
+ ignore: "Ignore file(s) or glob pattern(s)",
+ "inline-diffs":
+ "Display actual/expected differences inline within each string",
+ invert: "Inverts --grep and --fgrep matches",
+ jobs: "Number of concurrent jobs for --parallel; use 1 to run in serial",
+ "list-interfaces": "List built-in user interfaces & exit",
+ "list-reporters": "List built-in reporters & exit",
+ "no-colors": "Force-disable color output",
+ "node-option": 'Node or V8 option (no leading "--")',
+ package: "Path to package.json for config",
+ parallel: "Run tests in parallel",
+ "posix-exit-codes":
+ "Use POSIX and UNIX shell exit codes as Mocha's return value",
+ recursive: "Look for tests in subdirectories",
+ reporter: "Specify reporter to use",
+ "reporter-option": "Reporter-specific options (<k=v,[k1=v1,..]>)",
+ require: "Require module",
+ retries: "Retry failed tests this many times",
+ slow: 'Specify "slow" test threshold (in milliseconds)',
+ sort: "Sort test files",
+ timeout: "Specify test timeout threshold (in milliseconds)",
+ ui: "Specify user interface",
+ watch: "Watch files in the current working directory for changes",
+ "watch-files": "List of paths or globs to watch",
+ "watch-ignore": "List of paths or globs to exclude from watching",
+};
+
+const getRunOptionDefinitions = () =>
+ Object.entries(types).flatMap(([type, names]) =>
+ names.map((name) => ({
+ name,
+ type,
+ aliases: aliases[name] || [],
+ description: descriptions[name] || "",
+ })),
+ );
+
const ALL_MOCHA_FLAGS = Object.keys(types).reduce((acc, key) => {
// gets all flags from each of the fields in `types`, adds those,
// then adds aliases of each flag (if any)
@@ -140,5 +201,6 @@ const expectedTypeForFlag = (flag) => {
exports.types = types;
exports.aliases = aliases;
+exports.getRunOptionDefinitions = getRunOptionDefinitions;
exports.isMochaFlag = isMochaFlag;
exports.expectedTypeForFlag = expectedTypeForFlag;
diff --git a/lib/cli/run.cjs b/lib/cli/run.cjs
index 5e59403b..d872a420 100644
--- a/lib/cli/run.cjs
+++ b/lib/cli/run.cjs
@@ -7,7 +7,6 @@
* @private
*/
-const pc = require("picocolors");
const Mocha = require("../mocha.cjs");
const {
createUnsupportedError,
@@ -21,359 +20,123 @@ const {
validateLegacyPlugin,
runMocha,
} = require("./run-helpers.cjs");
-const { ONE_AND_DONES, ONE_AND_DONE_ARGS } = require("./one-and-dones.js");
+const { ONE_AND_DONES } = require("./one-and-dones.js");
const debug = require("debug")("mocha:cli:run");
-const defaults = require("../mocharc.json");
-const { types, aliases } = require("./run-option-metadata.cjs");
-const { isCI, logSymbols } = require("../utils.cjs");
-
-/**
- * Logical option groups
- * @constant
- */
-const GROUPS = {
- FILES: "File Handling",
- FILTERS: "Test Filters",
- NODEJS: "Node.js & V8",
- OUTPUT: "Reporting & Output",
- RULES: "Rules & Behavior",
- CONFIG: "Configuration",
-};
exports.command = ["$0 [spec..]", "inspect"];
exports.describe = "Run tests with Mocha";
-exports.builder = (yargs) =>
- yargs
- .options({
- "allow-uncaught": {
- description: "Allow uncaught errors to propagate",
- group: GROUPS.RULES,
- },
- "async-only": {
- description:
- "Require all tests to use a callback (async) or return a Promise",
- group: GROUPS.RULES,
- },
- bail: {
- description: 'Abort ("bail") after first test failure',
- group: GROUPS.RULES,
- },
- "check-leaks": {
- description: "Check for global variable leaks",
- group: GROUPS.RULES,
- },
- color: {
- description: "Force-enable color output",
- group: GROUPS.OUTPUT,
- },
- config: {
- config: true,
- defaultDescription: "(nearest rc file)",
- description: "Path to config file",
- group: GROUPS.CONFIG,
- },
- delay: {
- description: "Delay initial execution of root suite",
- group: GROUPS.RULES,
- },
- diff: {
- default: true,
- description: "Show diff on failure",
- group: GROUPS.OUTPUT,
- },
- "dry-run": {
- description: "Report tests without executing them",
- group: GROUPS.RULES,
- },
- exit: {
- description: "Force Mocha to quit after tests complete",
- group: GROUPS.RULES,
- },
- extension: {
- default: defaults.extension,
- description: "File extension(s) to load",
- group: GROUPS.FILES,
- requiresArg: true,
- coerce: list,
- },
- "pass-on-failing-test-suite": {
- default: false,
- description: "Not fail test run if tests were failed",
- group: GROUPS.RULES,
- },
- "fail-hook-affected-tests": {
- description:
- "Report tests as failed when affected by hook failures (before/beforeEach)",
- group: GROUPS.RULES,
- },
- "fail-zero": {
- description: "Fail test run if no test(s) encountered",
- group: GROUPS.RULES,
- },
- fgrep: {
- conflicts: "grep",
- description: "Only run tests containing this string",
- group: GROUPS.FILTERS,
- requiresArg: true,
- },
- file: {
- defaultDescription: "(none)",
- description:
- "Specify file(s) to be loaded prior to root suite execution",
- group: GROUPS.FILES,
- normalize: true,
- requiresArg: true,
- },
- "forbid-only": {
- description: "Fail if exclusive test(s) encountered",
- group: GROUPS.RULES,
- default: isCI(),
- },
- "forbid-pending": {
- description: "Fail if pending test(s) encountered",
- group: GROUPS.RULES,
- },
- "full-trace": {
- description: "Display full stack traces",
- group: GROUPS.OUTPUT,
- },
- global: {
- coerce: list,
- description: "List of allowed global variables",
- group: GROUPS.RULES,
- requiresArg: true,
- },
- grep: {
- coerce: (value) => (!value ? null : value),
- conflicts: "fgrep",
- description: "Only run tests matching this string or regexp",
- group: GROUPS.FILTERS,
- requiresArg: true,
- },
- ignore: {
- defaultDescription: "(none)",
- description: "Ignore file(s) or glob pattern(s)",
- group: GROUPS.FILES,
- requiresArg: true,
- },
- "inline-diffs": {
- description:
- "Display actual/expected differences inline within each string",
- group: GROUPS.OUTPUT,
- },
- invert: {
- description: "Inverts --grep and --fgrep matches",
- group: GROUPS.FILTERS,
- },
- jobs: {
- description:
- "Number of concurrent jobs for --parallel; use 1 to run in serial",
- defaultDescription: "(number of CPU cores - 1)",
- requiresArg: true,
- group: GROUPS.RULES,
- },
- "list-interfaces": {
- conflicts: Array.from(ONE_AND_DONE_ARGS).filter(
- (arg) => arg !== "list-interfaces",
- ),
- description: "List built-in user interfaces & exit",
- },
- "list-reporters": {
- conflicts: Array.from(ONE_AND_DONE_ARGS).filter(
- (arg) => arg !== "list-reporters",
- ),
- description: "List built-in reporters & exit",
- },
- "no-colors": {
- description: "Force-disable color output",
- group: GROUPS.OUTPUT,
- hidden: true,
- },
- "node-option": {
- description: 'Node or V8 option (no leading "--")',
- group: GROUPS.CONFIG,
- },
- package: {
- description: "Path to package.json for config",
- group: GROUPS.CONFIG,
- normalize: true,
- requiresArg: true,
- },
- parallel: {
- description: "Run tests in parallel",
- group: GROUPS.RULES,
- },
- "posix-exit-codes": {
- description:
- "Use POSIX and UNIX shell exit codes as Mocha's return value",
- group: GROUPS.RULES,
- },
- recursive: {
- description: "Look for tests in subdirectories",
- group: GROUPS.FILES,
- },
- reporter: {
- default: defaults.reporter,
- description: "Specify reporter to use",
- group: GROUPS.OUTPUT,
- requiresArg: true,
- },
- "reporter-option": {
- coerce: (opts) =>
- list(opts).reduce((acc, opt) => {
- const pair = opt.split("=");
-
- if (pair.length > 2 || !pair.length) {
- throw createInvalidArgumentValueError(
- `invalid reporter option '${opt}'`,
- "--reporter-option",
- opt,
- 'expected "key=value" format',
- );
- }
-
- acc[pair[0]] = pair.length === 2 ? pair[1] : true;
- return acc;
- }, {}),
- description: "Reporter-specific options (<k=v,[k1=v1,..]>)",
- group: GROUPS.OUTPUT,
- requiresArg: true,
- },
- require: {
- defaultDescription: "(none)",
- description: "Require module",
- group: GROUPS.FILES,
- requiresArg: true,
- },
- retries: {
- description: "Retry failed tests this many times",
- group: GROUPS.RULES,
- },
- slow: {
- default: defaults.slow,
- description: 'Specify "slow" test threshold (in milliseconds)',
- group: GROUPS.RULES,
- },
- sort: {
- description: "Sort test files",
- group: GROUPS.FILES,
- },
- timeout: {
- default: defaults.timeout,
- description: "Specify test timeout threshold (in milliseconds)",
- group: GROUPS.RULES,
- },
- ui: {
- default: defaults.ui,
- description: "Specify user interface",
- group: GROUPS.RULES,
- requiresArg: true,
- },
- watch: {
- description: "Watch files in the current working directory for changes",
- group: GROUPS.FILES,
- },
- "clear-screen": {
- description: "Clear the terminal before each run in watch mode",
- group: GROUPS.OUTPUT,
- },
- "watch-files": {
- description: "List of paths or globs to watch",
- group: GROUPS.FILES,
- requiresArg: true,
- coerce: list,
- },
- "watch-ignore": {
- description: "List of paths or globs to exclude from watching",
- group: GROUPS.FILES,
- requiresArg: true,
- coerce: list,
- default: defaults["watch-ignore"],
- },
- })
- .positional("spec", {
- default: ["test"],
- description: "One or more files, directories, or globs to test",
- type: "array",
- })
- .check((argv) => {
- // "one-and-dones"; let yargs handle help and version
- Object.keys(ONE_AND_DONES).forEach((opt) => {
- if (argv[opt]) {
- ONE_AND_DONES[opt].call(null, yargs);
- process.exit();
- }
+const camelCase = (name) =>
+ name.replace(/-([a-z])/g, (_, char) => char.toUpperCase());
+
+const coerceReporterOption = (opts) =>
+ list(opts).reduce((acc, opt) => {
+ const pair = opt.split("=");
+
+ if (pair.length > 2 || !pair.length) {
+ throw createInvalidArgumentValueError(
+ `invalid reporter option '${opt}'`,
+ "--reporter-option",
+ opt,
+ 'expected "key=value" format',
+ );
+ }
+
+ acc[pair[0]] = pair.length === 2 ? pair[1] : true;
+ return acc;
+ }, {});
+
+const normalizeRunOptions = (argv) => {
+ Object.keys(argv).forEach((name) => {
+ const reporterOptionMatch = name.match(/^reporter-options?\.(.+)$/);
+ if (reporterOptionMatch) {
+ argv["reporter-option"] = Object.assign({}, argv["reporter-option"], {
+ [reporterOptionMatch[1]]: argv[name],
});
+ }
- // yargs.implies() isn't flexible enough to handle this
- if (argv.invert && !("fgrep" in argv || "grep" in argv)) {
- throw createMissingArgumentError(
- '"--invert" requires one of "--fgrep <str>" or "--grep <regexp>"',
- "--fgrep|--grep",
- "string|regexp",
- );
+ if (name.includes("-")) {
+ const normalizedName = camelCase(name);
+ if (!(normalizedName in argv)) {
+ argv[normalizedName] = argv[name];
}
+ }
+ });
- if (argv.parallel) {
- // yargs.conflicts() can't deal with `--file foo.js --no-parallel`, either
- if (argv.file) {
- throw createUnsupportedError(
- "--parallel runs test files in a non-deterministic order, and is mutually exclusive with --file",
- );
- }
+ if (Array.isArray(argv["reporter-option"])) {
+ argv["reporter-option"] = coerceReporterOption(argv["reporter-option"]);
+ }
+};
- // or this
- if (argv.sort) {
- throw createUnsupportedError(
- "--parallel runs test files in a non-deterministic order, and is mutually exclusive with --sort",
- );
- }
+const validateRunOptions = (argv) => {
+ // "one-and-dones"; help and version are handled by the top-level CLI.
+ const oneAndDoneOptions = Object.keys(ONE_AND_DONES).filter((opt) =>
+ Boolean(argv[opt]),
+ );
+ if (oneAndDoneOptions.length > 1) {
+ throw createUnsupportedError(
+ `Arguments ${oneAndDoneOptions.join(" and ")} are mutually exclusive`,
+ );
+ }
- if (argv.reporter === "progress") {
- throw createUnsupportedError(
- "--reporter=progress is mutually exclusive with --parallel",
- );
- }
+ Object.keys(ONE_AND_DONES).forEach((opt) => {
+ if (argv[opt]) {
+ ONE_AND_DONES[opt].call(null);
+ process.exit(0);
+ }
+ });
+
+ if (argv.invert && !("fgrep" in argv || "grep" in argv)) {
+ throw createMissingArgumentError(
+ '"--invert" requires one of "--fgrep <str>" or "--grep <regexp>"',
+ "--fgrep|--grep",
+ "string|regexp",
+ );
+ }
- if (argv.reporter === "markdown") {
- throw createUnsupportedError(
- "--reporter=markdown is mutually exclusive with --parallel",
- );
- }
+ if (argv.fgrep && argv.grep) {
+ throw createUnsupportedError(
+ "Arguments fgrep and grep are mutually exclusive",
+ );
+ }
- if (argv.reporter === "json-stream") {
- throw createUnsupportedError(
- "--reporter=json-stream is mutually exclusive with --parallel",
- );
- }
- }
+ if (argv.parallel) {
+ if (argv.file) {
+ throw createUnsupportedError(
+ "--parallel runs test files in a non-deterministic order, and is mutually exclusive with --file",
+ );
+ }
+
+ if (argv.sort) {
+ throw createUnsupportedError(
+ "--parallel runs test files in a non-deterministic order, and is mutually exclusive with --sort",
+ );
+ }
+
+ if (["progress", "markdown", "json-stream"].includes(argv.reporter)) {
+ throw createUnsupportedError(
+ `--reporter=${argv.reporter} is mutually exclusive with --parallel`,
+ );
+ }
+ }
+};
- return true;
- })
- .middleware(async (argv, yargs) => {
- // currently a failing middleware does not work nicely with yargs' `fail()`.
- try {
- // load requires first, because it can impact "plugin" validation
- const plugins = await handleRequires(argv.require);
- validateLegacyPlugin(argv, "reporter", Mocha.reporters);
- validateLegacyPlugin(argv, "ui", Mocha.interfaces);
- Object.assign(argv, plugins);
- } catch (err) {
- // this could be a bad --require, bad reporter, ui, etc.
- console.error(`\n${logSymbols.error} ${pc.red("ERROR:")}`, err);
- yargs.exit(1);
- }
- })
- .array(types.array)
- .boolean(types.boolean)
- .string(types.string)
- .number(types.number)
- .alias(aliases);
+const prepareRunOptions = async (argv) => {
+ const plugins = await handleRequires(argv.require);
+ validateLegacyPlugin(argv, "reporter", Mocha.reporters);
+ validateLegacyPlugin(argv, "ui", Mocha.interfaces);
+ Object.assign(argv, plugins);
+ return argv;
+};
+
+exports.validateRunOptions = validateRunOptions;
+exports.prepareRunOptions = prepareRunOptions;
+exports.normalizeRunOptions = normalizeRunOptions;
exports.handler = async function (argv) {
- debug("post-yargs config", argv);
+ normalizeRunOptions(argv);
+ debug("running with config", argv);
const mocha = new Mocha(argv);
try {
diff --git a/lib/cli/unparse-args.js b/lib/cli/unparse-args.js
index b11dff4b..c7edded2 100644
--- a/lib/cli/unparse-args.js
+++ b/lib/cli/unparse-args.js
@@ -23,6 +23,9 @@ const unparseOption = (name, value) => {
);
}
+ if (name.includes(".")) {
+ return [`--${name}=${String(value)}`];
+ }
return [`--${name}`, String(value)];
};
diff --git a/package-lock.json b/package-lock.json
index a3bf20c7..77795b65 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -24,8 +24,7 @@
"serialize-javascript": "^7.0.2",
"strip-json-comments": "^5.0.3",
"supports-color": "^8.1.1",
- "workerpool": "^10.0.0",
- "yargs": "^17.7.2"
+ "workerpool": "^10.0.0"
},
"bin": {
"mocha": "bin/mocha.js"
@@ -40,7 +39,6 @@
"@rollup/plugin-node-resolve": "^16.0.3",
"@test/esm-only-loader": "./test/compiler-fixtures/esm-only-loader",
"@types/node": "^24.0.0",
- "@types/yargs": "^17.0.33",
"chai": "^6.0.0",
"coffeescript": "^2.6.1",
"cross-env": "^10.0.0",
@@ -2435,23 +2433,6 @@
"dev": true,
"license": "MIT"
},
- "node_modules/@types/yargs": {
- "version": "17.0.33",
- "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-17.0.33.tgz",
- "integrity": "sha512-WpxBCKWPLr4xSsHgz511rFJAM+wS28w2zEO1QDNY5zM/S8ok70NNfztH0xwhqKyaK0OHCbN98LDAZuy1ctxDkA==",
- "dev": true,
- "license": "MIT",
- "dependencies": {
- "@types/yargs-parser": "*"
- }
- },
- "node_modules/@types/yargs-parser": {
- "version": "21.0.3",
- "resolved": "https://registry.npmjs.org/@types/yargs-parser/-/yargs-parser-21.0.3.tgz",
- "integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",
- "dev": true,
- "license": "MIT"
- },
"node_modules/@voxpelli/semver-set": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/@voxpelli/semver-set/-/semver-set-6.0.0.tgz",
@@ -2775,6 +2756,7 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
"engines": {
"node": ">=8"
}
@@ -2783,6 +2765,7 @@
"version": "4.3.0",
"resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
"integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "dev": true,
"dependencies": {
"color-convert": "^2.0.1"
},
@@ -3373,6 +3356,7 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
"integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "dev": true,
"dependencies": {
"color-name": "~1.1.4"
},
@@ -3389,7 +3373,8 @@
"node_modules/color-name": {
"version": "1.1.4",
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
- "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "dev": true
},
"node_modules/commander": {
"version": "2.20.3",
@@ -3781,7 +3766,8 @@
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
- "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "dev": true
},
"node_modules/enhanced-resolve": {
"version": "5.24.2",
@@ -3860,6 +3846,7 @@
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
"integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
+ "dev": true,
"license": "MIT",
"engines": {
"node": ">=6"
@@ -4504,6 +4491,7 @@
"version": "2.0.5",
"resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
"integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
+ "dev": true,
"engines": {
"node": "6.* || 8.* || >= 10.*"
}
@@ -5026,6 +5014,7 @@
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true,
"engines": {
"node": ">=8"
}
@@ -7964,6 +7953,7 @@
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
"integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
+ "dev": true,
"engines": {
"node": ">=0.10.0"
}
@@ -8555,6 +8545,7 @@
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "dev": true,
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
@@ -8584,6 +8575,7 @@
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
"dependencies": {
"ansi-regex": "^5.0.1"
},
@@ -9448,6 +9440,7 @@
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
"integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
+ "dev": true,
"dependencies": {
"ansi-styles": "^4.0.0",
"string-width": "^4.1.0",
@@ -9504,6 +9497,7 @@
"version": "5.0.8",
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
"integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
+ "dev": true,
"engines": {
"node": ">=10"
}
@@ -9535,6 +9529,7 @@
"version": "17.7.2",
"resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz",
"integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==",
+ "dev": true,
"license": "MIT",
"dependencies": {
"cliui": "^8.0.1",
@@ -9553,6 +9548,7 @@
"version": "21.1.1",
"resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
"integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
+ "dev": true,
"license": "ISC",
"engines": {
"node": ">=12"
@@ -9562,6 +9558,7 @@
"version": "8.0.1",
"resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
"integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
+ "dev": true,
"license": "ISC",
"dependencies": {
"string-width": "^4.2.0",
diff --git a/package.json b/package.json
index 45936a76..8ca67026 100644
--- a/package.json
+++ b/package.json
@@ -102,8 +102,7 @@
"serialize-javascript": "^7.0.2",
"strip-json-comments": "^5.0.3",
"supports-color": "^8.1.1",
- "workerpool": "^10.0.0",
- "yargs": "^17.7.2"
+ "workerpool": "^10.0.0"
},
"devDependencies": {
"@eslint/js": "^10.0.0",
@@ -115,7 +114,6 @@
"@rollup/plugin-node-resolve": "^16.0.3",
"@test/esm-only-loader": "./test/compiler-fixtures/esm-only-loader",
"@types/node": "^24.0.0",
- "@types/yargs": "^17.0.33",
"chai": "^6.0.0",
"coffeescript": "^2.6.1",
"cross-env": "^10.0.0",
diff --git a/test/integration/help.spec.js b/test/integration/help.spec.js
new file mode 100644
index 00000000..3fa76833
--- /dev/null
+++ b/test/integration/help.spec.js
@@ -0,0 +1,82 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { sync as rimrafSync } from "rimraf";
+import { invokeMocha } from "./helpers.cjs";
+
+function expectSuccessfulOutput(args, matcher, done) {
+ invokeMocha(
+ args,
+ function (err, result) {
+ if (err) {
+ return done(err);
+ }
+ expect(result, "to have succeeded");
+ expect(result.output, "to match", matcher);
+ done();
+ },
+ { stdio: "pipe" },
+ );
+}
+
+describe("help", function () {
+ it("prints usage, commands and common options", function (done) {
+ invokeMocha(
+ ["--help"],
+ function (err, result) {
+ if (err) {
+ return done(err);
+ }
+ expect(result, "to have succeeded");
+ expect(result.output, "to contain", "Usage: mocha [spec..]");
+ expect(result.output, "to contain", "mocha init <path>");
+ expect(result.output, "to contain", "--reporter");
+ expect(result.output, "to contain", "--timeout");
+ done();
+ },
+ { stdio: "pipe" },
+ );
+ });
+
+ it("prints usage for -h", function (done) {
+ expectSuccessfulOutput(["-h"], /Usage: mocha \[spec\.\.\]/, done);
+ });
+
+ it("prints help for init --help without writing files", function (done) {
+ const tmpdir = fs.mkdtempSync(path.join(os.tmpdir(), "mocha-init-help-"));
+
+ invokeMocha(
+ ["init", tmpdir, "--help"],
+ function (err, result) {
+ const files = fs.readdirSync(tmpdir);
+ rimrafSync(tmpdir);
+ if (err) {
+ return done(err);
+ }
+ expect(result, "to have succeeded");
+ expect(result.output, "to contain", "Usage: mocha [spec..]");
+ expect(files, "to be empty");
+ done();
+ },
+ { stdio: "pipe" },
+ );
+ });
+});
+
+describe("version", function () {
+ it("prints version for --version", function (done) {
+ expectSuccessfulOutput(["--version"], /^\d+\.\d+\.\d+/, done);
+ });
+
+ it("prints version for -V", function (done) {
+ expectSuccessfulOutput(["-V"], /^\d+\.\d+\.\d+/, done);
+ });
+
+ it("prints version without loading required modules", function (done) {
+ expectSuccessfulOutput(
+ ["--version", "--require", "definitely-missing-module"],
+ /^\d+\.\d+\.\d+/,
+ done,
+ );
+ });
+});
diff --git a/test/integration/init.spec.cjs b/test/integration/init.spec.cjs
index d2f5f269..88f93476 100644
--- a/test/integration/init.spec.cjs
+++ b/test/integration/init.spec.cjs
@@ -2,10 +2,21 @@
var fs = require("node:fs");
var rimraf = require("rimraf");
-var invokeMocha = require("./helpers.cjs").invokeMocha;
+var helpers = require("./helpers.cjs");
+var invokeMocha = helpers.invokeMocha;
+var invokeNode = helpers.invokeNode;
var path = require("node:path");
var os = require("node:os");
+var CLI_EXECUTABLE = require.resolve("../../lib/cli/cli.js");
+
+function expectInitFiles(tmpdir) {
+ expect(fs.existsSync(path.join(tmpdir, "mocha.css")), "to be true");
+ expect(fs.existsSync(path.join(tmpdir, "mocha.js")), "to be true");
+ expect(fs.existsSync(path.join(tmpdir, "tests.spec.js")), "to be true");
+ expect(fs.existsSync(path.join(tmpdir, "index.html")), "to be true");
+}
+
describe("init command", function () {
var tmpdir;
@@ -70,10 +81,37 @@ describe("init command", function () {
return done(err);
}
expect(result, "to have succeeded");
- expect(fs.existsSync(path.join(tmpdir, "mocha.css")), "to be true");
- expect(fs.existsSync(path.join(tmpdir, "mocha.js")), "to be true");
- expect(fs.existsSync(path.join(tmpdir, "tests.spec.js")), "to be true");
- expect(fs.existsSync(path.join(tmpdir, "index.html")), "to be true");
+ expectInitFiles(tmpdir);
+ done();
+ },
+ { stdio: "pipe" },
+ );
+ });
+
+ it("should create files when init follows a top-level option", function (done) {
+ invokeNode(
+ [CLI_EXECUTABLE, "--no-config", "init", tmpdir],
+ function (err, result) {
+ if (err) {
+ return done(err);
+ }
+ expect(result, "to have succeeded");
+ expectInitFiles(tmpdir);
+ done();
+ },
+ { stdio: "pipe" },
+ );
+ });
+
+ it("should create files when init is respawned with a Node option", function (done) {
+ invokeMocha(
+ ["--node-option", "trace-warnings", "init", tmpdir],
+ function (err, result) {
+ if (err) {
+ return done(err);
+ }
+ expect(result, "to have succeeded");
+ expectInitFiles(tmpdir);
done();
},
{ stdio: "pipe" },
diff --git a/test/integration/options/listInterfaces.spec.cjs b/test/integration/options/listInterfaces.spec.cjs
index c9bcb3d2..b2782522 100644
--- a/test/integration/options/listInterfaces.spec.cjs
+++ b/test/integration/options/listInterfaces.spec.cjs
@@ -35,4 +35,22 @@ describe("--list-interfaces", function () {
done();
});
});
+
+ it("should fail when combined with another one-and-done option", function (done) {
+ invokeMocha(
+ ["--list-interfaces", "--list-reporters"],
+ function (err, result) {
+ if (err) {
+ return done(err);
+ }
+ expect(
+ result,
+ "to have failed with output",
+ /Arguments list-interfaces and list-reporters are mutually exclusive/,
+ );
+ done();
+ },
+ { stdio: "pipe" },
+ );
+ });
});
diff --git a/test/integration/options/listReporters.spec.cjs b/test/integration/options/listReporters.spec.cjs
index fca9055f..8056e97f 100644
--- a/test/integration/options/listReporters.spec.cjs
+++ b/test/integration/options/listReporters.spec.cjs
@@ -37,4 +37,22 @@ describe("--list-reporters", function () {
done();
});
});
+
+ it("should fail when combined with another one-and-done option", function (done) {
+ invokeMocha(
+ ["--list-reporters", "--list-interfaces"],
+ function (err, result) {
+ if (err) {
+ return done(err);
+ }
+ expect(
+ result,
+ "to have failed with output",
+ /Arguments list-interfaces and list-reporters are mutually exclusive/,
+ );
+ done();
+ },
+ { stdio: "pipe" },
+ );
+ });
});
diff --git a/test/integration/options/reporter-option.spec.cjs b/test/integration/options/reporter-option.spec.cjs
index 60c59fcf..8d2fd51f 100644
--- a/test/integration/options/reporter-option.spec.cjs
+++ b/test/integration/options/reporter-option.spec.cjs
@@ -1,7 +1,19 @@
"use strict";
var runMocha = require("../helpers.cjs").runMocha;
+var invokeMocha = require("../helpers.cjs").invokeMocha;
var path = require("node:path");
+var fs = require("node:fs");
+var os = require("node:os");
+var rimraf = require("rimraf");
+
+var customReporter = path.join(
+ __dirname,
+ "..",
+ "fixtures",
+ "options",
+ "reporter-with-options.fixture.cjs",
+);
describe("--reporter-option", function () {
describe("when given options w/ invalid format", function () {
@@ -26,18 +38,7 @@ describe("--reporter-option", function () {
it("should allow comma-separated values", function (done) {
runMocha(
"passing.fixture.cjs",
- [
- "--reporter",
- path.join(
- __dirname,
- "..",
- "fixtures",
- "options",
- "reporter-with-options.fixture.cjs",
- ),
- "--reporter-option",
- "foo=bar,baz=quux",
- ],
+ ["--reporter", customReporter, "--reporter-option", "foo=bar,baz=quux"],
function (err, res) {
if (err) {
return done(err);
@@ -57,13 +58,7 @@ describe("--reporter-option", function () {
"passing.fixture.cjs",
[
"--reporter",
- path.join(
- __dirname,
- "..",
- "fixtures",
- "options",
- "reporter-with-options.fixture.cjs",
- ),
+ customReporter,
"--reporter-option",
"foo=bar",
"--reporter-option",
@@ -82,5 +77,130 @@ describe("--reporter-option", function () {
"pipe",
);
});
+
+ it("should allow key-only boolean values", function (done) {
+ runMocha(
+ "passing.fixture.cjs",
+ ["--reporter", customReporter, "--reporter-option", "foo"],
+ function (err, res) {
+ if (err) {
+ return done(err);
+ }
+ expect(res, "to have passed").and(
+ "to contain output",
+ /{"foo":true}/,
+ );
+ done();
+ },
+ "pipe",
+ );
+ });
+
+ it("should allow the short alias", function (done) {
+ runMocha(
+ "passing.fixture.cjs",
+ ["--reporter", customReporter, "-O", "foo=bar"],
+ function (err, res) {
+ if (err) {
+ return done(err);
+ }
+ expect(res, "to have passed").and(
+ "to contain output",
+ /{"foo":"bar"}/,
+ );
+ done();
+ },
+ "pipe",
+ );
+ });
+
+ it("should allow the long alias", function (done) {
+ runMocha(
+ "passing.fixture.cjs",
+ ["--reporter", customReporter, "--reporter-options", "foo=bar"],
+ function (err, res) {
+ if (err) {
+ return done(err);
+ }
+ expect(res, "to have passed").and(
+ "to contain output",
+ /{"foo":"bar"}/,
+ );
+ done();
+ },
+ "pipe",
+ );
+ });
+
+ it("should preserve package config reporter options after respawning with a Node option", function (done) {
+ var tmpdir = fs.mkdtempSync(
+ path.join(os.tmpdir(), "mocha-reporter-option-"),
+ );
+ fs.writeFileSync(
+ path.join(tmpdir, "package.json"),
+ JSON.stringify({
+ mocha: {
+ reporter: customReporter,
+ "reporter-option": ["foo=bar"],
+ spec: [
+ path.join(__dirname, "..", "fixtures", "passing.fixture.cjs"),
+ ],
+ },
+ }),
+ );
+
+ invokeMocha(
+ ["--node-option", "trace-warnings"],
+ function (err, res) {
+ rimraf.sync(tmpdir);
+ if (err) {
+ return done(err);
+ }
+ expect(res, "to have passed").and(
+ "to contain output",
+ /{"foo":"bar"}/,
+ );
+ done();
+ },
+ { cwd: tmpdir, stdio: "pipe" },
+ );
+ });
+
+ it("should preserve package config reporter option objects after respawning with a Node option", function (done) {
+ var tmpdir = fs.mkdtempSync(
+ path.join(os.tmpdir(), "mocha-reporter-option-"),
+ );
+ fs.writeFileSync(
+ path.join(tmpdir, "package.json"),
+ JSON.stringify({
+ mocha: {
+ reporter: customReporter,
+ "reporter-option": {
+ foo: "bar",
+ baz: true,
+ },
+ spec: [
+ path.join(__dirname, "..", "fixtures", "passing.fixture.cjs"),
+ ],
+ },
+ }),
+ );
+
+ invokeMocha(
+ ["--node-option", "trace-warnings"],
+ function (err, res) {
+ rimraf.sync(tmpdir);
+ if (err) {
+ return done(err);
+ }
+ expect(res, "to have passed").and(
+ "to contain output",
+ /{"foo":"bar","baz":true}/,
+ );
+ done();
+ },
+ { cwd: tmpdir, stdio: "pipe" },
+ );
+ });
});
});
diff --git a/test/integration/options/run-preparation.spec.js b/test/integration/options/run-preparation.spec.js
new file mode 100644
index 00000000..ae8e3170
--- /dev/null
+++ b/test/integration/options/run-preparation.spec.js
@@ -0,0 +1,37 @@
+import { runMocha } from "../helpers.cjs";
+
+describe("run preparation", function () {
+ it("should fail when a required module cannot be loaded", function (done) {
+ runMocha(
+ "passing.fixture.cjs",
+ ["--require", "definitely-missing-module"],
+ function (err, result) {
+ if (err) {
+ return done(err);
+ }
+ expect(result, "to have failed");
+ expect(result.output, "to contain", "ERROR:");
+ expect(result.output, "to contain", "definitely-missing-module");
+ done();
+ },
+ "pipe",
+ );
+ });
+
+ it("should fail when a reporter cannot be loaded", function (done) {
+ runMocha(
+ "passing.fixture.cjs",
+ ["--reporter", "definitely-missing-reporter"],
+ function (err, result) {
+ if (err) {
+ return done(err);
+ }
+ expect(result, "to have failed");
+ expect(result.output, "to contain", "ERROR:");
+ expect(result.output, "to contain", "definitely-missing-reporter");
+ done();
+ },
+ "pipe",
+ );
+ });
+});
diff --git a/test/node-unit/cli/cli.spec.js b/test/node-unit/cli/cli.spec.js
new file mode 100644
index 00000000..e69f5704
--- /dev/null
+++ b/test/node-unit/cli/cli.spec.js
@@ -0,0 +1,26 @@
+import { main } from "../../../lib/cli/cli.js";
+import sinon from "sinon";
+
+describe("cli", function () {
+ describe("main()", function () {
+ beforeEach(function () {
+ sinon.stub(console, "error");
+ sinon.stub(console, "log");
+ sinon.stub(process, "exit").throws(new Error("process.exit"));
+ });
+
+ afterEach(function () {
+ sinon.restore();
+ });
+
+ it("prints version and exits for --version", function () {
+ expect(() => main(["--version"]), "to throw", /process\.exit/);
+ expect(process.exit, "to have a call satisfying", [0]);
+ });
+
+ it("prints help and exits for --help", function () {
+ expect(() => main(["--help"]), "to throw", /process\.exit/);
+ expect(process.exit, "to have a call satisfying", [0]);
+ });
+ });
+});
diff --git a/test/node-unit/cli/run.spec.cjs b/test/node-unit/cli/run.spec.cjs
index 1969b649..b7b48bd0 100644
--- a/test/node-unit/cli/run.spec.cjs
+++ b/test/node-unit/cli/run.spec.cjs
@@ -1,24 +1,45 @@
"use strict";
-const { builder } = require("../../../lib/cli/run.cjs");
-const { types } = require("../../../lib/cli/run-option-metadata.cjs");
+const {
+ getRunOptionDefinitions,
+ types,
+} = require("../../../lib/cli/run-option-metadata.cjs");
+const { validateRunOptions } = require("../../../lib/cli/run.cjs");
describe("command", function () {
describe("run", function () {
- describe("builder", function () {
- const IGNORED_OPTIONS = new Set(["help", "version"]);
- const options = builder(require("yargs")()).getOptions();
+ describe("option metadata", function () {
["number", "string", "boolean", "array"].forEach((type) => {
describe(`${type} type`, function () {
- Array.from(new Set(options[type])).forEach((option) => {
- if (!IGNORED_OPTIONS.has(option)) {
- it(`should include option ${option}`, function () {
- expect(types[type], "to contain", option);
+ getRunOptionDefinitions()
+ .filter((option) => option.type === type)
+ .forEach((option) => {
+ it(`should include option ${option.name}`, function () {
+ expect(types[type], "to contain", option.name);
});
- }
- });
+ });
});
});
});
});
});
+
+describe("validateRunOptions()", function () {
+ it("throws when multiple one-and-done options are provided", function () {
+ expect(
+ () =>
+ validateRunOptions({
+ "list-interfaces": true,
+ "list-reporters": true,
+ }),
+ "to throw",
+ /Arguments list-interfaces and list-reporters are mutually exclusive/,
+ );
+ });
+
+ it("does not throw when no one-and-done option is provided", function () {
+ expect(() => validateRunOptions({}), "not to throw");
+ });
+
+ // providing exactly one one-and-done option is tested via each option's tests
+});
diff --git a/test/node-unit/cli/unparse-args.spec.js b/test/node-unit/cli/unparse-args.spec.js
index 6e9e7955..8b6c8145 100644
--- a/test/node-unit/cli/unparse-args.spec.js
+++ b/test/node-unit/cli/unparse-args.spec.js
@@ -85,7 +85,7 @@ describe("unparse-args", function () {
);
});
- it("unparses reporter-option object values in yargs-unparser-compatible dotted form", function () {
+ it("unparses reporter-option object values in dotted form", function () {
expect(
unparseMochaArgs({
"reporter-option": {
@@ -94,7 +94,7 @@ describe("unparse-args", function () {
},
}),
"to equal",
- ["--reporter-option.foo", "bar", "--reporter-option.baz"],
+ ["--reporter-option.foo=bar", "--reporter-option.baz"],
);
});
});