Mocha

Mocha

new Mocha(optionsopt)

Source:

Constructs a new Mocha instance with options.

Parameters:
NameTypeAttributesDescription
optionsObject<optional>

Settings object.

Properties
NameTypeAttributesDescription
allowUncaughtboolean<optional>

Propagate uncaught errors?

asyncOnlyboolean<optional>

Force done callback or promise?

bailboolean<optional>

Bail after first test failure?

checkLeaksboolean<optional>

Check for global variable leaks?

colorboolean<optional>

Color TTY output from reporter?

delayboolean<optional>

Delay root suite execution?

diffboolean<optional>

Show diff on failure?

dryRunboolean<optional>

Report tests without running them?

failZeroboolean<optional>

Fail test run if zero tests?

fgrepstring<optional>

Test filter given string.

forbidOnlyboolean<optional>

Tests marked only fail the suite?

forbidPendingboolean<optional>

Pending tests fail the suite?

fullTraceboolean<optional>

Full stacktrace upon failure?

globalArray:.<string:><optional>

Variables expected in global scope.

grepRegExp | string<optional>

Test filter given regular expression.

inlineDiffsboolean<optional>

Display inline diffs?

invertboolean<optional>

Invert test filter matches?

noHighlightingboolean<optional>

Disable syntax highlighting?

reporterstring | constructor<optional>

Reporter name or constructor.

reporterOptionObject<optional>

Reporter settings object.

retriesnumber<optional>

Number of times to retry failed tests.

slownumber<optional>

Slow threshold value.

timeoutnumber | string<optional>

Timeout threshold value.

uistring<optional>

Interface name.

parallelboolean<optional>

Run jobs in parallel.

jobsnumber<optional>

Max number of worker processes for parallel runs.

rootHooksMochaRootHookObject<optional>

Hooks to bootstrap the root suite with.

requireArray:.<string:><optional>

Pathname of rootHooks plugin for parallel runs.

isWorkerboolean<optional>

Should be true if Mocha process is running in a worker process.

Members

(static) exports.reporters

Source:

(static) exports.Runner

Source:

(readonly) version :string

Source:

Mocha version as specified by "package.json".

Type:
  • string

Methods

addFile(file) → {Mocha}

Adds file to be loaded for execution.

Source:
See:

Useful for generic setup code that must be included within test suite.

Parameters:
NameTypeDescription
filestring

Pathname of file to be loaded.

Returns:

this

Type
Mocha

allowUncaught(allowUncaughtopt) → {Mocha}

Source:
See:

Enables or disables uncaught errors to propagate.

Parameters:
NameTypeAttributesDefaultDescription
allowUncaughtboolean<optional>
true

Whether to propagate uncaught errors.

Returns:

this

Type
Mocha

asyncOnly(asyncOnlyopt) → {Mocha}

Source:
See:

Forces all tests to either accept a done callback or return a promise.

Parameters:
NameTypeAttributesDefaultDescription
asyncOnlyboolean<optional>
true

Whether to force done callback or promise.

Returns:

this

Type
Mocha

bail(bailopt) → {Mocha}

Source:
See:

Enables or disables bailing on the first failure.

Parameters:
NameTypeAttributesDefaultDescription
bailboolean<optional>
true

Whether to bail on first error.

Returns:

this

Type
Mocha

checkLeaks(checkLeaksopt) → {Mocha}

Source:
See:

Enables or disables checking for global variables leaked while running tests.

Parameters:
NameTypeAttributesDefaultDescription
checkLeaksboolean<optional>
true

Whether to check for global variable leaks.

Returns:

this

Type
Mocha

cleanReferencesAfterRun(cleanReferencesAfterRun) → {Mocha}

Source:
See:

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:
NameTypeDescription
cleanReferencesAfterRunboolean
Returns:

this

Type
Mocha

color(coloropt) → {Mocha}

Source:
See:

Enables or disables TTY color output by screen-oriented reporters.

Parameters:
NameTypeAttributesDefaultDescription
colorboolean<optional>
true

Whether to enable color output.

Returns:

this

Type
Mocha

delay() → {Mocha}

Delays root suite execution.

Source:
See:

Used to perform async operations before any suites are run.

Returns:

this

Type
Mocha

diff(diffopt) → {Mocha}

Source:
See:

Enables or disables reporter to include diff in test failure output.

Parameters:
NameTypeAttributesDefaultDescription
diffboolean<optional>
true

Whether to show diff on failure.

Returns:

this

Type
Mocha

dispose()

Source:

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.

dryRun(dryRunopt) → {Mocha}

Source:
See:

Enables or disables running tests in dry-run mode.

Parameters:
NameTypeAttributesDefaultDescription
dryRunboolean<optional>
true

Whether to activate dry-run mode.

Returns:

this

Type
Mocha

enableGlobalSetup(enabledopt) → {Mocha}

Source:

Toggle execution of any global setup fixture(s)

