mocha (master) doxdox documentation

simple, flexible, fun test framework

# disableTimeouts(value)

Given option/command value, disable timeouts if applicable

Parameters

Name Types Description
value string - Value to check

# require()

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

# Date()

Save timer references to avoid Sinon interfering (see GH-237).

# global.Mocha()

Expose mocha.

# mocha()

Create a Mocha instance.

Returns

undefined

# Mocha.process()

Expose the process shim. https://github.com/mochajs/mocha/pull/916

# mocha.run()

Run mocha, returning the Runner.

# Mocha.Runner.immediately()

High-performance override of Runner.immediately.

# mocha.setup()

Setup mocha with the given setting options.

# 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.listenerCount()

Implements listenerCount for 'uncaughtException'.

# process.on()

Implements uncaughtException listener.

# process.removeListener()

Remove uncaughtException listener. Revert to original onerror handler if previously defined.

# process.stdout()

Shim process.stdout.

# module.exports()

Loads files from disk (see FILES above) to be shown as data. Used for embedding sources directly into pages

# API_ENDPOINT()

The OC API endpoint

# BLOCKED_CATEGORIES()

Add a few Categories exposed by Open Collective to help moderation

# BLOCKED_STRINGS()

In addition to the blocklist, any account slug matching this regex will not be displayed on the website.

# getAllOrders(slug)

Retrieves donation data from OC Handles pagination

Parameters

Name Types Description
slug string - Collective slug to get donation data from

# module.exports()

Return the output of mocha --help for display

# addSauceLabsTestName(testName, cfg)

Adds a name for the tests, reflected in SauceLabs' UI. Returns new Karma config. Does not add a test name if the sauceLabs prop of cfg is falsy (which would imply that we're not running tests on SauceLabs).

Parameters

Name Types Description
testName string - SauceLabs test name
cfg object - Karma config.

# addSauceTests(cfg, sauceLabs)

Adds Saucelabs-specific config to a Karma config object. If sauceLabs parameter is falsy, just return a clone of the cfg parameter.

Parameters

Name Types Description
cfg object - Karma config
sauceLabs object - SauceLabs config

# addStandardDependencies(cfg)

Returns a new Karma config containing standard dependencies for our tests. Most suites use this.

Parameters

Name Types Description
cfg object - Karma config

# 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 object - Karma config
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 object - Karma config.
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)

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.init()

private method

Exports Yargs commands

# 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

# fs()

private method

Responsible for loading / finding Mocha's "rc" files.

# parsers()

Parsers for various config filetypes. Each accepts a filepath and returns an object (but could throw)

# fs()

private method

Command module for "init" command

# 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.

# debugFlags()

private method

These flags are considered "debug" flags.

# 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.

# exports.ONE_AND_DONE_ARGS()

private method

A Set of all one-and-done options

# exports.ONE_AND_DONES()

private method

Handlers for one-and-done options

# 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.

# 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. RC file (.mocharc.c?js, .mocharc.ya?ml, mocharc.json) 3. mocha prop of package.json 4. default configuration (lib/mocharc.json) If a {@link module:lib/cli/one-and-dones.ONE_AND_DONE_ARGS "one-and-done" option} is present in the argv array, no external config files will be read.

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

# YARGS_PARSER_CONFIG()

private method

Base yargs parser configuration

# exitMocha(code)

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
code number - Exit code; typically # of failures

# exitMochaLater(code)

private method

Exits Mocha when tests + code under test has finished execution (default)

Parameters

Name Types Description
code 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, opts)

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
opts Options - 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()

private method

Helper scripts for the run command

# parallelRun(mocha, options, fileCollectParams)

private method

Collect files and run tests (using BufferedRunner). This is async for consistency.

Parameters

Name Types Description
mocha Mocha - Mocha instance
options Options - 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, opts.exit, fileCollectParams)

private method

Collect and load test files, then run mocha instance.

Parameters

Name Types Description
mocha Mocha - Mocha instance
opts Options - Command line options
opts.exit boolean - Whether or not to force-exit after tests are complete
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.isMochaFlag(flag)

