# disableTimeouts(value)
Given option/command value, disable timeouts if applicable
Parameters
| Name | Types | Description |
|---|---|---|
| value | string |
- Value to check |
# os()
private method
This wrapper executable checks for known node flags and appends them when found, before invoking the "real" executable (lib/cli/cli.js)
# trimV8Option(value)
If value begins with v8- and is not explicitly v8-options, remove prefix
Parameters
| Name | Types | Description |
|---|---|---|
| value | string |
- Value to check |
# mocha.throwError()
Function to allow assertion libraries to throw errors directly into mocha. This is useful when running tests in a browser because window.onerror will only receive the 'message' attribute of the Error.
# mocha.ui()
Override ui to ensure that the ui functions are initialized. Normally this would happen in Mocha.prototype.loadFiles.
# process.removeListener()
Remove uncaughtException listener. Revert to original onerror handler if previously defined.
# addStandardDependencies(cfg)
Returns a new Karma config containing standard dependencies for our tests. Most suites use this.
Parameters
| Name | Types | Description |
|---|---|---|
| cfg | KarmaConfig |
# baseConfig()
# chooseTestSuite(cfg, value)
Returns a new Karma config to run with specific configuration (which cannot be run with other configurations) as specified by value. Known values: - bdd - bdd-specific tests - tdd - tdd-specific tests - qunit - qunit-specific tests - esm - ESM-specific tests Since we can't change Mocha's interface on-the-fly, tests for specific interfaces must be run in isolation.
Parameters
| Name | Types | Description |
|---|---|---|
| cfg | KarmaConfig |
|
| value | string |
Configuration identifier, if any |
# createBundleDir(cfg, bundleDirPath)
Creates dir bundleDirPath if it does not exist; returns new Karma config containing bundleDirPath for rollup plugin. If this fails, the rollup plugin will use a temp dir.
Parameters
| Name | Types | Description |
|---|---|---|
| cfg | KarmaConfig |
|
| bundleDirPath | string |
Path where the output bundle should live |
# highlight(js)
private method
Highlight the given string of js.
Parameters
| Name | Types | Description |
|---|---|---|
| js | string |
Returns
string
# highlightTags(name)
private method
Highlight the contents of tag name.
Parameters
| Name | Types | Description |
|---|---|---|
| name | string |
# parseQuery(qs)
private method
Parse the given qs.
Parameters
| Name | Types | Description |
|---|---|---|
| qs | string |
Returns
Object<string, string>
# debug()
Contains CLI entry point and public API for programmatic usage in Node.js. - Option parsing is handled by {@link https://npm.im/yargs yargs}. - If executed via node, this module will run {@linkcode module:lib/cli.main main()}.
# exports.main(argv, mochaArgs)
- Accepts an
Arrayof arguments - Modifies {@link https://nodejs.org/api/modules.html#modules_module_paths Node.js' search path} for easy loading of consumer modules - Sets {@linkcode https://nodejs.org/api/errors.html#errors_error_stacktracelimit Error.stackTraceLimit} toInfinity
Parameters
| Name | Types | Description |
|---|---|---|
| argv | string[] |
- Array of arguments to parse, or by default the lovely process.argv.slice(2) |
| mochaArgs | object |
- Object of already parsed Mocha arguments (by bin/mocha) |
# module.exports(opts)
private method
Smash together an array of test files in the correct order
Parameters
| Name | Types | Description |
|---|---|---|
| opts | FileCollectionOptions |
- Options |
# exports.CONFIG_FILES()
private method
These are the valid config files, in order of precedence; e.g., if .mocharc.js is present, then .mocharc.yaml and the rest will be ignored. The user should still be able to explicitly specify a file.
# exports.findConfig(cwd)
Find ("find up") config file starting at cwd
Parameters
| Name | Types | Description |
|---|---|---|
| cwd | string |
- Current working directory |
# exports.loadConfig(filepath)
private method
Loads and parses, based on file extension, a config file. "JSON" files may have comments.
Parameters
| Name | Types | Description |
|---|---|---|
| filepath | string |
- Config file path to load |
# parsers()
Parsers for various config filetypes. Each accepts a filepath and returns an object (but could throw)
# fs()
private method
Contains lookupFiles, which takes some globs/dirs/options and returns a list of files.
# hasMatchingExtname(pathname, exts)
private method
Determines if pathname has a matching file extension. Supports multi-part extensions.
Parameters
| Name | Types | Description |
|---|---|---|
| pathname | string |
- Pathname to check for match. |
| exts | string[] |
- List of file extensions, w/-or-w/o leading period |
Returns
boolean
`true` if file extension matches.
# isHiddenOnUnix(pathname)
private method
Determines if pathname would be a "hidden" file (or directory) on UN*X.
Parameters
| Name | Types | Description |
|---|---|---|
| pathname | string |
- Pathname to check for match. |
Returns
boolean
whether pathname would be considered a hidden file.
# lookupFiles(filepath, extensions, recursive)
Lookup file names at the given path.
Parameters
| Name | Types | Description |
|---|---|---|
| filepath | string |
- Base path to start searching from. |
| extensions | string[] |
- File extensions to look for. |
| recursive | boolean |
- Whether to recurse into subdirectories. |
Returns
string[]
An array of paths.
# exports.impliesNoTimeouts(flag)
private method
Returns true if the flag is a "debug-like" flag. These require timeouts to be suppressed, or pausing the debugger on breakpoints will cause test failures.
Parameters
| Name | Types | Description |
|---|---|---|
| flag | string |
- Flag to test |
# exports.isNodeFlag(flag, bareword)
private method
Mocha has historical support for various node and V8 flags which might not appear in process.allowedNodeEnvironmentFlags. These include: - --preserve-symlinks - --harmony-* - --gc-global - --trace-* - --es-staging - --use-strict - --v8-* (but not --v8-options)
Parameters
| Name | Types | Description |
|---|---|---|
| flag | string |
- Flag to test |
| bareword | boolean |
- If false, we expect flag to have one or two leading dashes. |
# exports.unparseNodeFlags(opts)
private method
All non-strictly-boolean arguments to node--those with values--must specify those values using =, e.g., --inspect=0.0.0.0. Unparse these arguments using yargs-unparser (which would result in --inspect 0.0.0.0), then supply = where we have values. There's probably an easier or more robust way to do this; fixes welcome
Parameters
| Name | Types | Description |
|---|---|---|
| opts | Object |
- Arguments object |
# nodeFlags()
private method
Some settings and code related to Mocha's handling of Node.js/V8 flags.
# Mocha()
private method
Contains "command" code for "one-and-dones"--options passed to Mocha which cause it to just dump some info and exit. See {@link module:lib/cli/one-and-dones.ONE_AND_DONE_ARGS ONE_AND_DONE_ARGS} for more info.
# showKeys(obj)
private method
Dumps a sorted list of the enumerable, lower-case keys of some object to STDOUT.
Parameters
| Name | Types | Description |
|---|---|---|
| obj | Object |
- Object, ostensibly having some enumerable keys |
# configuration()
private method
This is the config pulled from the yargs property of Mocha's package.json, but it also disables camel case expansion as to avoid outputting non-canonical keynames, as we need to do some lookups.
# createErrorForNumericPositionalArg(allArgs, numericArg, parsedResult)
private method
Throws either "UNSUPPORTED" error or "INVALID_ARG_TYPE" error for numeric positional arguments.
Parameters
| Name | Types | Description |
|---|---|---|
| allArgs | string[] |
- Stringified args passed to mocha cli |
| numericArg | number |
- Numeric positional arg for which error must be thrown |
| parsedResult | Object |
- Result from yargs-parser |
# fs()
private method
Main entry point for handling filesystem-based configuration, whether that's a config file or package.json or whatever.
# globOptions()
private method
This is a really fancy way to: - array-type options: ensure unique values and evtl. split comma-delimited lists - boolean/number/string- options: use last element when given multiple times This is passed as the coerce option to yargs-parser
# loadOptions(argv)
Priority list: 1. Command-line args 2. MOCHA_OPTIONS environment variable. 3. RC file (.mocharc.c?js, .mocharc.ya?ml, mocharc.json) 4. mocha prop of package.json 5. 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.
Parameters
| Name | Types | Description |
|---|---|---|
| argv | string |
string[] |
# loadPkgRc(args, args.config)
Given path to package.json in args.package, attempt to load config from mocha prop.
Parameters
| Name | Types | Description |
|---|---|---|
| args | Object |
- Arguments object |
| args.config | string |
boolean |
# loadRc(args, args.config)
Given path to config file in args.config, attempt to load & parse config file.
Parameters
| Name | Types | Description |
|---|---|---|
| args | Object |
- Arguments object |
| args.config | string |
boolean |
# nargOpts()
private method
We do not have a case when multiple arguments are ever allowed after a flag (e.g., --foo bar baz quux), so we fix the number of arguments to 1 across the board of non-boolean options. This is passed as the narg option to yargs-parser
# parse(args, defaultValues, configObjects)
private method
Wrapper around yargs-parser which applies our settings
Parameters
| Name | Types | Description |
|---|---|---|
| args | string |
string[] |
| defaultValues | Object |
- Default values of mocharc.json |
| configObjects | ...Object |
- configObjects for yargs-parser |
# exitMocha(clampedCode)
private method
Exits Mocha when Mocha itself has finished execution, regardless of what the tests or code under test is doing.
Parameters
| Name | Types | Description |
|---|---|---|
| clampedCode | number |
- Exit code; typically # of failures |
# exitMochaLater(clampedCode)
private method
Exits Mocha when tests + code under test has finished execution (default)
Parameters
| Name | Types | Description |
|---|---|---|
| clampedCode | number |
- Exit code; typically # of failures |
# exports.handleRequires(requires)
private method
require() the modules as required by --require <require>. Returns array of mochaHooks exports, if any.
Parameters
| Name | Types | Description |
|---|---|---|
| requires | string[] |
- Modules to require |
# exports.list(str)
private method
Coerce a comma-delimited string (or array thereof) into a flattened array of strings
Parameters
| Name | Types | Description |
|---|---|---|
| str | string |
string[] |
# exports.runMocha(mocha, options)
private method
Actually run tests. Delegates to one of four different functions: - singleRun: run tests in serial & exit - watchRun: run tests in serial, rerunning as files change - parallelRun: run tests in parallel & exit - watchParallelRun: run tests in parallel, rerunning as files change
Parameters
| Name | Types | Description |
|---|---|---|
| mocha | Mocha |
- Mocha instance |
| options | MochaOptions |
- Command line options |
# exports.validateLegacyPlugin(opts, pluginType, map)
private method
Used for --reporter and --ui. Ensures there's only one, and asserts that it actually exists. This must be run after requires are processed (see {@link handleRequires}), as it'll prevent interfaces from loading otherwise.
Parameters
| Name | Types | Description |
|---|---|---|
| opts | Object |
- Options object |
| pluginType | "reporter" |
"ui" |
| map | Object |
- Used as a cache of sorts; Mocha.reporters where each key corresponds to a reporter name, Mocha.interfaces where each key corresponds to an interface name. |
# fs()
# handleUnmatchedFiles(mocha, unmatchedFiles)
private method
Logs errors and exits the app if unmatched files exist
Parameters
| Name | Types | Description |
|---|---|---|
| mocha | Mocha |
- Mocha instance |
| unmatchedFiles | UnmatchedFile |
- object containing unmatched file paths |
# parallelRun(mocha, options, fileCollectParams)
private method
Collect files and run tests (using Runner). This is async for consistency.
Parameters
| Name | Types | Description |
|---|---|---|
| mocha | Mocha |
- Mocha instance |
| options | MochaOptions |
- Command line options |
| fileCollectParams | Object |
- Parameters that control test file collection. See lib/cli/collect-files.js. |
# pluginId()
This should be a unique identifier; either a string (present in map), or a resolvable (via require.resolve) module ID/path.
# singleRun(mocha, opts, fileCollectParams)
private method
Collect and load test files, then run mocha instance.
Parameters
| Name | Types | Description |
|---|---|---|
| mocha | Mocha |
- Mocha instance |
| opts | MochaOptions |
- Command line options |
| fileCollectParams | Object |
- Parameters that control test file collection. See lib/cli/collect-files.js. |
# exports.aliases()
private method
Option aliases keyed by canonical option name. Arrays used to reduce
# exports.expectedTypeForFlag(flag)
private method
Returns expected yarg option type for a given mocha flag.
Parameters
| Name | Types | Description |
|---|---|---|
| flag | string |
- Flag to check (can be with or without leading dashes "--"") |
# exports.isMochaFlag(flag)
private method
Returns true if the provided flag is known to Mocha.
Parameters
| Name | Types | Description |
|---|---|---|
| flag | string |
- Flag to check |
# blastCache(watcher)
private method
Blast all of the watched files out of require.cache
Parameters
| Name | Types | Description |
|---|---|---|
| watcher | FSWatcher |
- Chokidar FSWatcher |
# cache(map, key, value)
Performs a map.set() but will delete the first key for new key-value pairs whenever the limit is reached.
Parameters
| Name | Types | Description |
|---|---|---|
| map | Map<string, boolean> |
The map to use. |
| key | string |
The key to use. |
| value | boolean |
The value to set. |
# createPathFilter(globPaths, basePath)
private method
Extracts out paths without the glob part, the directory paths, and the paths for matching from the provided glob paths.
Parameters
| Name | Types | Description |
|---|---|---|
| globPaths | string[] |
The list of glob paths to create a filter for. |
| basePath | string |
The path where mocha is run (e.g., current working directory). |
# createPathMatcher(allowed, ignored, basePath)
private method
Creates an object for matching allowed or ignored file paths.
Parameters
| Name | Types | Description |
|---|---|---|
| allowed | PathFilter |
The filter for allowed paths. |
| ignored | PathFilter |
The filter for ignored paths. |
| basePath | string |
The path where mocha is run (e.g., current working directory). |
# createRerunner(mocha, watcher, opts, opts.beforeRun)
private method
Create an object that allows you to rerun tests on the mocha instance.
Parameters
| Name | Types | Description |
|---|---|---|
| mocha | Mocha |
- Mocha instance |
| watcher | FSWatcher |
- Chokidar FSWatcher instance |
| opts | Object |
- Options! |
| opts.beforeRun | BeforeWatchRun |
- Function to call before mocha.run() |
# createWatcher(mocha, opts, opts.beforeRun, opts.watchFiles, opts.watchIgnore, opts.fileCollectParams)
private method
Bootstraps a Chokidar watcher. Handles keyboard input & signals
Parameters
| Name | Types | Description |
|---|---|---|
| mocha | Mocha |
- Mocha instance |
| opts | Object |
|
| opts.beforeRun | BeforeWatchRun |
- Function to call before mocha.run() |
| opts.watchFiles | string[] |
- List of paths and patterns to watch. If not provided all files with an extension included in fileCollectionParams.extension are watched. See first argument of chokidar.watch. |
| opts.watchIgnore | string[] |
- List of paths and patterns to exclude from watching. See ignored option of chokidar. |
| opts.fileCollectParams | FileCollectionOptions |
- List of extensions to watch if opts.watchFiles is not given. |
# exports.watchParallelRun(mocha, opts, opts.watchFiles, opts.watchIgnore, fileCollectParams)
private method
Run Mocha in parallel "watch" mode
Parameters
| Name | Types | Description |
|---|---|---|
| mocha | Mocha |
- Mocha instance |
| opts | Object |
- Options |
| opts.watchFiles | string[] |
- List of paths and patterns to watch. If not provided all files with an extension included in fileCollectionParams.extension are watched. See first argument of chokidar.watch. |
| opts.watchIgnore | string[] |
- List of paths and patterns to exclude from watching. See ignored option of chokidar. |
| fileCollectParams | FileCollectionOptions |
- Parameters that control test |
# exports.watchRun(mocha, opts, opts.watchFiles, opts.watchIgnore, fileCollectParams)
private method
Run Mocha in "watch" mode
Parameters
| Name | Types | Description |
|---|---|---|
| mocha | Mocha |
- Mocha instance |
| opts | Object |
- Options |
| opts.watchFiles | string[] |
- List of paths and patterns to watch. If not provided all files with an extension included in fileCollectionParams.extension are watched. See first argument of chokidar.watch. |
| opts.watchIgnore | string[] |
- List of paths and patterns to exclude from watching. See ignored option of chokidar. |
| fileCollectParams | FileCollectionOptions |
- Parameters that control test file collection. See lib/cli/collect-files.js. |
# getWatchedFiles(watcher)
private method
Return the list of absolute paths watched by a Chokidar watcher.
Parameters
| Name | Types | Description |
|---|---|---|
| watcher | |
- Instance of a Chokidar watcher |
Returns
string[]
- List of absolute paths
# matcher()
# matchPattern(filePath, pattern, matchParent)
private method
Checks if the provided path matches with the path pattern.
Parameters
| Name | Types | Description |
|---|---|---|
| filePath | string |
The path to match. |
| pattern | PathPattern |
The path pattern for matching. |
| matchParent | boolean |
Treats the provided path as a match if it's a valid parent directory from the list of paths. |
# Context.retries(n)
private method
Set or get a number of allowed retries on failed tests
Parameters
| Name | Types | Description |
|---|---|---|
| n | number |
Returns
Context
self
# Context.runnable(runnable)
private method
Set or get the context Runnable to runnable.
Parameters
| Name | Types | Description |
|---|---|---|
| runnable | Runnable |
Returns
Context
context
# Context.slow(ms)
private method
Set or get test slowness threshold ms.
Parameters
| Name | Types | Description |
|---|---|---|
| ms | number |
Returns
Context
self
# Context.timeout(ms)
private method
Set or get test timeout ms.
Parameters
| Name | Types | Description |
|---|---|---|
| ms | number |
Returns
Context
self
# constants()
When Mocha throws exceptions (or rejects Promises), it attempts to assign a code property to the Error object, for easier handling. These are the potential values of code.
# INVALID_PLUGIN_DEFINITION()
To be thrown when a builtin or third-party plugin definition (the definition of mochaHooks) is invalid
# INVALID_PLUGIN_IMPLEMENTATION()
To be thrown when a user-defined plugin implementation (e.g., mochaHooks) is invalid
# createFatalError(message)
Creates an error object to be thrown when an unrecoverable error occurs.
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message to be displayed. |
# createForbiddenExclusivityError(mocha)
Creates an error object to be thrown when .only() is used with --forbid-only.
Parameters
| Name | Types | Description |
|---|---|---|
| mocha | Mocha |
- Mocha instance |
# createInvalidArgumentTypeError(message, argument, expected)
Creates an error object to be thrown when an argument did not use the supported type
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message to be displayed. |
| argument | string |
- Argument name. |
| expected | string |
- Expected argument datatype. |
# createInvalidArgumentValueError(message, argument, value, reason)
Creates an error object to be thrown when an argument did not use the supported value
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message to be displayed. |
| argument | string |
- Argument name. |
| value | string |
- Argument value. |
| reason | string |
- Why value is invalid. |
# createInvalidExceptionError(message)
Creates an error object to be thrown when an exception was caught, but the Error is falsy or undefined.
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message to be displayed. |
# createInvalidInterfaceError(message, ui)
Creates an error object to be thrown when the interface specified in the options was not found.
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message to be displayed. |
| ui | string |
- User-specified interface value. |
# createInvalidLegacyPluginError(message, pluginType, pluginId)
Dynamically creates a plugin-type-specific error based on plugin type
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message |
| pluginType | "reporter" |
"ui" |
| pluginId | string |
- Name/path of plugin, if any |
# createInvalidPluginDefinitionError(msg, pluginDef)
Creates an error object to be thrown when a plugin definition is invalid
Parameters
| Name | Types | Description |
|---|---|---|
| msg | string |
- Error message |
| pluginDef | PluginDefinition |
- Problematic plugin definition |
# createInvalidPluginError(message, pluginType, pluginId)
DEPRECATED. Use {@link createInvalidLegacyPluginError} instead Dynamically creates a plugin-type-specific error based on plugin type
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message |
| pluginType | "reporter" |
"interface" |
| pluginId | string |
- Name/path of plugin, if any |
# createInvalidPluginImplementationError(msg, opts, opts.pluginDef, opts.pluginImpl)
Creates an error object to be thrown when a plugin implementation (user code) is invalid
Parameters
| Name | Types | Description |
|---|---|---|
| msg | string |
- Error message |
| opts | Object |
- Plugin definition and user-supplied implementation |
| opts.pluginDef | PluginDefinition |
- Plugin Definition |
| opts.pluginImpl | * |
- Plugin Implementation (user-supplied) |
# createInvalidReporterError(message, reporter)
Creates an error object to be thrown when the reporter specified in the options was not found.
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message to be displayed. |
| reporter | string |
- User-specified reporter value. |
# createMissingArgumentError(message, argument, expected)
Creates an error object to be thrown when an argument is missing.
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message to be displayed. |
| argument | string |
- Argument name. |
| expected | string |
- Expected argument datatype. |
# createMochaInstanceAlreadyDisposedError(message, cleanReferencesAfterRun, instance)
Creates an error object to be thrown when a mocha object's run method is executed while it is already disposed.
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
The error message to be displayed. |
| cleanReferencesAfterRun | boolean |
the value of cleanReferencesAfterRun |
| instance | Mocha |
the mocha instance that throw this error |
# createMochaInstanceAlreadyRunningError(message)
Creates an error object to be thrown when a mocha object's run method is called while a test run is in progress.
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
The error message to be displayed. |
# createMultipleDoneError(runnable, originalErr)
Creates an error object to be thrown when done() is called multiple times in a test
Parameters
| Name | Types | Description |
|---|---|---|
| runnable | Runnable |
- Original runnable |
| originalErr | Error |
- Original error, if any |
# createNoFilesMatchPatternError(message, pattern)
Creates an error object to be thrown when no files to be tested could be found using specified pattern.
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message to be displayed. |
| pattern | string |
- User-specified argument value. |
# createTimeoutError(msg, timeout, file)
Creates an error object to be thrown when a runnable exceeds its allowed run time.
Parameters
| Name | Types | Description |
|---|---|---|
| msg | string |
- Error message |
| timeout | number |
- Timeout in ms |
| file | string |
- File, if given |
# createUnparsableFileError(message)
Creates an error object to be thrown when file is unparsable
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message to be displayed. |
# createUnsupportedError(message)
Creates an error object to be thrown when a behavior, option, or parameter is unsupported.
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
- Error message to be displayed. |
# deprecate(msg)
private method
Show a deprecation warning. Each distinct message is only displayed once. Ignores empty messages.
Parameters
| Name | Types | Description |
|---|---|---|
| msg | string |
- Warning to print |
# isMochaError(err)
Returns true if an error came out of Mocha. Can suffer from false negatives, but not false positives.
Parameters
| Name | Types | Description |
|---|---|---|
| err | * |
- Error, or anything |
# MOCHA_ERRORS()
private method
A set containing all string values of all Mocha error constants, for use by {@link isMochaError}.
# require()
# warn(msg)
private method
Show a generic warning. Ignores empty messages.
Parameters
| Name | Types | Description |
|---|---|---|
| msg | string |
- Warning to print |
# constructor(title, fn)
Initialize a new Hook with the given title and callback fn
Parameters
| Name | Types | Description |
|---|---|---|
| title | String |
|
| fn | Function |
# serialize()
private method
Returns an object suitable for IPC. Functions are represented by keys beginning with $$.
# bddInterface(suite)
BDD-style interface: describe('Array', function() { describe('#indexOf()', function() { it('should return -1 when not present', function() { // ... }); it('should return the index when present', function() { // ... }); }); });
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
Root suite. |
# context.describe()
Describe a "suite" with the given title and callback fn containing nested suites and/or tests.
# context.it()
Describe a specification or test-case with the given title and callback fn acting as a thunk.
# Test()
# after(name, fn)
Execute after running tests.
Parameters
| Name | Types | Description |
|---|---|---|
| name | string |
|
| fn | Function |
# afterEach(name, fn)
Execute after each test case.
Parameters
| Name | Types | Description |
|---|---|---|
| name | string |
|
| fn | Function |
# before(name, fn)
Execute before running tests.
Parameters
| Name | Types | Description |
|---|---|---|
| name | string |
|
| fn | Function |
# beforeEach(name, fn)
Execute before each test case.
Parameters
| Name | Types | Description |
|---|---|---|
| name | string |
|
| fn | Function |
# create(opts, opts.title, opts.fn, opts.pending, opts.file, opts.isOnly)
Creates a suite.
Parameters
| Name | Types | Description |
|---|---|---|
| opts | Object |
Options |
| opts.title | string |
Title of Suite |
| opts.fn | Function |
Suite Function (not always applicable) |
| opts.pending | boolean |
Is Suite pending? |
| opts.file | string |
Filepath where this Suite resides |
| opts.isOnly | boolean |
Is Suite exclusive? |
# module.exports(suites, context, mocha)
private method
Functions common to more than one interface.
Parameters
| Name | Types | Description |
|---|---|---|
| suites | Suite[] |
|
| context | Context |
|
| mocha | Mocha |
Returns
Object
An object containing common functions.
# only(opts)
Create an exclusive Suite; convenience function See docstring for create() below.
Parameters
| Name | Types | Description |
|---|---|---|
| opts | Object |
# only(mocha, test)
Exclusive test-case.
Parameters
| Name | Types | Description |
|---|---|---|
| mocha | Object |
|
| test | Function |
# runWithSuite(suite)
This is only present if flag --delay is passed into Mocha. It triggers root suite execution.
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
The root suite. |
Returns
Function
A function which runs the root suite
# shouldBeTested(suite)
private method
Check if the suite should be tested.
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
- suite to check |
# skip(opts)
Create a Suite, but skip it; convenience function See docstring for create() below.
Parameters
| Name | Types | Description |
|---|---|---|
| opts | Object |
# Suite()
# module.exports(suite)
Exports-style (as Node.js module) interface: exports.Array = { '#indexOf()': { 'should return -1 when the value is not present': function() { }, 'should return the correct index when the value is present': function() { } } };
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
Root suite. |
# context.test()
Describe a specification or test-case with the given title and callback fn acting as a thunk.
# qUnitInterface(suite)
QUnit-style interface: suite('Array'); test('#length', function() { var arr = [1,2,3]; ok(arr.length == 3); }); test('#indexOf()', function() { var arr = [1,2,3]; ok(arr.indexOf(1) == 0); ok(arr.indexOf(2) == 1); ok(arr.indexOf(3) == 2); }); suite('String'); test('#length', function() { ok('foo'.length == 3); });
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
Root suite. |
# Test()
# context.suite()
Describe a "suite" with the given title and callback fn containing nested suites and/or tests.
# context.test()
Describe a specification or test-case with the given title and callback fn acting as a thunk.
# module.exports(suite)
TDD-style interface: suite('Array', function() { suite('#indexOf()', function() { suiteSetup(function() { }); test('should return -1 when not present', function() { }); test('should return the index when present', function() { }); suiteTeardown(function() { }); }); });
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
Root suite. |
# Test()
# _runGlobalFixtures(fixtureFns, context)
private method
Run global fixtures sequentially with context context
Parameters
| Name | Types | Description |
|---|---|---|
| fixtureFns | MochaGlobalFixture[] |
- Fixtures to run |
| context | object |
- context object |
# delay()
# enableGlobalSetup(enabled)
Toggle execution of any global setup fixture(s)
Parameters
| Name | Types | Description |
|---|---|---|
| enabled | boolean |
- If false, do not run global setup fixture |
# enableGlobalTeardown(enabled)
Toggle execution of any global teardown fixture(s)
Parameters
| Name | Types | Description |
|---|---|---|
| enabled | boolean |
- If false, do not run global teardown fixture |
# exports.reporters()
# exports.Runner()
# globalSetup(setupFns)
Configures one or more global setup fixtures. If given no parameters, unsets any previously-set fixtures.
Parameters
| Name | Types | Description |
|---|---|---|
| setupFns | MochaGlobalFixture |
MochaGlobalFixture[] |
# globalTeardown(teardownFns)
Configures one or more global teardown fixtures. If given no parameters, unsets any previously-set fixtures.
Parameters
| Name | Types | Description |
|---|---|---|
| teardownFns | MochaGlobalFixture |
MochaGlobalFixture[] |
# lazyLoadFiles(enable)
Disables implicit call to {@link Mocha#loadFiles} in {@link Mocha#run}. This setting is used by watch mode, parallel mode, and for loading ESM files.
Parameters
| Name | Types | Description |
|---|---|---|
| enable | boolean |
- If true, disable eager loading of files in {@link Mocha#run} |
# Mocha(options)
Constructs a new Mocha instance with options.
Parameters
| Name | Types | Description |
|---|---|---|
| options | MochaOptions |
- Settings object. |
# Mocha._guardRunningStateTransition()
private method
Throws an error if mocha is in the wrong state to be able to transition to a "running" state.
# Mocha.addFile(file)
Parameters
| Name | Types | Description |
|---|---|---|
| file | string |
- Pathname of file to be loaded. |
# Mocha.allowUncaught(allowUncaught)
Enables or disables uncaught errors to propagate.
Parameters
| Name | Types | Description |
|---|---|---|
| allowUncaught | boolean |
- Whether to propagate uncaught errors. |
Returns
Mocha
this
# Mocha.asyncOnly(asyncOnly)
Forces all tests to either accept a done callback or return a promise.
Parameters
| Name | Types | Description |
|---|---|---|
| asyncOnly | boolean |
- Whether to force done callback or promise. |
Returns
Mocha
this
# Mocha.bail(bail)
Enables or disables bailing on the first failure.
Parameters
| Name | Types | Description |
|---|---|---|
| bail | boolean |
- Whether to bail on first error. |
# Mocha.checkLeaks(checkLeaks)
Enables or disables checking for global variables leaked while running tests.
Parameters
| Name | Types | Description |
|---|---|---|
| checkLeaks | boolean |
- Whether to check for global variable leaks. |
Returns
Mocha
this
# Mocha.cleanReferencesAfterRun(cleanReferencesAfterRun)
Enables or disables whether or not to dispose after each test run. Disable this to ensure you can run the test suite multiple times. If disabled, be sure to dispose mocha when you're done to prevent memory leaks.
Parameters
| Name | Types | Description |
|---|---|---|
| cleanReferencesAfterRun | boolean |
Returns
Mocha
this
# Mocha.color(color)
Enables or disables TTY color output by screen-oriented reporters.
Parameters
| Name | Types | Description |
|---|---|---|
| color | boolean |
- Whether to enable color output. |
Returns
Mocha
this
# Mocha.diff(diff)
Enables or disables reporter to include diff in test failure output.
Parameters
| Name | Types | Description |
|---|---|---|
| diff | boolean |
- Whether to show diff on failure. |
Returns
Mocha
this
# Mocha.dispose()
Manually dispose this mocha instance. Mark this instance as disposed and unable to run more tests. It also removes function references to tests functions and hooks, so variables trapped in closures can be cleaned by the garbage collector.
# Mocha.dryRun(dryRun)
Enables or disables running tests in dry-run mode.
Parameters
| Name | Types | Description |
|---|---|---|
| dryRun | boolean |
- Whether to activate dry-run mode. |
Returns
Mocha
this
# Mocha.failHookAffectedTests(failHookAffectedTests)
Reports tests as failed when they are skipped due to a hook failure.
Parameters
| Name | Types | Description |
|---|---|---|
| failHookAffectedTests | boolean |
- Whether to fail tests affected by hook failures. |
Returns
Mocha
this
# Mocha.failZero(failZero)
Fails test run if no tests encountered with exit-code 1.
Parameters
| Name | Types | Description |
|---|---|---|
| failZero | boolean |
- Whether to fail test run. |
Returns
Mocha
this
# Mocha.fgrep(str)
Sets grep filter after escaping RegExp special characters.
Parameters
| Name | Types | Description |
|---|---|---|
| str | string |
- Value to be converted to a regexp. |
# Mocha.forbidOnly(forbidOnly)
Causes tests marked only to fail the suite.
Parameters
| Name | Types | Description |
|---|---|---|
| forbidOnly | boolean |
- Whether tests marked only fail the suite. |
# Mocha.forbidPending(forbidPending)
Causes pending tests and tests marked skip to fail the suite.
Parameters
| Name | Types | Description |
|---|---|---|
| forbidPending | boolean |
- Whether pending tests fail the suite. |
# Mocha.fullTrace(fullTrace)
Displays full stack trace upon test failure.
Parameters
| Name | Types | Description |
|---|---|---|
| fullTrace | boolean |
- Whether to print full stacktrace upon failure. |
Returns
Mocha
this
# Mocha.global(global)
Specifies whitelist of variable names to be expected in global scope.
Parameters
| Name | Types | Description |
|---|---|---|
| global | String[] |
String |
Returns
Mocha
this
# Mocha.hasGlobalTeardownFixtures()
Returns true if one or more global teardown fixtures have been supplied.
# Mocha.inlineDiffs(inlineDiffs)
Enables or disables reporter to use inline diffs (rather than +/-) in test failure output.
Parameters
| Name | Types | Description |
|---|---|---|
| inlineDiffs | boolean |
- Whether to use inline diffs. |
Returns
Mocha
this
# Mocha.loadFiles(fn)
private method
Loads files prior to execution. Does not support ES Modules.
Parameters
| Name | Types | Description |
|---|---|---|
| fn | Function |
- Callback invoked upon completion. |
# Mocha.loadFilesAsync(options, options.esmDecorator)
Loads files prior to execution. Supports Node ES Modules.
Parameters
| Name | Types | Description |
|---|---|---|
| options | Object |
- Settings object. |
| options.esmDecorator | Function |
- Function invoked on esm module name right before importing it. By default will passthrough as is. |
# Mocha.passOnFailingTestSuite(passOnFailingTestSuite)
Fail test run if tests were failed.
Parameters
| Name | Types | Description |
|---|---|---|
| passOnFailingTestSuite | boolean |
- Whether to fail test run. |
Returns
Mocha
this
# Mocha.reporter(reporterName, reporterOptions)
Sets reporter to reporter, defaults to "spec".
Parameters
| Name | Types | Description |
|---|---|---|
| reporterName | String |
Reporter |
| reporterOptions | Object |
- Options used to configure the reporter. |
# Mocha.retries(retry)
Sets the number of times to retry failed tests.
Parameters
| Name | Types | Description |
|---|---|---|
| retry | number |
- Number of times to retry failed tests. |
Returns
Mocha
this
# Mocha.run(fn)
Runs root suite and invokes fn() when complete.
Parameters
| Name | Types | Description |
|---|---|---|
| fn | DoneCB |
- Callback invoked when test execution completed. |
# Mocha.slow(msecs)
Sets slowness threshold value.
Parameters
| Name | Types | Description |
|---|---|---|
| msecs | number |
- Slowness threshold value. |
Returns
Mocha
this
# Mocha.ui(ui)
Sets test UI name, defaults to "bdd".
Parameters
| Name | Types | Description |
|---|---|---|
| ui | string |
Function |
# Mocha.unloadFile(file)
private method
Removes a previously loaded file from Node's require cache.
Parameters
| Name | Types | Description |
|---|---|---|
| file | string |
- Pathname of file to be unloaded. |
# mochaStates()
private method
A Mocha instance is a finite state machine. These are the states it can be in.
# module.exports()
# parallelMode(enable)
Toggles parallel mode. Must be run before calling {@link Mocha#run}. Changes the Runner class to use; also enables lazy file loading if not already done so. Warning: when passed false and lazy loading has been enabled via any means (including calling parallelMode(true)), this method will not disable lazy loading. Lazy loading is a prerequisite for parallel mode, but parallel mode is not a prerequisite for lazy loading!
Parameters
| Name | Types | Description |
|---|---|---|
| enable | boolean |
- If true, enable; otherwise disable. |
# REFERENCES_CLEANED()
private method
Mocha instance is done running tests and references to test functions and hooks are cleaned. You can reset this state by unloading the test files.
# rootHooks(hooks)
Assigns hooks to the root suite
Parameters
| Name | Types | Description |
|---|---|---|
| hooks | MochaRootHookObject |
- Hooks to assign to root suite |
# runGlobalSetup(context)
Run any global setup fixtures sequentially, if any. This is automatically called by {@link Mocha#run} unless the runGlobalSetup option is false; see {@link Mocha#enableGlobalSetup}. The context object this function resolves with should be consumed by {@link Mocha#runGlobalTeardown}.
Parameters
| Name | Types | Description |
|---|---|---|
| context | object |
- Context object if already have one |
# runGlobalTeardown(context)
Run any global teardown fixtures sequentially, if any. This is automatically called by {@link Mocha#run} unless the runGlobalTeardown option is false; see {@link Mocha#enableGlobalTeardown}. Should be called with context object returned by {@link Mocha#runGlobalSetup}, if applicable.
Parameters
| Name | Types | Description |
|---|---|---|
| context | object |
- Context object if already have one |
# this._lazyLoadFiles()
private method
Whether or not to call {@link Mocha#loadFiles} implicitly when calling {@link Mocha#run}. If this is true, then it's up to the consumer to call {@link Mocha#loadFiles} or {@link Mocha#loadFilesAsync}.
# this._runnerClass()
private method
The class which we'll instantiate in {@link Mocha#run}. Defaults to {@link Runner} in serial mode; changes in parallel mode.
# this.isWorker()
private method
It's useful for a Mocha instance to know if it's running in a worker process. We could derive this via other means, but it's helpful to have a flag to refer to.
# constructor(opts)
Creates an underlying worker pool instance; determines max worker count
Parameters
| Name | Types | Description |
|---|---|---|
| opts | Partial<WorkerPoolOptions> |
- Options |
# optionsCache()
A mapping of Mocha Options objects to serialized values. This is helpful because we tend to same the same options over and over over IPC.
# resetOptionsCache()
private method
Resets internal cache of serialized options objects. For testing/debugging
# run(filepath, options)
private method
Adds a test file run to the worker pool queue for execution by a worker process. Handles serialization/deserialization.
Parameters
| Name | Types | Description |
|---|---|---|
| filepath | string |
- Filepath of test |
| options | MochaOptions |
- Options for Mocha instance |
# serializeJavascript()
# serializeOptions(opts)
private method
Given Mocha options object opts, serialize into a format suitable for transmission over IPC.
Parameters
| Name | Types | Description |
|---|---|---|
| opts | MochaOptions |
- Mocha options |
# stats()
private method
Returns stats about the state of the worker processes in the pool. Used for debugging.
# terminate(force)
private method
Terminates all workers in the pool.
Parameters
| Name | Types | Description |
|---|---|---|
| force | boolean |
- Whether to force-kill workers. By default, lets workers finish their current task before termination. |
# exports.unloadFile(file)
Deletes a file from the require cache.
Parameters
| Name | Types | Description |
|---|---|---|
| file | string |
- File |
# _bindSigIntListener(pool)
private method
Listen on Process.SIGINT; terminate pool if caught. Returns the listener for later call to process.removeListener().
Parameters
| Name | Types | Description |
|---|---|---|
| pool | BufferedWorkerPool |
- Worker pool |
# _createFileRunner(pool, options)
private method
Returns a mapping function to enqueue a file in the worker pool and return results of its execution.
Parameters
| Name | Types | Description |
|---|---|---|
| pool | BufferedWorkerPool |
- Worker pool |
| options | RunnerOptions |
- Mocha options |
# DEBUG_STATS_INTERVAL()
The interval at which we will display stats for worker processes in debug mode
# emitEvent(event, failureCount)
Emits event and sets BAILING state, if necessary.
Parameters
| Name | Types | Description |
|---|---|---|
| event | Object |
- Event having eventName, maybe data and maybe error |
| failureCount | number |
- Failure count |
# isParallelMode()
If this class is the Runner in use, then this is going to return true. For use by reporters.
# linkEvent(event)
Given an event, recursively find any objects in its data that have ID's, and create object references to already-seen objects.
Parameters
| Name | Types | Description |
|---|---|---|
| event | Object |
- Event having eventName, maybe data and maybe error |
# linkPartialObjects(value)
Toggle partial object linking behavior; used for building object references from unique ID's.
Parameters
| Name | Types | Description |
|---|---|---|
| value | boolean |
- If true, enable partial object linking, otherwise disable |
# ParallelBufferedRunner()
This Runner delegates tests runs to worker threads. Does not execute any {@link Runnable}s by itself!
# pool()
# run(callback, opts)
Runs Mocha tests by creating a thread pool, then delegating work to the worker threads. Each worker receives one file, and as workers become available, they take a file from the queue and run it. The worker thread execution is treated like an RPC--it returns a Promise containing serialized information about the run. The information is processed as it's received, and emitted to a {@link Reporter}, which is likely listening for these events.
Parameters
| Name | Types | Description |
|---|---|---|
| callback | Function |
- Called with an exit code corresponding to number of test failures. |
| opts | RunnerOptions |
- options |
# Runner()
# workerReporter(path)
Configures an alternate reporter for worker processes to use. Subclasses using worker processes should implement this.
Parameters
| Name | Types | Description |
|---|---|---|
| path | string |
- Absolute path to alternate reporter for worker processes to use |
# constructor(runner)
Calls {@link ParallelBuffered#createListeners}
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
# createListener(eventName)
Returns a new listener which saves event data in memory to {@link ParallelBuffered#events}. Listeners are indexed by eventName and stored in {@link ParallelBuffered#listeners}. This is a defensive measure, so that we don't a) leak memory or b) remove other listeners that may not be associated with this reporter. Subclasses could override this behavior.
Parameters
| Name | Types | Description |
|---|---|---|
| eventName | string |
- Name of event to create listener for |
# createListeners(runner)
Creates event listeners (using {@link ParallelBuffered#createListener}) for each reporter-relevant event emitted by a {@link Runner}. This array is drained when {@link ParallelBuffered#done} is called by {@link Runner#run}. Subclasses could override this behavior.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Runner instance |
# done(failures, callback)
Calls the {@link Mocha#run} callback (callback) with the test failure count and the array of {@link BufferedEvent} objects. Resets the array. This is called directly by Runner#run and should not be called by any other consumer. Subclasses could override this.
Parameters
| Name | Types | Description |
|---|---|---|
| failures | number |
- Number of failed tests |
| callback | Function |
- The callback passed to {@link Mocha#run}. |
# EVENT_NAMES()
List of events to listen to; these will be buffered and sent when Mocha#run is complete (via {@link ParallelBuffered#done}).
# ONCE_EVENT_NAMES()
Like {@link EVENT_NAMES}, except we expect these events to only be emitted by the Runner once.
# ParallelBuffered()
The ParallelBuffered reporter is used by each worker process in "parallel" mode, by default. Instead of reporting to STDOUT, etc., it retains a list of events it receives and hands these off to the callback passed into {@link Mocha#run}. That callback will then return the data to the main process.
# ...args(args)
Instantiates a new {@link SerializableWorkerResult}.
Parameters
| Name | Types | Description |
|---|---|---|
| args | ...any |
- Args to constructor |
# ...args(args)
In case you hated using new (I do).
Parameters
| Name | Types | Description |
|---|---|---|
| args | ...any |
- Args for {@link SerializableEvent#constructor}. |
# _deserializeError(value)
Used internally by {@link SerializableEvent.deserialize}; creates an Error from an Error-like (serialized) object
Parameters
| Name | Types | Description |
|---|---|---|
| value | Object |
- An Error-like value |
# _deserializeObject(parent, key)
Used internally by {@link SerializableEvent.deserialize}; recursively deserializes an object in-place.
Parameters
| Name | Types | Description |
|---|---|---|
| parent | object |
Array |
| key | string |
number |
# _serialize(pairs, parent, key)
Used internally by {@link SerializableEvent#serialize}.
Parameters
| Name | Types | Description |
|---|---|---|
| pairs | Array<object |
string> |
| parent | object |
- Some parent object |
| key | string |
- Key to inspect |
# constructor(events, failureCount)
Creates instance props; of note, the __type prop. Note that the failure count is redundant and could be derived from the list of events; but since we're already doing the work, might as well use it.
Parameters
| Name | Types | Description |
|---|---|---|
| events | SerializableEvent[] |
- Events to eventually serialize |
| failureCount | number |
- Failure count |
# constructor(eventName, originalValue, originalError)
Constructs a SerializableEvent, throwing if we receive unexpected data. Practically, events emitted from Runner have a minimum of zero (0) arguments-- (for example, {@link Runnable.constants.EVENT_RUN_BEGIN}) and a maximum of two (2) (for example, {@link Runnable.constants.EVENT_TEST_FAIL}, where the second argument is an Error). The first argument, if present, is a {@link Runnable}. This constructor's arguments adhere to this convention.
Parameters
| Name | Types | Description |
|---|---|---|
| eventName | string |
- A non-empty event name. |
| originalValue | any |
- Some data. Corresponds to extra arguments passed to EventEmitter#emit. |
| originalError | Error |
- An error, if there's an error. |
# deserialize(obj)
Deserializes a {@link SerializedWorkerResult} into something reporters can use; calls {@link SerializableEvent.deserialize} on each item in its events prop.
Parameters
| Name | Types | Description |
|---|---|---|
| obj | SerializedWorkerResult |
# deserialize(obj)
Deserialize value returned from a worker into something more useful. Does not return the same object.
Parameters
| Name | Types | Description |
|---|---|---|
| obj | SerializedEvent |
- Object returned from worker |
# deserialize(value)
"Deserializes" a "message" received over IPC. This could be expanded with other objects that need deserialization, but at present time we only care about {@link SerializableWorkerResult} objects.
Parameters
| Name | Types | Description |
|---|---|---|
| value | * |
- A "message" to deserialize |
# isSerializedWorkerResult(value)
Returns true if this is a {@link SerializedWorkerResult} or a {@link SerializableWorkerResult}.
Parameters
| Name | Types | Description |
|---|---|---|
| value | * |
- A value to check |
# Object.defineProperty()
Symbol-like value needed to distinguish when attempting to deserialize this object (once it's been received over IPC).
# Object.defineProperty()
The raw value. We don't want this value sent via IPC; making it non-enumerable will do that.
# require()
# SerializableEvent()
private method
Represents an event, emitted by a {@link Runner}, which is to be transmitted over IPC. Due to the contents of the event data, it's not possible to send them verbatim. When received by the main process--and handled by reporters--these objects are expected to contain {@link Runnable} instances. This class provides facilities to perform the translation via serialization and deserialization.
# SerializableWorkerResult()
private method
The serializable result of a test file run from a worker.
# serialize()
Serializes each {@link SerializableEvent} in our events prop; makes this object read-only.
# serialize()
Modifies this object in place (for theoretical memory consumption & performance reasons); serializes SerializableEvent#originalValue (placing the result in SerializableEvent#data) and SerializableEvent#error. Freezes this object. The result is an object that can be transmitted over IPC. If this quickly becomes unmaintainable, we will want to move towards immutable objects post-haste.
# serialize(value)
"Serializes" a value for transmission over IPC as a message. If value is an object and has a serialize() method, call that method; otherwise return the object and hope for the best.
Parameters
| Name | Types | Description |
|---|---|---|
| value | * |
- A value to serialize |
# bootstrap(argv)
Initializes some stuff on the first call to {@link run}. Handles --require and --ui. Does not handle --reporter, as only the Buffered reporter is used. This function only runs once per worker; it overwrites itself with a no-op before returning.
Parameters
| Name | Types | Description |
|---|---|---|
| argv | MochaOptions |
- Command-line options |
# run(filepath, serializedOptions)
Runs a single test file in a worker thread.
Parameters
| Name | Types | Description |
|---|---|---|
| filepath | string |
- Filepath of test file |
| serializedOptions | string |
- Serialized options. This string will be eval'd! |
# PendingError(message)
Initialize a new PendingError error with the given message.
Parameters
| Name | Types | Description |
|---|---|---|
| message | string |
# constructor(opts)
Initializes plugin names, plugin map, etc.
Parameters
| Name | Types | Description |
|---|---|---|
| opts | PluginLoaderOptions |
- Options |
# create(opts)
Constructs a {@link PluginLoader}
Parameters
| Name | Types | Description |
|---|---|---|
| opts | PluginLoaderOptions |
- Plugin loader options |
# finalize()
Call the finalize() function of each known plugin definition on the plugins found by [load()]{@link PluginLoader#load}. Output suitable for passing as input into {@link Mocha} constructor.
# load(requiredModule)
Inspects a module's exports for known plugins and keeps them in memory.
Parameters
| Name | Types | Description |
|---|---|---|
| requiredModule | * |
- The exports of a module loaded via --require |
# PluginLoader()
private method
Contains a registry of [plugin definitions]{@link PluginDefinition} and discovers plugin implementations in user-supplied code. - [load()]{@link #load} should be called for all required modules - The result of [finalize()]{@link #finalize} should be merged into the options for the [Mocha]{@link Mocha} constructor.
# register(pluginDef)
Register a plugin
Parameters
| Name | Types | Description |
|---|---|---|
| pluginDef | PluginDefinition |
- Plugin definition |
# Base()
# color(type, str)
private method
Color str with the given type, allowing colors to be disabled, as well as user-defined color schemes.
Parameters
| Name | Types | Description |
|---|---|---|
| type | string |
|
| str | string |
Returns
string
# colorLines(name, str)
private method
Colors lines for str, using the color name.
Parameters
| Name | Types | Description |
|---|---|---|
| name | string |
|
| str | string |
Returns
string
# constructor(runner, options)
Constructs a new Base reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# errorDiff(actual, expected)
private method
Returns character diff for err.
Parameters
| Name | Types | Description |
|---|---|---|
| actual | String |
|
| expected | String |
Returns
string
the diff
# exports.list(failures)
Outputs the given failures as a list.
Parameters
| Name | Types | Description |
|---|---|---|
| failures | Object[] |
- Each is Test instance with corresponding Error property |
# generateDiff(actual, expected)
Returns a diff between 2 strings with coloured ANSI output.
Parameters
| Name | Types | Description |
|---|---|---|
| actual | string |
|
| expected | string |
Returns
string
Diff
# getFullErrorStack(err, seen)
private method
Traverses err.cause and returns all stack traces
Parameters
| Name | Types | Description |
|---|---|---|
| err | Error |
|
| seen | Set<Error> |
Returns
FullErrorStack
# inlineDiff(actual, expected)
private method
Returns inline diff between 2 strings with coloured ANSI output.
Parameters
| Name | Types | Description |
|---|---|---|
| actual | String |
|
| expected | String |
Returns
string
Diff
# pad(str, len)
private method
Pads the given str to len.
Parameters
| Name | Types | Description |
|---|---|---|
| str | string |
|
| len | string |
Returns
string
# sameType(a, b)
private method
Checks that a / b have the same type.
Parameters
| Name | Types | Description |
|---|---|---|
| a | Object |
|
| b | Object |
Returns
boolean
# unifiedDiff(actual, expected)
private method
Returns unified diff between two strings with coloured ANSI output.
Parameters
| Name | Types | Description |
|---|---|---|
| actual | String |
|
| expected | String |
Returns
string
The diff.
# constructor(runner, options)
Constructs a new Doc reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# constructor(runner, options)
Constructs a new Dot reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# addCodeToggle(el, contents)
Adds code toggle functionality for the provided test's list element.
Parameters
| Name | Types | Description |
|---|---|---|
| el | HTMLLIElement |
|
| contents | string |
# constructor(runner, options)
Constructs a new HTML reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# hideSuitesWithout(classname)
Check for suites that do not have elements with classname, and hide them.
Parameters
| Name | Types | Description |
|---|---|---|
| classname | text |
# makeUrl(s)
Makes a URL, preserving querystring ("search") parameters.
Parameters
| Name | Types | Description |
|---|---|---|
| s | string |
Returns
string
A new URL.
# resultIndicator()
Stat item containing the root suite pass or fail indicator (hasFailures ? '✖' : '✓')
# text(el, contents)
Set an element's text contents.
Parameters
| Name | Types | Description |
|---|---|---|
| el | HTMLElement |
|
| contents | string |
# clean(test)
private method
Returns an object literal representation of test free of cyclic properties, etc.
Parameters
| Name | Types | Description |
|---|---|---|
| test | Test |
- Instance used as data source. |
Returns
Object
object containing pared-down test instance data
# constructor(runner, options)
Constructs a new JSONStream reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# writeEvent(event)
private method
Writes Mocha event to reporter output stream.
Parameters
| Name | Types | Description |
|---|---|---|
| event | unknown[] |
- Mocha event to be output. |
# clean(test)
private method
Return a plain-object representation of test free of cyclic properties etc.
Parameters
| Name | Types | Description |
|---|---|---|
| test | Object |
Returns
Object
# cleanCycles(obj)
private method
Replaces any circular references inside obj with '[object Object]'
Parameters
| Name | Types | Description |
|---|---|---|
| obj | Object |
Returns
Object
# constructor(runner, options)
Constructs a new JSON reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# errorJSON(err)
private method
Transform an Error object into a JSON object.
Parameters
| Name | Types | Description |
|---|---|---|
| err | Error |
Returns
Object
# constructor(runner, options)
Constructs a new Landing reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# constructor(runner, options)
Constructs a new List reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# constructor(runner, options)
Constructs a new Markdown reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# constructor(runner, options)
Constructs a new Min reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# constructor(runner, options)
Constructs a new Nyan reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# drawScoreboard()
private method
Draw the "scoreboard" showing the number of passes, failures and pending tests.
# rainbowify(str)
private method
Apply rainbow to the given str.
Parameters
| Name | Types | Description |
|---|---|---|
| str | string |
Returns
string
# constructor(runner, options)
Constructs a new Progress reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# constructor(runner, options)
Constructs a new Spec reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# constructor(runner, options)
Constructs a new TAP reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# createProducer(tapVersion)
private method
Returns a tapVersion-appropriate TAP producer instance, if possible.
Parameters
| Name | Types | Description |
|---|---|---|
| tapVersion | string |
- Version of TAP specification to produce. |
# println(format, varArgs)
private method
Writes newline-terminated formatted string to reporter output stream.
Parameters
| Name | Types | Description |
|---|---|---|
| format | string |
- printf-like format string |
| varArgs | ...* |
- Format string arguments |
# s(n, test)
Writes that test passed to reporter output stream.
Parameters
| Name | Types | Description |
|---|---|---|
| n | number |
- Index of test that passed. |
| test | Test |
- Instance containing test information. |
# title(test)
private method
Returns a TAP-safe title of test.
Parameters
| Name | Types | Description |
|---|---|---|
| test | Test |
- Test instance. |
Returns
String
title with any hash character removed
# writeEpilogue(stats)
Writes the summary epilogue to reporter output stream.
Parameters
| Name | Types | Description |
|---|---|---|
| stats | Object |
- Object containing run statistics. |
# writeFail(n, test)
Writes that test failed to reporter output stream.
Parameters
| Name | Types | Description |
|---|---|---|
| n | number |
- Index of test that failed. |
| test | Test |
- Instance containing test information. |
# writePending(n, test)
Writes that test was skipped to reporter output stream.
Parameters
| Name | Types | Description |
|---|---|---|
| n | number |
- Index of test that was skipped. |
| test | Test |
- Instance containing test information. |
# writePlan(ntests)
Writes the plan to reporter output stream.
Parameters
| Name | Types | Description |
|---|---|---|
| ntests | number |
- Number of tests that are planned to run. |
# constructor(runner, options)
Constructs a new XUnit reporter instance.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Instance triggers reporter actions. |
| options | Object |
- runner options |
# done(failures, fn)
Override done to close the stream (if it's a file).
Parameters
| Name | Types | Description |
|---|---|---|
| failures | |
|
| fn | Function |
# tag(name, attrs, close, content)
HTML tag helper.
Parameters
| Name | Types | Description |
|---|---|---|
| name | |
|
| attrs | |
|
| close | |
|
| content | |
Returns
string
# _timeoutError(ms)
private method
Instantiates a "timeout" error
Parameters
| Name | Types | Description |
|---|---|---|
| ms | number |
- Timeout (in milliseconds) |
# constructor(title, fn)
Initialize a new Runnable with the given title and callback fn. Additional properties, like getFullTitle() and slow(), can be viewed in the Runnable source.
Parameters
| Name | Types | Description |
|---|---|---|
| title | String |
|
| fn | Function |
# fullTitle()
Return the full title generated by recursively concatenating the parent's full title.
Returns
string
# globals(globals)
private method
Set or get a list of whitelisted globals for this test run.
Parameters
| Name | Types | Description |
|---|---|---|
| globals | string[] |
# run(fn)
private method
Run the test and invoke fn(err).
Parameters
| Name | Types | Description |
|---|---|---|
| fn | Function |
# slow(ms)
private method
Set or get slow ms.
Parameters
| Name | Types | Description |
|---|---|---|
| ms | number |
string |
Returns
Runnable|number
ms or Runnable instance.
# titlePath()
Return the title path generated by concatenating the parent's title path with the title.
Returns
string[]
# toValueOrError(value)
private method
Given value, return identity if truthy, otherwise create an "invalid exception" error and return that.
Parameters
| Name | Types | Description |
|---|---|---|
| value | * |
- Value to return, if present |
# constructor(suite, opts, opts.cleanReferencesAfterRun, opts.delay, opts.dryRun, opts.failZero, opts.failHookAffectedTests)
Initialize a Runner at the Root {@link Suite}, which represents a hierarchy of {@link Suite|Suites} and {@link Test|Tests}.
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
- Root suite |
| opts | Object |
- Settings object |
| opts.cleanReferencesAfterRun | boolean |
- Whether to clean references to test fns and hooks when a suite is done. |
| opts.delay | boolean |
- Whether to delay execution of root suite until ready. |
| opts.dryRun | boolean |
- Whether to report tests without running them. |
| opts.failZero | boolean |
- Whether to fail test run if zero tests encountered. |
| opts.failHookAffectedTests | boolean |
- Whether to fail all tests affected by hook failures. |
# createHookSkipError(hookTitle, hookError)
private method
Create an error object for a test that was skipped due to a hook failure.
Parameters
| Name | Types | Description |
|---|---|---|
| hookTitle | string |
- The title of the failed hook |
| hookError | * |
- The error from the failed hook (may not be an Error object) |
# EVENT_DELAY_END()
Emitted when delayed Root {@link Suite} execution is triggered by user via global.run()
# EVENT_RUN_BEGIN()
Emitted when Root {@link Suite} execution begins (all files have been parsed and hooks/tests are ready for execution)
# EVENT_TEST_FAIL()
Emitted when {@link Test} execution fails. Includes an err object of type Error.
# filterLeaks(ok, globals)
private method
Filter leaks with the given globals flagged as ok.
Parameters
| Name | Types | Description |
|---|---|---|
| ok | Array |
|
| globals | Array |
Returns
Array
# isError(err, err.message)
private method
Check if argument is an instance of Error object or a duck-typed equivalent.
Parameters
| Name | Types | Description |
|---|---|---|
| err | Object |
- object to check |
| err.message | string |
- error message |
# isParallelMode()
Returns true if Mocha is running in parallel mode. For reporters. Subclasses should return an appropriate value.
# Runner._addEventListener(target, eventName, fn)
private method
Replacement for target.on(eventName, listener) that does bookkeeping to remove them when this runner instance is disposed.
Parameters
| Name | Types | Description |
|---|---|---|
| target | EventEmitter |
- The EventEmitter |
| eventName | string |
- The event name |
| fn | string |
- Listener function |
# Runner._removeEventListener(target, eventName, listener)
private method
Replacement for target.removeListener(eventName, listener) that also updates the bookkeeping.
Parameters
| Name | Types | Description |
|---|---|---|
| target | EventEmitter |
- The EventEmitter |
| eventName | string |
- The event name |
| listener | function |
- Listener function |
# Runner._uncaught(err)
private method
Handle uncaught exceptions within runner. This function is bound to the instance as Runner#uncaught at instantiation time. It's intended to be listening on the Process.uncaughtException event. In order to not leak EE listeners, we need to ensure no more than a single uncaughtException listener exists per Runner. The only way to do this--because this function needs the context (and we don't have lambdas)--is to use Function.prototype.bind. We need strict equality to unregister and only unregister the one listener we set from the Process.uncaughtException event; would be poor form to just remove everything. See {@link Runner#run} for where the event listener is registered and unregistered.
Parameters
| Name | Types | Description |
|---|---|---|
| err | Error |
- Some uncaught error |
# Runner.dispose()
Removes all event handlers set during a run on this instance. Remark: this does not clean/dispose the tests or suites themselves.
# Runner.fail(test, err, force)
private method
Fail the given test. If test is a hook, failures work in the following pattern: - If bail, run corresponding after each and after hooks, then exit - Failed before hook skips all tests in a suite and subsuites, but jumps to corresponding after hook - Failed before each hook skips remaining tests in a suite and jumps to corresponding after each hook, which is run only once - Failed after hook does not alter execution order - Failed after each hook skips remaining tests in a suite and subsuites, but executes other after each hooks
Parameters
| Name | Types | Description |
|---|---|---|
| test | Runnable |
|
| err | Error |
|
| force | boolean |
- Whether to fail a pending test. |
# Runner.failAffectedTests(suite, hookError, hookTitle)
private method
Fail all tests that are affected by a hook failure. This is used when the failHookAffectedTests option is enabled.
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
- The suite containing the affected tests |
| hookError | Error |
- The error from the failed hook |
| hookTitle | string |
- The title of the failed hook |
# Runner.globals(arr)
Allow the given arr of globals.
Parameters
| Name | Types | Description |
|---|---|---|
| arr | Array |
Returns
Runner
Runner instance.
# Runner.grep(re, invert)
Run tests with full titles matching re. Updates runner.total with number of tests matched.
Parameters
| Name | Types | Description |
|---|---|---|
| re | RegExp |
|
| invert | boolean |
Returns
Runner
Runner instance.
# Runner.grepTotal(suite)
Returns the number of tests matching the grep search for the given suite.
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
Returns
number
# Runner.hook(name, fn)
private method
Run hook name callbacks and then invoke fn().
Parameters
| Name | Types | Description |
|---|---|---|
| name | string |
|
| fn | Function |
# Runner.hookDown(name, fn)
private method
Run 'beforeEach' hooks from top level down.
Parameters
| Name | Types | Description |
|---|---|---|
| name | String |
|
| fn | Function |
# Runner.hooks(name, suites, fn)
private method
Run hook name for the given array of suites in order, and callback fn(err, errSuite).
Parameters
| Name | Types | Description |
|---|---|---|
| name | string |
|
| suites | Array |
|
| fn | Function |
# Runner.hookUp(name, fn)
private method
Run 'afterEach' hooks from bottom up.
Parameters
| Name | Types | Description |
|---|---|---|
| name | String |
|
| fn | Function |
# Runner.immediately(fn)
private method
Wrapper for setImmediate, process.nextTick, or browser polyfill.
Parameters
| Name | Types | Description |
|---|---|---|
| fn | Function |
# Runner.linkPartialObjects(value)
Toggle partial object linking behavior; used for building object references from unique ID's. Does nothing in serial mode, because the object references already exist. Subclasses can implement this (e.g., ParallelBufferedRunner)
Parameters
| Name | Types | Description |
|---|---|---|
| value | boolean |
- If true, enable partial object linking, otherwise disable |
# Runner.parents()
private method
Return an array of parent Suites from closest to furthest.
Returns
Array
# Runner.run(fn, opts)
Run the root suite and invoke fn(failures) on completion.
Parameters
| Name | Types | Description |
|---|---|---|
| fn | Function |
- Callback when finished |
| opts | RunnerOptions |
- For subclasses |
# Runner.runSuite(suite, fn)
private method
Run the given suite and invoke the callback fn() when complete.
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
|
| fn | Function |
# Runner.runTest(fn)
private method
Run the current test and callback fn(err).
Parameters
| Name | Types | Description |
|---|---|---|
| fn | Function |
# Runner.runTests(suite, fn)
private method
Run tests in the given suite and invoke the callback fn() when complete.
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
|
| fn | Function |
# Runner.workerReporter(path)
Configures an alternate reporter for worker processes to use. Subclasses using worker processes should implement this.
Parameters
| Name | Types | Description |
|---|---|---|
| path | string |
- Absolute path to alternate reporter for worker processes to use |
# this._eventListeners()
# thrown2Error(thrown)
private method
Converts thrown non-extensible type into proper Error.
Parameters
| Name | Types | Description |
|---|---|---|
| thrown | * |
- Non-extensible type thrown by code |
Returns
Error
# createStatsCollector(runner)
private method
Provides stats such as test duration, number of tests passed / failed etc., by listening for events emitted by runner.
Parameters
| Name | Types | Description |
|---|---|---|
| runner | Runner |
- Runner instance |
# stats()
# _createHook(title, fn)
private method
Generic hook-creator.
Parameters
| Name | Types | Description |
|---|---|---|
| title | string |
- Title of hook |
| fn | Function |
- Hook callback |
# addSuite(suite)
private method
Add a test suite.
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
Returns
Suite
for chaining
# addTest(test)
private method
Add a test to this suite.
Parameters
| Name | Types | Description |
|---|---|---|
| test | Test |
Returns
Suite
for chaining
# afterAll(title, fn)
private method
Run fn(test[, done]) after running tests.
Parameters
| Name | Types | Description |
|---|---|---|
| title | string |
|
| fn | Function |
Returns
Suite
for chaining
# afterEach(title, fn)
private method
Run fn(test[, done]) after each test case.
Parameters
| Name | Types | Description |
|---|---|---|
| title | string |
|
| fn | Function |
Returns
Suite
for chaining
# appendOnlySuite(suite)
private method
Adds a suite to the list of subsuites marked only.
Parameters
| Name | Types | Description |
|---|---|---|
| suite | Suite |
# appendOnlyTest(test)
private method
Adds a test to the list of tests marked only.
Parameters
| Name | Types | Description |
|---|---|---|
| test | Test |
# bail(bail)
private method
Set or get whether to bail after first error.
Parameters
| Name | Types | Description |
|---|---|---|
| bail | boolean |
Returns
Suite|number
for chaining
# beforeAll(title, fn)
private method
Run fn(test[, done]) before running tests.
Parameters
| Name | Types | Description |
|---|---|---|
| title | string |
|
| fn | Function |
Returns
Suite
for chaining
# beforeEach(title, fn)
private method
Run fn(test[, done]) before each test case.
Parameters
| Name | Types | Description |
|---|---|---|
| title | string |
|
| fn | Function |
Returns
Suite
for chaining
# cleanReferences()
private method
Cleans up the references to all the deferred functions (before/after/beforeEach/afterEach) and tests of a Suite. These must be deleted otherwise a memory leak can happen, as those functions may reference variables from closures, thus those variables can never be garbage collected as long as the deferred functions exist.
# constructor(title, parentContext, isRoot)
Constructs a new Suite instance with the given title, ctx, and isRoot.
Parameters
| Name | Types | Description |
|---|---|---|
| title | string |
- Suite title. |
| parentContext | Context |
- Parent context instance. |
| isRoot | boolean |
- Whether this is the root suite. |
# create(parent, title)
Create a new Suite with the given title and parent Suite.
Parameters
| Name | Types | Description |
|---|---|---|
| parent | Suite |
- Parent suite (required!) |
| title | string |
- Title |
Returns
Suite
# eachTest(fn)
private method
Iterates through each suite recursively to find all tests. Applies a function in the format fn(test).
Parameters
| Name | Types | Description |
|---|---|---|
| fn | Function |
Returns
Suite
# EVENT_FILE_POST_REQUIRE()
Event emitted after a test file has been loaded. Not emitted in browser.
# EVENT_FILE_PRE_REQUIRE()
Event emitted before a test file has been loaded. In browser, this is emitted once an interface has been selected.
# EVENT_FILE_REQUIRE()
Event emitted immediately after a test file has been loaded. Not emitted in browser.
# fullTitle()
Return the full title generated by recursively concatenating the parent's full title.
Returns
string
# retries(n)
private method
Set or get number of times to retry a failed test.
Parameters
| Name | Types | Description |
|---|---|---|
| n | number |
string |
Returns
Suite|number
for chaining
# serialize()
private method
Returns an object suitable for IPC. Functions are represented by keys beginning with $$.
# slow(ms)
private method
Set or get slow ms or short-hand such as "2s".
Parameters
| Name | Types | Description |
|---|---|---|
| ms | number |
string |
Returns
Suite|number
for chaining
# timeout(ms)
private method
Set or get timeout ms or short-hand such as "2s".
Parameters
| Name | Types | Description |
|---|---|---|
| ms | number |
string |
Returns
Suite|number
for chaining
# titlePath()
Return the title path generated by recursively concatenating the parent's title path.
Returns
string[]
# constructor(title, fn)
Initialize a new Test with the given title and callback fn.
Parameters
| Name | Types | Description |
|---|---|---|
| title | String |
- Test title (required) |
| fn | Function |
- Test callback. If omitted, the Test is considered "pending" |
# serialize()
private method
Returns an minimal object suitable for transmission over IPC. Functions are represented by keys beginning with $$.
# filename(filename)
private method
A function accepting a test file path and returning the results of a test run
Parameters
| Name | Types | Description |
|---|---|---|
| filename | |
- File to run |
# filePath(filePath)
private method
Checks if the file path matches the allowed patterns.
Parameters
| Name | Types | Description |
|---|---|---|
| filePath | |
The file path to check. |
# options()
private method
Callback to be run before mocha.run() is called. Optionally, it can return a new Mocha instance.
# this(value)
A (sync) function to assert a user-supplied plugin implementation is valid. Defined in a {@link PluginDefinition}.
Parameters
| Name | Types | Description |
|---|---|---|
| value | |
Value to check |
# canonicalize(value, stack, typeHint)
private method
Return a new Thing that has the keys in sorted order. Recursive. If the Thing... - has already been seen, return string '[Circular]' - is undefined, return string '[undefined]' - is null, return value null - is some other primitive, return the value - is not a primitive or an Array, Object, or Function, return the value of the Thing's toString() method - is a non-empty Array, Object, or Function, return the result of calling this function again. - is an empty Array, Object, or Function, return the result of calling emptyRepresentation()
Parameters
| Name | Types | Description |
|---|---|---|
| value | * |
Thing to inspect. May or may not have properties. |
| stack | Array |
Stack of seen values |
| typeHint | string |
Type hint |
Returns
(Object|Array|Function|string|undefined)
# canonicalType(value)
private method
Takes some variable and asks Object.prototype.toString() what it thinks it is.
Parameters
| Name | Types | Description |
|---|---|---|
| value | * |
The value to test. |
# clamp(value, range)
Clamps a numeric value to an inclusive range.
Parameters
| Name | Types | Description |
|---|---|---|
| value | number |
- Value to be clamped. |
| range | number[] |
- Two element array specifying [min, max] range. |
# emptyRepresentation(value, typeHint)
private method
If a value could have properties, and has none, this function is called, which returns a string representation of the empty value. Functions w/ no properties return '[Function]' Arrays w/ length === 0 return '[]' Objects w/ no properties return '{}' All else: return result of value.toString()
Parameters
| Name | Types | Description |
|---|---|---|
| value | * |
The value to inspect. |
| typeHint | string |
The type of the value |
# exports.breakCircularDeps(inputObj)
Replaces any detected circular dependency with the string '[Circular]' Mutates original object
Parameters
| Name | Types | Description |
|---|---|---|
| inputObj | |
{*} |
# exports.clean(str)
Strip the function definition from str, and re-indent for pre whitespace.
Parameters
| Name | Types | Description |
|---|---|---|
| str | string |
Returns
string
# exports.createMap(obj)
Creates a map-like object.
Parameters
| Name | Types | Description |
|---|---|---|
| obj | ...* |
- Arguments to Object.assign(). |
# exports.defineConstants(obj)
Creates a read-only map-like object.
Parameters
| Name | Types | Description |
|---|---|---|
| obj | ...* |
- Arguments to Object.assign(). |
# exports.escape(html)
private method
Escape special characters in the given string of html.
Parameters
| Name | Types | Description |
|---|---|---|
| html | string |
Returns
string
# exports.getMochaID(obj)
Retrieves a Mocha ID from an object, if present.
Parameters
| Name | Types | Description |
|---|---|---|
| obj | * |
- Object |
# exports.isCI()
Checks if being ran in a CI environment. This uses the CI env variable, which is set by most popular CI providers. Some examples include: Github: https://docs.github.com/en/actions/reference/workflows-and-actions/variables Gitlab: https://docs.gitlab.com/ci/variables/predefined_variables/ CircleCI: https://circleci.com/docs/reference/variables/#built-in-environment-variables Bitbucket: https://support.atlassian.com/bitbucket-cloud/docs/variables-and-secrets/
# exports.isString(obj)
private method
Test if the given obj is type of string.
Parameters
| Name | Types | Description |
|---|---|---|
| obj | Object |
Returns
boolean
# exports.slug(str)
private method
Compute a slug from the given str.
Parameters
| Name | Types | Description |
|---|---|---|
| str | string |
Returns
string
# exports.stackTraceFilter()
# exports.stringify(value)
private method
Stringify value. Different behavior depending on type of value: - If value is undefined or null, return '[undefined]' or '[null]', respectively. - If value is not an object, function or array, return result of value.toString() wrapped in double-quotes. - If value is an empty object, function, or array, return result of function {@link emptyRepresentation}. - If value has properties, call {@link exports.canonicalize} on it, then return result of JSON.stringify().
Parameters
| Name | Types | Description |
|---|---|---|
| value | * |
Returns
string
# exports.uniqueID()
Creates a new unique identifier Does not create cryptographically safe ids. Trivial copy of nanoid/non-secure
# isBrowser()
private method
Returns true if Mocha is running in a browser. Checks for process.browser.
# jsonStringify(object, spaces, depth)
private method
like JSON.stringify but more sense.
Parameters
| Name | Types | Description |
|---|---|---|
| object | Object |
|
| spaces | number= |
|
| depth | number= |
# type(value)
private method
Returns a general type or data structure of a variable
Parameters
| Name | Types | Description |
|---|---|---|
| value | * |
The value to test. |
# bundlePreprocessor()
A special preprocessor that builds the main rollup bundle once and passes the bundle contents through on all later preprocessing request.
# framework()
The rollup framework that creates the initial logger and bundle file as well as prepends the bundle file to the karma file configuration.
# os()
This Karma plugin bundles all test files into a single file for browser testing. The plugin reads the file configuration from your Karma config and replaces them with a single bundle file instead. This is done by creating a rollup bundle file at a new path, then replacing all input file glob patterns with the bundle file. Then a bundle processor transform is added to handle that specific new file. The bundle preprocessor is the one actually calling rollup with a modified config that allows for multiple entry points for a single output bundle. This is an implementation that specifically solves Mocha's use case. It does not support watch mode. It possibly could be made reusable with more work and actual testing. We do not use karma-rollup-preprocessor because at the time of implementation it had a behavior where each individual file gets bundled separately with no deduplication of dependencies across bundles. This makes the operation slow to a point where it is actively blocking a responsive feedback loop in development. See issue at https://github.com/jlmakes/karma-rollup-preprocessor/issues/49 This plugin was based on the architecture of https://www.npmjs.com/package/karma-browserify in order to achieve the behavior where all input files get bundled into a single file. The code has been modified heavily to simplify and support rollup instead of browserify.
# loadAndExpect(filename, done)
Load the filename using an ESM-only loader and expect things to work
Parameters
| Name | Types | Description |
|---|---|---|
| filename | string |
Name of the file to load |
| done | Function |
A Mocha done callback for when the test ends |
# loadAndExpect(filename, done)
Runs exec on an ESM setup for the given file
Parameters
| Name | Types | Description |
|---|---|---|
| filename | string |
Path to the file to load |
| done | Function |
A Mocha done callback for when the test ends |
# getDiffs(output)
Returns an array of diffs corresponding to exceptions thrown from specs, given the plaintext output (-C) of a mocha run.
Parameters
| Name | Types | Description |
|---|---|---|
| output | string |
returns {string[]} |
# getExpectedOutput()
Returns content of test/integration/fixtures/diffs/output, post-processed for consumption by tests.
# context.test()
Describes a specification or test-case with the given title and callback fn acting as a thunk.
# it()
This file should only generate one failure per spec despite the fact that Mocha is capable of detecting two distinct exceptions during test execution.
# it()
This file should generate only one failure per spec for the thrown error. It should not report misleading 'multiple calls to done()'.
# copyFixture(fixtureName, dest)
Synchronously copy a fixture to the given destination file path. Creates parent directories of the destination path if necessary.
Parameters
| Name | Types | Description |
|---|---|---|
| fixtureName | string |
- Relative path from __dirname to fixture, or absolute path |
| dest | * |
- Destination directory |
# createSubprocess(args, done, opts, opts.fork)
Creates a subprocess and calls callback done when it has exited. This is the most low-level function and should not be exported.
Parameters
| Name | Types | Description |
|---|---|---|
| args | string[] |
- Path to executable and arguments |
| done | RawResultCallback |
- Callback |
| opts | Object |
string |
| opts.fork | boolean |
- If true, use child_process.fork instead |
# defaultArgs(args)
Creates arguments loading a default fixture if none provided - The --no-color arg is always used (color output complicates testing STDOUT) - Unless --bail or --no-bail is set, use --no-bail. This enables using --bail (if desired) from the command-line when running our integration test suites without stepping on the toes of subprocesses. - Unless --parallel or --no-parallel is set, use --no-parallel. We assume the test suite is already running in parallel--and there's no point in trying to run a single test fixture in parallel. - The {@link DEFAULT_FIXTURE} file is used if no arguments are provided.
Parameters
| Name | Types | Description |
|---|---|---|
| args | string[] |
* |
# getSummary(res)
Parses some mocha reporter output and returns a summary based on the "epilogue"
Parameters
| Name | Types | Description |
|---|---|---|
| res | string |
- Typically output of STDOUT from the 'spec' reporter |
# invokeMocha(args, done, opts)
Invoke mocha with default arguments. Calls done upon exit. Does not accept a fixture path. Good for testing error conditions. This is low-level, and you likely want {@link runMocha} or even {@link runMochaJSON} if you are running test fixtures.
Parameters
| Name | Types | Description |
|---|---|---|
| args | string[] |
RawResultCallback |
| done | RawResultCallback |
Object |
| opts | Object |
- Options |
# invokeMochaAsync(args, opts)
Invokes the mocha binary with the given arguments. Returns the child process and a promise for the results of running the command. The promise resolves when the child process exits. The result includes the raw string output, as well as exit code. By default, STDERR is ignored. Pass {stdio: 'pipe'} as opts if you want it as part of the result output.
Parameters
| Name | Types | Description |
|---|---|---|
| args | string[] |
- Array of args |
| opts | Object |
- Opts for spawn() |
# invokeNode(args, done, opts)
Invokes subprocess with currently-running node. Useful for running certain fixtures as scripts.
Parameters
| Name | Types | Description |
|---|---|---|
| args | string[] |
RawResultCallback |
| done | RawResultCallback |
Object |
| opts | Object |
- Options |
# mocha()
# mocha.on()
Emulate node's exit code for fatal signal. Allows tests to see the same exit code as the mocha cli.
# replaceFileContents(filepath, pattern, replacement)
Synchronously replace all substrings matched by pattern with replacement in the contents of file at filepath
Parameters
| Name | Types | Description |
|---|---|---|
| filepath | string |
- Path to file |
| pattern | RegExp |
string |
| replacement | string |
- Replacement |
# resolveFixturePath(fixture)
Given a fixture "name" (a relative path from ${__dirname}/fixtures), with or without extension, or an absolute path, resolve a fixture filepath
Parameters
| Name | Types | Description |
|---|---|---|
| fixture | string |
- Fixture name |
# runMocha(fixturePath, args, done, opts)
Invokes the mocha binary for the given fixture with color output disabled. Accepts an array of additional command line args to pass. The callback is invoked with a summary of the run, in addition to its output. The summary includes the number of passing, pending, and failing tests, as well as the exit code. Useful for testing different reporters. By default, STDERR is ignored. Pass {stdio: 'pipe'} as opts if you want it. Example response: { pending: 0, passing: 0, failing: 1, code: 1, output: '...' }
Parameters
| Name | Types | Description |
|---|---|---|
| fixturePath | string |
- Path to fixture .js file |
| args | string[] |
SummarizedResultCallback |
| done | SummarizedResultCallback |
Object |
| opts | Object |
- Options for spawn() |
# runMochaAsync(fixturePath, args, opts)
If you need more granular control, try {@link invokeMochaAsync} instead. Like {@link runMocha}, but returns a Promise.
Parameters
| Name | Types | Description |
|---|---|---|
| fixturePath | string |
- Path to (or name of, or basename of) fixture file |
| args | Options |
- Command-line arguments to the mocha executable |
| opts | Object |
- Options for child_process.spawn. |
# runMochaJSON(fixturePath, args, done, opts)
Invokes the mocha executable for the given fixture using the json reporter, calling callback done with parsed output. Use when you expect mocha not to fail (test failures OK); the output from the json reporter--and thus the entire subprocess--must be valid JSON! By default, STDERR is ignored. Pass {stdio: 'pipe'} as opts if you want it.
Parameters
| Name | Types | Description |
|---|---|---|
| fixturePath | string |
- Path from __dirname__ |
| args | string[] |
JSONResultCallback |
| done | JSONResultCallback |
Object |
| opts | Object |
- Opts for spawn() |
# runMochaJSONAsync(fixturePath, args, opts)
Like {@link runMochaJSON}, but returns a Promise.
Parameters
| Name | Types | Description |
|---|---|---|
| fixturePath | string |
- Path to (or name of, or basename of) fixture file |
| args | Options |
- Command-line args |
| opts | Object |
- Options for child_process.spawn |
# runMochaWatchAsync(args, opts, change)
Runs the mocha executable in watch mode calls change and returns the raw result. The function starts mocha with the given arguments and --watch and waits until the first test run has completed. Then it calls change and waits until the second test run has been completed. Mocha is killed and the result is returned. On Windows, this will call child_process.fork() instead of spawn(). Exit code will always be 0
Parameters
| Name | Types | Description |
|---|---|---|
| args | string[] |
- Array of argument strings |
| opts | object |
string |
| change | Function |
- A potentially Promise-returning callback to execute which will change a watched file |
# runMochaWatchJSONAsync(args, opts, change)
Runs the mocha executable in watch mode calls change and returns the JSON result. The function starts mocha with the given arguments and --watch and waits until the first test run has completed. Then it calls change and waits until the second test run has been completed. Mocha is killed and the result is returned. On Windows, this will call child_process.fork() instead of spawn(). Exit code will always be 0
Parameters
| Name | Types | Description |
|---|---|---|
| args | string[] |
- Array of argument strings |
| opts | object |
string |
| change | Function |
- A potentially Promise-returning callback to execute which will change a watched file |
# SPLIT_DOT_REPORTER_REGEXP()
regular expression used for splitting lines based on new line / dot symbol.
# toJSONResult(result)
Coerce output as returned by _spawnMochaWithListeners using JSON reporter into a JSONResult as recognized by our custom unexpected assertions
Parameters
| Name | Types | Description |
|---|---|---|
| result | RawResult |
- Raw stdout from Mocha run using JSON reporter |
# touchFile(filepath)
Synchronously touch a file. Creates the file and all its parent directories if necessary.
Parameters
| Name | Types | Description |
|---|---|---|
| filepath | string |
- Path to file |
# runExit(shouldExit, behavior)
Returns a test that executes Mocha in a subprocess with either --exit, --no-exit, or default behavior.
Parameters
| Name | Types | Description |
|---|---|---|
| shouldExit | boolean |
- Expected result; true if Mocha should have force-killed the process. |
| behavior | "enabled" |
"disabled" |
# assertReporterOutputEquality(reporter)
Many (but not all) reporters can use this assertion to compare output of serial vs. parallel
Parameters
| Name | Types | Description |
|---|---|---|
| reporter | string |
- Reporter name |
# checkProcessExists(pid, options, options.root)
Check if a process exists using ps-list
Parameters
| Name | Types | Description |
|---|---|---|
| pid | number |
- Process ID to check |
| options | Object |
- Options object |
| options.root | boolean |
- Include the PID itself in results |
# compareReporters(reporter)
Run a test fixture with the same reporter in both parallel and serial modes, returning both outputs for comparison
Parameters
| Name | Types | Description |
|---|---|---|
| reporter | string |
- Reporter name |
# getChildPids(pid, options, options.root)
Get child processes of a given PID using ps-list
Parameters
| Name | Types | Description |
|---|---|---|
| pid | number |
- Parent process ID |
| options | Object |
- Options object |
| options.root | boolean |
- Include the parent PID in results |
# waitForChildPids(pid)
Polls a process for its list of children PIDs. Returns the first non-empty list found
Parameters
| Name | Types | Description |
|---|---|---|
| pid | number |
- Process PID |
# cleanup()
# setupHookTest(hookName)
Helper for setting up hook tests
Parameters
| Name | Types | Description |
|---|---|---|
| hookName | string |
name of hook to test |
Returns
function
# tempDir()
# it()
# extractHookOutputFromResult(res)
Extracts root hook log messages from run results root-hook-defs-* fixtures are root hook plugins which call console.log() for verification that they have been run.
Parameters
| Name | Types | Description |
|---|---|---|
| res | RawResult |
- result of invokeMochaAsync() |
# runMochaForHookOutput(args, opts)
Helper to call Mocha and pipe the result through extractHookOutputFromResult
Parameters
| Name | Types | Description |
|---|---|---|
| args | * |
- args for invokeMochaAsync |
| opts | * |
- opts for invokeMochaAsync |
# describe()
Order of priority: 1. Command-line args 2. MOCHA_OPTIONS environment variable 3. RC file (.mocharc.js, .mocharc.ya?ml, mocharc.json) 4. mocha prop of package.json 5. default rc
# rewiremock.proxy()
# runner()
# createMockRunner(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2)
Creates a mock runner object.
Parameters
| Name | Types | Description |
|---|---|---|
| runStr | string |
- argument that defines the runnerEvent |
| ifStr1 | string |
- runner event |
| ifStr2 | (string |
null) |
| ifStr3 | (string |
null) |
| arg1 | (* |
null) |
| arg2 | (* |
null) |
Returns
Object
mock runner instance
# createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2)
Creates an event handler function to be used by the runner.
Parameters
| Name | Types | Description |
|---|---|---|
| runStr | string |
- argument that defines the runnerEvent |
| ifStr1 | string |
- runner event |
| ifStr2 | (string |
null) |
| ifStr3 | (string |
null) |
| arg1 | (* |
null) |
| arg2 | (* |
null) |
Returns
Function
event handler for the requested runner events
# createRunReporterFunction(ReporterClass)
Creates closure with reference to the reporter class constructor.
Parameters
| Name | Types | Description |
|---|---|---|
| ReporterClass | Function |
- Reporter class constructor |
Returns
createRunReporterFunction~runReporter
# runReporter(extensions, runner, options, tee)
Run reporter using stream reassignment to capture output.
Parameters
| Name | Types | Description |
|---|---|---|
| extensions | object |
- Any extra properties to add to the instance. |
| runner | Runner |
- Mock instance |
| options | Object |
- Reporter configuration settings |
| tee | boolean |
- Whether to echo output to screen |
Returns
string[]
Lines of output written to `stdout`