Parameters:
NameTypeAttributesDefaultDescription
enabledboolean<optional>
true

If false, do not run global setup fixture

Returns:
Type
Mocha

enableGlobalTeardown(enabledopt) → {Mocha}

Source:

Toggle execution of any global teardown fixture(s)

Parameters:
NameTypeAttributesDefaultDescription
enabledboolean<optional>
true

If false, do not run global teardown fixture

Returns:
Type
Mocha

failZero(failZeroopt) → {Mocha}

Source:
See:

Fails test run if no tests encountered with exit-code 1.

Parameters:
NameTypeAttributesDefaultDescription
failZeroboolean<optional>
true

Whether to fail test run.

Returns:

this

Type
Mocha

fgrep(str) → {Mocha}

Source:
See:

Sets grep filter after escaping RegExp special characters.

Example
// Select tests whose full title begins with `"foo"` followed by a period
mocha.fgrep('foo.');
Parameters:
NameTypeDescription
strstring

Value to be converted to a regexp.

Returns:

this

Type
Mocha

forbidOnly(forbidOnlyopt) → {Mocha}

Source:
See:

Causes tests marked only to fail the suite.

Parameters:
NameTypeAttributesDefaultDescription
forbidOnlyboolean<optional>
true

Whether tests marked only fail the suite.

Returns:

this

Type
Mocha

forbidPending(forbidPendingopt) → {Mocha}

Source:
See:

Causes pending tests and tests marked skip to fail the suite.

Parameters:
NameTypeAttributesDefaultDescription
forbidPendingboolean<optional>
true

Whether pending tests fail the suite.

Returns:

this

Type
Mocha

fullTrace(fullTraceopt) → {Mocha}

Source:
See:

Displays full stack trace upon test failure.

Parameters:
NameTypeAttributesDefaultDescription
fullTraceboolean<optional>
true

Whether to print full stacktrace upon failure.

Returns:

this

Type
Mocha

global(global) → {Mocha}

Source:
See:

Specifies whitelist of variable names to be expected in global scope.

Example
// Specify variables to be expected in global scope
mocha.global(['jQuery', 'MyLib']);
Parameters:
NameTypeDescription
globalArray:.<String:> | String

Accepted global variable name(s).

Returns:

this

Type
Mocha

globalSetup(setupFnsopt) → {Mocha}

Source:

Configures one or more global setup fixtures.

If given no parameters, unsets any previously-set fixtures.

Parameters:
NameTypeAttributesDescription
setupFnsMochaGlobalFixture | Array:.<MochaGlobalFixture:><optional>

Global setup fixture(s)

Returns:
Type
Mocha

globalTeardown(teardownFnsopt) → {Mocha}

Source:

Configures one or more global teardown fixtures.

If given no parameters, unsets any previously-set fixtures.

Parameters:
NameTypeAttributesDescription
teardownFnsMochaGlobalFixture | Array:.<MochaGlobalFixture:><optional>

Global teardown fixture(s)

Returns:
Type
Mocha

grep(re) → {Mocha}

Sets grep filter used to select specific tests for execution.

Source:
See:

If re is a regexp-like string, it will be converted to regexp.
The regexp is tested against the full title of each test (i.e., the
name of the test preceded by titles of each its ancestral suites).
As such, using an exact-match fixed pattern against the
test name itself will not yield any matches.


Previous filter value will be overwritten on each call!

Examples
// Select tests whose full title contains `"match"`, ignoring case
mocha.grep(/match/i);
// Same as above but with regexp-like string argument
mocha.grep('/match/i');
// ## Anti-example
// Given embedded test `it('only-this-test')`...
mocha.grep('/^only-this-test$/');    // NO! Use `.only()` to do this!
Parameters:
NameTypeDescription
reRegExp | String

Regular expression used to select tests.

Returns:

this

Type
Mocha

hasGlobalSetupFixtures() → {boolean}

Source:

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

Returns:
Type
boolean

hasGlobalTeardownFixtures() → {boolean}

Source:

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

Returns:
Type
boolean

inlineDiffs(inlineDiffsopt) → {Mocha}

Source:
See:

Enables or disables reporter to use inline diffs (rather than +/-)
in test failure output.

Parameters:
NameTypeAttributesDefaultDescription
inlineDiffsboolean<optional>
true

Whether to use inline diffs.

Returns:

this

Type
Mocha

invert() → {Mocha}

Source:
See:

Inverts grep matches.

Example
// Select tests whose full title does *not* contain `"match"`, ignoring case
mocha.grep(/match/i).invert();
Returns:

this

Type
Mocha

lazyLoadFiles(enableopt)

Source:
To Do:
  • This should throw if we've already loaded files; such behavior necessitates adding a new state.

Disables implicit call to Mocha#loadFiles in Mocha#run. This
setting is used by watch mode, parallel mode, and for loading ESM files.

Parameters:
NameTypeAttributesDescription
enableboolean<optional>