private method

Returns true if the provided flag is known to Mocha.

Parameters

Name Types Description
flag string - Flag to check

# TYPES()

private method

Dictionary of yargs option types to list of options having said type

# GROUPS()

Logical option groups

# symbols()

private method

Definition for Mocha's default ("run tests") command

# blastCache(watcher)

private method

Blast all of the watched files out of require.cache

Parameters

Name Types Description
watcher FSWatcher - chokidar FSWatcher

# 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.

# eraseLine()

private method

Erases the line on stdout

# 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

# hideCursor()

private method

Hide the cursor.

# showCursor()

private method

Show the cursor.

# Context()

private method

Initialize a new Context.

# 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.skip()

private method

Mark a test as skipped.

# 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

# module.exports()

Expose Context.

# 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.

# 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, filename)

Creates an error object to be thrown when file is unparsable

Parameters

Name Types Description
message string - Error message to be displayed.
filename string - File name

# 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

# emitWarning()

process.emitWarning or a polyfill

# FATAL()

An unrecoverable error.

# FORBIDDEN_EXCLUSIVITY()

Use of only() w/ --forbid-only results in this error.

# INSTANCE_ALREADY_DISPOSED()

Invalid state transition occurring in Mocha instance

# INSTANCE_ALREADY_RUNNING()

Invalid state transition occurring in Mocha instance

# INVALID_ARG_TYPE()

The type of an argument to a function call is invalid

# INVALID_ARG_VALUE()

The value of an argument to a function call is invalid

# INVALID_EXCEPTION()

Something was thrown, but it wasn't an Error

# INVALID_INTERFACE()

An interface (e.g., Mocha.interfaces) is unknown or invalid

# 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

# INVALID_REPORTER()

A reporter (.e.g, Mocha.reporters) is unknown or invalid

# 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}.

# MULTIPLE_DONE()

done() was called twice in a Test or Hook callback

# NO_FILES_MATCH_PATTERN()

No files matched the pattern provided by the user

# TIMEOUT()

When a runnable exceeds its allowed run time.

# UNPARSABLE_FILE()

Input file is not able to be parsed

# UNSUPPORTED()

Known, but unsupported behavior of some kind

# warn(msg)

private method

Show a generic warning. Ignores empty messages.

Parameters

Name Types Description
msg string - Warning to print

# Hook(title, fn)

Initialize a new Hook with the given title and callback fn

Parameters

Name Types Description
title String
fn Function

# Hook.error(err)

Get or set the test err.

Parameters

Name Types Description
err Error

Returns

Error

# Hook.reset()

Resets the state for a next run.

# inherits()

Inherit from Runnable.prototype.

# module.exports()

Expose Hook.

# 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.describe.only()

Exclusive suite.

# context.it()

Describe a specification or test-case with the given title and callback fn acting as a thunk.

# context.it.only()

Exclusive test-case.

# context.xdescribe()

Pending describe.

# context.xit()

Pending test case.

# 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

# skip(title)

Pending test case.

Parameters

Name Types Description
title string

# 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.suite()

Describe a "suite" with the given title.

# context.suite.only()

Exclusive Suite.

# context.test()

Describe a specification or test-case with the given title and callback fn acting as a thunk.

# context.test.only()

Exclusive test-case.

# 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.

# context.suite()

Describe a "suite" with the given title and callback fn containing nested suites and/or tests.

# context.suite.only()

Exclusive test-case.

# context.suite.skip()

Pending suite.

# context.test()

Describe a specification or test-case with the given title and callback fn acting as a thunk.

# context.test.only()

Exclusive test-case.

# 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.

# _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()

# DISPOSED()

private method

Mocha instance is disposed and can no longer be used.

# 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()

# exports.utils()

private method

Expose internals.

# 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[]

# hasGlobalSetupFixtures()

Returns true if one or more global setup fixtures have been supplied.

# INIT()

private method

Initial state of the mocha instance