If true, disable eager loading of files in
Mocha#run

loadFilesAsync(optionsopt) → {Promise}

Source:
See:

The implementation relies on Node's require and import to execute
the test interface functions and will be subject to its cache.
Supports both CJS and ESM modules.

Example
// loads ESM (and CJS) test files asynchronously, then runs root suite
mocha.loadFilesAsync()
  .then(() => mocha.run(failures => process.exitCode = failures ? 1 : 0))
  .catch(() => process.exitCode = 1);
Parameters:
NameTypeAttributesDescription
optionsObject<optional>

Settings object.

Properties
NameTypeAttributesDescription
esmDecoratorfunction<optional>

Function invoked on esm module name right before importing it. By default will passthrough as is.

Returns:
Type
Promise

noHighlighting() → {Mocha}

Source:

Disables syntax highlighting (in browser).

Returns:

this

Type
Mocha

parallelMode(enableopt) → {Mocha}

Source:

Toggles parallel mode.

Must be run before calling 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:
NameTypeAttributesDescription
enableboolean<optional>

If true, enable; otherwise disable.

Throws:
  • If run in browser

  • If Mocha not in INIT state

Returns:
Type
Mocha

reporter(reporterName, reporterOptionsopt) → {Mocha}

Source:
See:

Sets reporter to reporter, defaults to "spec".

Example
// Use XUnit reporter and direct its output to file
mocha.reporter('xunit', { output: '/path/to/testspec.xunit.xml' });
Parameters:
NameTypeAttributesDescription
reporterNameString | function

Reporter name or constructor.

reporterOptionsObject<optional>

Options used to configure the reporter.

Throws:

if requested reporter cannot be loaded

Type
Error
Returns:

this

Type
Mocha

retries(retry) → {Mocha}

Source:
See:

Sets the number of times to retry failed tests.

Example
// Allow any failed test to retry one more time
mocha.retries(1);
Parameters:
NameTypeDescription
retrynumber

Number of times to retry failed tests.

Returns:

this

Type
Mocha

rootHooks(hooksopt)

Source:

Assigns hooks to the root suite

Parameters:
NameTypeAttributesDescription
hooksMochaRootHookObject<optional>

Hooks to assign to root suite

run(fnopt) → {Runner}

Source:
See:

To run tests multiple times (or to run tests in files that are
already in the require cache), make sure to clear them from
the cache first!

Example
// exit with non-zero status if there were test failures
mocha.run(failures => process.exitCode = failures ? 1 : 0);
Parameters:
NameTypeAttributesDescription
fnDoneCB<optional>

Callback invoked when test execution completed.

Returns:

runner instance

Type
Runner

runGlobalSetup(contextopt) → {Promise:.<object:>}

Source:

Run any global setup fixtures sequentially, if any.

This is automatically called by Mocha#run unless the runGlobalSetup option is false; see Mocha#enableGlobalSetup.

The context object this function resolves with should be consumed by Mocha#runGlobalTeardown.

Parameters:
NameTypeAttributesDescription
contextobject<optional>

Context object if already have one

Returns:

Context object

Type
Promise:.<object:>

runGlobalTeardown(contextopt) → {Promise:.<object:>}

Source:

Run any global teardown fixtures sequentially, if any.

This is automatically called by Mocha#run unless the runGlobalTeardown option is false; see Mocha#enableGlobalTeardown.

Should be called with context object returned by Mocha#runGlobalSetup, if applicable.

Parameters:
NameTypeAttributesDescription
contextobject<optional>

Context object if already have one

Returns:

Context object

Type
Promise:.<object:>

slow(msecs) → {Mocha}

Source:
See:

Sets slowness threshold value.

Examples
// Sets "slow" threshold to half a second
mocha.slow(500);
// Same as above but using string argument
mocha.slow('0.5s');
Parameters:
NameTypeDescription
msecsnumber

Slowness threshold value.

Returns:

this

Type
Mocha

timeout(msecs) → {Mocha}

Sets timeout threshold value.

Source:
See:

A string argument can use shorthand (such as "2s") and will be converted.
If the value is 0, timeouts will be disabled.

Examples
// Sets timeout to one second
mocha.timeout(1000);
// Same as above but using string argument
mocha.timeout('1s');
Parameters:
NameTypeDescription
msecsnumber | string

Timeout threshold value.

Returns:

this

Type
Mocha

ui(uiopt) → {Mocha}

Source:
See:

Sets test UI name, defaults to "bdd".

Parameters:
NameTypeAttributesDefaultDescription
uistring | function<optional>
bdd

Interface name or class.

Throws:

if requested interface cannot be loaded

Type
Error
Returns:

this

Type
Mocha

unloadFiles() → {Mocha}

Source:
See:

This allows required files to be "freshly" reloaded, providing the ability
to reuse a Mocha instance programmatically.
Note: does not clear ESM module files from the cache

Intended for consumers — not used internally

Returns:

this

Type
Mocha