# 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, options.allowUncaught, options.asyncOnly, options.bail, options.checkLeaks, options.color, options.delay, options.diff, options.dryRun, options.failZero, options.fgrep, options.forbidOnly, options.forbidPending, options.fullTrace, options.global, options.grep, options.inlineDiffs, options.invert, options.noHighlighting, options.reporter, options.reporterOption, options.retries, options.slow, options.timeout, options.ui, options.parallel, options.jobs, options.rootHooks, options.require, options.isWorker)

Constructs a new Mocha instance with options.

Parameters

Name Types Description
options Object - Settings object.
options.allowUncaught boolean - Propagate uncaught errors?
options.asyncOnly boolean - Force done callback or promise?
options.bail boolean - Bail after first test failure?
options.checkLeaks boolean - Check for global variable leaks?
options.color boolean - Color TTY output from reporter?
options.delay boolean - Delay root suite execution?
options.diff boolean - Show diff on failure?
options.dryRun boolean - Report tests without running them?
options.failZero boolean - Fail test run if zero tests?
options.fgrep string - Test filter given string.
options.forbidOnly boolean - Tests marked only fail the suite?
options.forbidPending boolean - Pending tests fail the suite?
options.fullTrace boolean - Full stacktrace upon failure?
options.global string[] - Variables expected in global scope.
options.grep RegExp string
options.inlineDiffs boolean - Display inline diffs?
options.invert boolean - Invert test filter matches?
options.noHighlighting boolean - Disable syntax highlighting?
options.reporter string constructor
options.reporterOption Object - Reporter settings object.
options.retries number - Number of times to retry failed tests.
options.slow number - Slow threshold value.
options.timeout number string
options.ui string - Interface name.
options.parallel boolean - Run jobs in parallel.
options.jobs number - Max number of worker processes for parallel runs.
options.rootHooks MochaRootHookObject - Hooks to bootstrap the root suite with.
options.require string[] - Pathname of rootHooks plugin for parallel runs.
options.isWorker boolean - Should be true if Mocha process is running in a worker process.

# 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.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.grep(re)

Parameters

Name Types Description
re RegExp 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.invert()

Inverts grep matches.

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.noHighlighting()

Disables syntax highlighting (in browser).

Returns

Mocha

this

# Mocha.reporter(reporterName, reporterOptions)

Sets reporter to reporter, defaults to "spec".

Parameters

Name Types Description
reporterName String Function
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.timeout(msecs)

Parameters

Name Types Description
msecs number string

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.

# Mocha.unloadFiles()

Unloads files from Node's require cache.

# mochaStates()

private method

A Mocha instance is a finite state machine. These are the states it can be in.

# Object.defineProperty()

Mocha version as specified by "package.json".

# 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

# RUNNING()

private method

Mocha instance is running tests

# 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.

# utils.isBrowser()

To require local UIs and reporters when running in node.

# ...args()

private method

Instantiates a {@link WorkerPool}.

# BufferedWorkerPool()

private method

A wrapper around a third-party worker pool implementation.

# 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 Options - Options for Mocha instance

# serializeOptions(opts)

private method

Given Mocha options object opts, serialize into a format suitable for transmission over IPC.

Parameters

Name Types Description
opts Options - 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.

# WORKER_POOL_DEFAULT_OPTS()

These options are passed into the workerpool module.

# 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 Options - Mocha options

# DEBUG_STATS_INTERVAL()

The interval at which we will display stats for worker processes in debug mode

# debugInterval()

This is an interval that outputs stats about the worker pool every so often

# DENY_OPTIONS()

List of options to not serialize for transmission to workers

# 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, opts.files, opts.options)

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 Object - options
opts.files string[] - Files to run
opts.options Options - command-line options

# sigIntListener()

Listener on Process.SIGINT which tries to cleanly terminate the worker pool.

# 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}).

# module.exports()

Serializable event data from a Runner. Keys of the data property beginning with __ will be converted into a function which returns the value upon deserialization.

# 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 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.

# this.events()

Retained list of events emitted from the {@link Runner} instance.

# this.listeners()

Map of Runner event names to listeners (for later teardown)

# ...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, seenObjects)

Used internally by {@link SerializableEvent#serialize}.

Parameters

Name Types Description
pairs Array<object string>
parent object - Some parent object
key string - Key to inspect
seenObjects WeakSet<Object> - For avoiding circular references

# 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 minumum 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()

An error, if present.

# Object.defineProperty()

The raw value. We don't want this value sent via IPC; making it non-enumerable will do that.

# 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

# this.eventName()

The event name.

# this.events()

All relevant events emitted from the {@link Runner}.

# this.failureCount()

The number of failures in this run

# 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 Options - 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!

# module.exports()

# Pending(message)

Initialize a new Pending 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

# MochaPlugins()

Built-in plugin definitions.

# 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

# this.ignoredExportNames()

Set of ignored plugins by export name

# this.knownExportNames()

Cache of known exportName values for checking conflicts

# this.knownOptionNames()

Cache of known optionName values for checking conflicts

# this.loaded()

Map of user-supplied plugin implementations

# this.registered()

Map of registered plugin defs

# Base(runner, options)

Constructs a new Base reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# Base.epilogue()

Outputs common epilogue used by many of the bundled reporters.

# 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

# consoleLog()

Save log references to avoid tests interfering (see GH-3604).

# diff()

Module dependencies.

# errorDiff(actual, expected)

private method

Returns character diff for err.

Parameters

Name Types Description
actual String
expected String

Returns

string

the diff

# exports.colors()

Default color map.

# exports.cursor()

Expose some basic cursor interactions that are common among reporters.

# exports.inlineDiffs()

Inline diffs instead of +/-

# exports.list(failures)

Outputs the given failures as a list.

Parameters

Name Types Description
failures Object[] - Each is Test instance with corresponding Error property

# exports.maxDiffSize()

Truncate diffs longer than this value to avoid slow performance

# exports.symbols()

Default symbol map.

# exports.useColors()

Enable coloring by default, except in the browser interface.

# exports.window()

Expose term window size, with some defaults for when stderr is not a tty.

# 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

# isatty()

Check if both stdio streams are associated with a tty.

# module.exports()

Expose Base.

# objToString()

Object#toString reference.

# 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.

# Base()

Module dependencies.

# Doc(runner, options)

Constructs a new Doc reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# module.exports()

Expose Doc.

# Base()

Module dependencies.

# Dot(runner, options)

Constructs a new Dot reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# e()

Inherit from Base.prototype.

# module.exports()

Expose Dot.

# Base()

Module dependencies.

# Date()

Save timer references to avoid Sinon interfering (see GH-237).

# error(msg)

Display error msg.

Parameters

Name Types Description
msg string

# fragment(html)

Return a DOM fragment from html.

Parameters

Name Types Description
html string

# hideSuitesWithout(classname)

Check for suites that do not have elements with classname, and hide them.

Parameters

Name Types Description
classname text

# HTML(runner, options)

Constructs a new HTML reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# HTML.addCodeToggle(el, contents)

Adds code toggle functionality for the provided test's list element.

Parameters

Name Types Description
el HTMLLIElement
contents string

# HTML.suiteURL(suite)

Provide suite URL.

Parameters

Name Types Description
suite Object

# HTML.testURL(test)

Provide test URL.

Parameters

Name Types Description
test Object

# makeUrl(s)

Makes a URL, preserving querystring ("search") parameters.

Parameters

Name Types Description
s string

Returns

string

A new URL.

# module.exports()

Expose HTML.

# on()

Listen on event with callback fn.

# statsTemplate()

Stats template.

# text(el, contents)

Set an element's text contents.

Parameters

Name Types Description
el HTMLElement
contents string

# unhide()

Unhide .hidden suites.

# Base()

Module dependencies.

# 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

# JSONStream(runner, options)

Constructs a new JSONStream reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# module.exports()

Expose JSONStream.

# writeEvent(event)

private method

Writes Mocha event to reporter output stream.

Parameters

Name Types Description
event JSONStream~MochaEvent - Mocha event to be output.

# Base()

Module dependencies.

# 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

# errorJSON(err)

private method

Transform an Error object into a JSON object.

Parameters

Name Types Description
err Error

Returns

Object

# JSONReporter(runner, options)

Constructs a new JSON reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# module.exports()

Expose JSON.

# Base()

Module dependencies.

# Base.colors()

Airplane crash color.

# Base.colors.plane()

Airplane color.

# Base.colors.runway()

Runway color.

# e()

Inherit from Base.prototype.

# Landing(runner, options)

Constructs a new Landing reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# module.exports()

Expose Landing.

# Base()

Module dependencies.

# e()

Inherit from Base.prototype.

# List(runner, options)

Constructs a new List reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# module.exports()

Expose List.

# Base()

Module dependencies.

# Markdown(runner, options)

Constructs a new Markdown reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# module.exports()

Expose Markdown.

# SUITE_PREFIX()

Constants

# Base()

Module dependencies.

# e()

Inherit from Base.prototype.

# Min(runner, options)

Constructs a new Min reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# module.exports()

Expose Min.

# Base()

Module dependencies.

# e()

Inherit from Base.prototype.

# module.exports()

Expose Dot.

# NyanCat(runner, options)

Constructs a new Nyan reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# NyanCat.appendRainbow()

private method

Append the rainbow.

# NyanCat.cursorDown(n)

private method

Move cursor down n.

Parameters

Name Types Description
n number

# NyanCat.cursorUp(n)

private method

Move cursor up n.

Parameters

Name Types Description
n number

# NyanCat.draw()

private method

Draw the nyan cat

# NyanCat.drawNyanCat()

private method

Draw the nyan cat

# NyanCat.drawRainbow()

private method

Draw the rainbow.

# NyanCat.drawScoreboard()

private method

Draw the "scoreboard" showing the number of passes, failures and pending tests.

# NyanCat.face()

private method

Draw nyan cat face.

Returns

string

# NyanCat.generateColors()

private method

Generate rainbow colors.

Returns

Array

# NyanCat.rainbowify(str)

private method

Apply rainbow to the given str.

Parameters

Name Types Description
str string

Returns

string

# Base()

Module dependencies.

# Base.colors.progress()

General progress bar color.

# e()

Inherit from Base.prototype.

# module.exports()

Expose Progress.

# Progress(runner, options)

Constructs a new Progress reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# Base()

Module dependencies.

# e()

Inherit from Base.prototype.

# module.exports()

Expose Spec.

# Spec(runner, options)

Constructs a new Spec 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.

# e()

Inherit from Base.prototype.

# inherits()

Inherit from TAPProducer.prototype.

# inherits()

Inherit from TAPProducer.prototype.

# module.exports()

Expose TAP.

# 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

# TAP(runner, options)

Constructs a new TAP reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# TAP12Producer()

private method

# TAP13Producer()

private method

# TAPProducer()

private method

# TAPProducer.writeEpilogue(stats)

Writes the summary epilogue to reporter output stream.

Parameters

Name Types Description
stats Object - Object containing run statistics.

# TAPProducer.writeFail(n, test, err)

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.
err Error - Reason the test failed.

# TAPProducer.writePass(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.

# TAPProducer.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.

# TAPProducer.writePlan(ntests)

Writes the plan to reporter output stream.

Parameters

Name Types Description
ntests number - Number of tests that are planned to run.

# TAPProducer.writeVersion()

Writes the TAP version to reporter output stream.

# this.writeFail()

Writes that test failed to reporter output stream, with error formatting.

# this.writeFail()

Writes that test failed to reporter output stream, with error formatting.

# this.writeVersion()

Writes the TAP version to reporter output stream.

# 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

# util()

Module dependencies.

# Base()

Module dependencies.

# Date()

Save timer references to avoid Sinon interfering (see GH-237).

# e()

Inherit from Base.prototype.

# module.exports()

Expose XUnit.

# tag(name, attrs, close, content)

HTML tag helper.

Parameters

Name Types Description
name
attrs
close
content

Returns

string

# XUnit(runner, options)

Constructs a new XUnit reporter instance.

Parameters

Name Types Description
runner Runner - Instance triggers reporter actions.
options Object - runner options

# XUnit.done(failures, fn)

Override done to close the stream (if it's a file).

Parameters

Name Types Description
failures
fn Function

# XUnit.test(test)

Output tag for the given test.

Parameters

Name Types Description
test Test

# XUnit.write(line)

Write out the given line.

Parameters

Name Types Description
line string

# Date()

private method

Save timer references to avoid Sinon interfering (see GH-237).

# Runnable(title, fn)

Initialize a new Runnable with the given title and callback fn.

Parameters

Name Types Description
title String
fn Function

# Runnable._timeoutError(ms)

private method

Instantiates a "timeout" error

Parameters

Name Types Description
ms number - Timeout (in milliseconds)

# Runnable.clearTimeout()

private method

Clear the timeout.

# Runnable.currentRetry()

private method

Set or get current retry

# Runnable.fullTitle()

Return the full title generated by recursively concatenating the parent's full title.

Returns

string

# Runnable.globals(globals)

private method

Set or get a list of whitelisted globals for this test run.

Parameters

Name Types Description
globals string[]

# Runnable.isFailed()

private method

Return true if this Runnable has failed.

Returns

boolean

# Runnable.isPassed()

private method

Return true if this Runnable has passed.

Returns

boolean

# Runnable.isPending()

private method

Check if this runnable or its parent suite is marked as pending.

# Runnable.reset()

Resets the state initially or for a next run.

# Runnable.resetTimeout()

private method

Reset the timeout.

# Runnable.retries()

private method

Set or get number of retries.

# Runnable.run(fn)

private method

Run the test and invoke fn(err).

Parameters

Name Types Description
fn Function

# Runnable.skip()

Halt and mark as pending.

# Runnable.slow(ms)

private method

Set or get slow ms.

Parameters

Name Types Description
ms number string

Returns

Runnable|number

ms or Runnable instance.

# Runnable.timeout(ms)

private method

Parameters

Name Types Description
ms number string

# Runnable.titlePath()

Return the title path generated by concatenating the parent's title path with the title.

Returns

string[]

# Runnable.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

# SED()

Value of state prop when a Runnable has passed

# STATE_FAILED()

Value of state prop when a Runnable has failed

# STATE_PENDING()

Value of state prop when a Runnable has been skipped by user

# utils.inherits()

Inherit from EventEmitter.prototype.

# constructor(suite, opts, opts.cleanReferencesAfterRun, opts.delay, opts.dryRun, opts.failZero)

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.

# EVENT_DELAY_BEGIN()

Emitted when Root {@link Suite} execution has been delayed via delay option

# EVENT_DELAY_END()

Emitted when delayed Root {@link Suite} execution is triggered by user via global.run()

# EVENT_HOOK_BEGIN()

Emitted when {@link Hook} execution begins

# EVENT_HOOK_END()

Emitted when {@link Hook} execution ends

# EVENT_RUN_BEGIN()

Emitted when Root {@link Suite} execution begins (all files have been parsed and hooks/tests are ready for execution)

# EVENT_RUN_END()

Emitted when Root {@link Suite} execution ends

# EVENT_SUITE_BEGIN()

Emitted when {@link Suite} execution begins

# EVENT_SUITE_END()

Emitted when {@link Suite} execution ends

# EVENT_TEST_BEGIN()

Emitted when {@link Test} execution begins

# EVENT_TEST_END()

Emitted when {@link Test} execution ends

# EVENT_TEST_FAIL()

Emitted when {@link Test} execution fails

# EVENT_TEST_PENDING()

Emitted when {@link Test} becomes pending

# EVENT_TEST_RETRY()

Emitted when {@link Test} execution has failed, but will retry

# EventEmitter()

private method

Module dependencies.

# filterLeaks(ok, globals)

private method

Filter leaks with the given globals flagged as ok.

Parameters

Name Types Description
ok Array
globals Array

Returns

Array

# globals()

private method

Non-enumerable globals.

# 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.

# module.exports()

Node.js' EventEmitter

# 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.abort()

Cleanly abort execution.

Returns

Runner

Runner instance.

# Runner.checkGlobals()

private method

Check for global variable leaks.

# 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.globalProps()

private method

Return a list of global properties.

Returns

Array

# 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, opts.files, opts.options)

Run the root suite and invoke fn(failures) on completion.

Parameters

Name Types Description
fn Function - Callback when finished
opts Object - For subclasses
opts.files string[] - Files to run
opts.options Options - command-line options

# 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

# S()

Emitted when {@link Test} execution succeeds

# STATE_IDLE()

Initial state of Runner

# STATE_RUNNING()

State set to this value when the Runner has started running

# STATE_STOPPED()

State set to this value when the Runner has stopped

# 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

# constants()

Provides a factory function for a {@link StatsCollector} object.

# 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

# Date()

Test statistics collector.

# stats()

# 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.

# 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.

# EVENT_ROOT_SUITE_RUN()

Event emitted when global.run() is called (use with delay option).

# EVENT_SUITE_ADD_HOOK_AFTER_ALL()

Emitted after an "after all" Hook has been added to a Suite.

# EVENT_SUITE_ADD_HOOK_AFTER_EACH()

Emitted after an "after each" Hook has been added to a Suite.

# EVENT_SUITE_ADD_HOOK_BEFORE_ALL()

Emitted after an "before all" Hook has been added to a Suite.

# EVENT_SUITE_ADD_HOOK_BEFORE_EACH()

Emitted after an "before each" Hook has been added to a Suite.

# EVENT_SUITE_ADD_SUITE()

Emitted after a child Suite has been added to a Suite.

# EVENT_SUITE_ADD_TEST()

Emitted after a Test has been added to a Suite.

# filterOnly()

private method

Filter suites based on isOnly logic.

# getHooks()

private method

Returns the array of hooks by hook name; see HOOK_TYPE_* constants.

# hasOnly()

private method

Determines whether a suite has an only test or suite as a descendant.

# HOOK_TYPE_AFTER_ALL()

Namespace for collection of a Suite's "after all" hooks.

# HOOK_TYPE_AFTER_EACH()

Namespace for collection of a Suite's "after each" hooks.

# HOOK_TYPE_BEFORE_ALL()

Namespace for collection of a Suite's "before all" hooks.

# HOOK_TYPE_BEFORE_EACH()

Namespace for collection of a Suite's "before each" hooks.

# inherits()

Inherit from EventEmitter.prototype.

# module.exports()

Expose Suite.

# require()

private method

Module dependencies.

# run()

private method

This will run the root suite if we happen to be running in delayed mode.

# serialize()

private method

Returns an object suitable for IPC. Functions are represented by keys beginning with $$.

# Suite(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.

# Suite._createHook(title, fn)

private method

Generic hook-creator.

Parameters

Name Types Description
title string - Title of hook
fn Function - Hook callback

# Suite.addSuite(suite)

private method

Add a test suite.

Parameters

Name Types Description
suite Suite

Returns

Suite

for chaining

# Suite.addTest(test)

private method

Add a test to this suite.

Parameters

Name Types Description
test Test

Returns

Suite

for chaining

# Suite.afterAll(title, fn)

private method

Run fn(test[, done]) after running tests.

Parameters

Name Types Description
title string
fn Function

Returns

Suite

for chaining

# Suite.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

# Suite.appendOnlySuite(suite)

private method

Adds a suite to the list of subsuites marked only.

Parameters

Name Types Description
suite Suite

# Suite.appendOnlyTest(test)

private method

Adds a test to the list of tests marked only.

Parameters

Name Types Description
test Test

# Suite.bail(bail)

private method

Set or get whether to bail after first error.

Parameters

Name Types Description
bail boolean

Returns

Suite|number

for chaining

# Suite.beforeAll(title, fn)

private method

Run fn(test[, done]) before running tests.

Parameters

Name Types Description
title string
fn Function

Returns

Suite

for chaining

# Suite.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

# Suite.clone()

private method

Return a clone of this Suite.

Returns

Suite

# 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

# Suite.dispose()

cleans all references from this suite and all child suites.

# 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

# Suite.fullTitle()

Return the full title generated by recursively concatenating the parent's full title.

Returns

string

# Suite.isPending()

private method

Check if this suite or its parent suite is marked as pending.

# Suite.markOnly()

private method

Marks a suite to be only.

# Suite.reset()

Resets the state initially or for a next run.

# Suite.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

# Suite.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

# Suite.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

# Suite.titlePath()

Return the title path generated by recursively concatenating the parent's title path.

Returns

string[]

# Suite.total()

Return the total number of tests.

Returns

number

# serialize()

private method

Returns an minimal object suitable for transmission over IPC. Functions are represented by keys beginning with $$.

# Test(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"

# Test.markOnly()

private method

Add test to the list of tests marked only.

# Test.reset()

Resets the state initially or for a next run.

# Test.retriedTest()

private method

Set or get retried test

# utils.inherits()

Inherit from Runnable.prototype.

# 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.

# cwd()

private method

Returns current working directory Wrapper around process.cwd() for isolation

# 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.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.inherits(ctor, superCtor)

Inherit the prototype methods from one constructor into another.

Parameters

Name Types Description
ctor function - Constructor function which needs to inherit the prototype.
superCtor function - Constructor function to inherit prototype from.

# exports.isString(obj)

private method

Test if the given obj is type of string.

Parameters

Name Types Description
obj Object

Returns

boolean

# exports.noop()

It's a noop.

# 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.

# isPromise(value)

Crude, but effective.

Parameters

Name Types Description
value *

# jsonStringify(object, spaces, depth)

private method

like JSON.stringify but more sense.

Parameters

Name Types Description
object Object
spaces number=
depth number=

# path()

Module dependencies.

# type(value)

private method

Returns a general type or data structure of a variable

Parameters

Name Types Description
value * The value to test.

# test(testName, mochaParams)

Generates a command to run mocha tests with or without test coverage as desired for the current runmode.

Parameters

Name Types Description
testName string The name of the test to be used for coverage reporting.
mochaParams string Parameters for the mocha CLI to execute the desired 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.

# pickFromPackageJson(options, options.keys)

This rollup plugin lets you pick specific fields you want to export for the specific case of importing a modules package.json. This helps reduce the file size of the resulting bundle.

Parameters

Name Types Description
options object
options.keys string[] List of keys to export from package.json

# 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.

# i()

Shared state! Bad practice, but nice for this test

# i()

Shared state! Bad practice, but nice for this test

# describe()

This file generates a wide range of output to test reporter functionality.

# context.test()

Describes a specification or test-case with the given title and callback fn acting as a thunk.

# module.exports()

A simple UI that only exposes a single function: test

# 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

# createTempDir()

Creates a temporary directory

# DEFAULT_FIXTURE()

Name of "default" fixture file.

# DEFAULT_FIXTURE_PATH()

Path to "default" fixture file

# 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_EXECUTABLE()

Path to mocha executable

# 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

# sleep(time)

Waits for time ms.

Parameters

Name Types Description
time number - Time in ms

# 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

# 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

# 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. RC file (.mocharc.js, .mocharc.ya?ml, mocharc.json) 3. mocha prop of package.json 4. default rc

# rewiremock.proxy()

# 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(ctor)

Creates closure with reference to the reporter class constructor.

Parameters

Name Types Description
ctor Function - Reporter class constructor

Returns

createRunReporterFunction~runReporter

# runReporter(stubSelf, runner, options, tee)

Run reporter using stream reassignment to capture output.

Parameters

Name Types Description
stubSelf Object - Reporter-like stub 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`

# cleanup()

# tmpdir()

# Base()

Stub Base reporter constructor

# opts()

Options for Mocha constructor

# reporterInstance()

Instance of a hypothetical reporter

# Runner()

Stub Runner constructor; returns a stubbed EventEmitter

# runner()

Stub Runner (EventEmitter) instance

# Suite()

Stub Suite constructor; returns a stubbed EventEmitter

# suite()

Stub Suite instance (root suite in our case)