| 1 |
--- |
| 2 |
layout: default |
| 3 |
title: "Mocha - the fun, simple, flexible JavaScript test framework" |
| 4 |
description: "Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun." |
| 5 |
--- |
| 6 |
|
| 7 |
<div class="admonition">This site has a new look, try it out at <a href="next">mochajs.org/next</a>!</div> |
| 8 |
|
| 9 |
Mocha is a feature-rich JavaScript test framework running on [Node.js][] and in the browser, making asynchronous testing _simple_ and _fun_. Mocha tests run serially, allowing for flexible and accurate reporting, while mapping uncaught exceptions to the correct test cases. Hosted on [GitHub][github-mocha]. |
| 10 |
|
| 11 |
<nav class="badges"> |
| 12 |
<a href="https://discord.gg/KeDn2uXhER"><img alt="Chat - Discord" height="18" src="https://img.shields.io/badge/chat-Discord-5765F2.svg" /></a> |
| 13 |
<a href="#sponsors"><img src="https://opencollective.com/mochajs/tiers/sponsors/badge.svg" height="18" alt="OpenCollective sponsors"></a> |
| 14 |
<a href="#backers"><img src="https://opencollective.com/mochajs/tiers/backers/badge.svg" height="18" alt="OpenCollective backers"></a> |
| 15 |
</nav> |
| 16 |
|
| 17 |
{% include 'supporters.md' %} |
| 18 |
|
| 19 |
## Features |
| 20 |
|
| 21 |
- [browser support](#running-mocha-in-the-browser) |
| 22 |
- [simple async support, including promises](#asynchronous-code) |
| 23 |
- [run Node.js tests in parallel](#parallel-tests) |
| 24 |
- [test coverage reporting](#wallabyjs) |
| 25 |
- [string diff support](#diffs) |
| 26 |
- [JavaScript API for running tests](#more-information) |
| 27 |
- [auto-detects and disables coloring for non-TTYs](#reporters) |
| 28 |
- [async test timeout support](#delayed-root-suite) |
| 29 |
- [test retry support](#retry-tests) |
| 30 |
- [test-specific timeouts](#test-level) |
| 31 |
- [reports test durations](#test-duration) |
| 32 |
- [highlights slow tests](#dot-matrix) |
| 33 |
- [file watcher support](#min) |
| 34 |
- [global variable leak detection](#-check-leaks) |
| 35 |
- [optionally run tests that match a regexp](#-grep-regexp-g-regexp) |
| 36 |
- [auto-exit to prevent "hanging" with an active loop](#-exit) |
| 37 |
- [easily meta-generate suites](#markdown) & [test-cases](#list) |
| 38 |
- [config file support](#-config-path) |
| 39 |
- [node debugger support](#-inspect-inspect-brk-inspect) |
| 40 |
- [node native ES modules support](#nodejs-native-esm-support) |
| 41 |
- [source-map support](#-enable-source-maps) |
| 42 |
- [detects multiple calls to `done()`](#detects-multiple-calls-to-done) |
| 43 |
- [use any assertion library you want](#assertions) |
| 44 |
- [extensible reporting, bundled with 9+ reporters](#reporters) |
| 45 |
- [extensible test DSLs or "interfaces"](#interfaces) |
| 46 |
- [before, after, before each, after each hooks](#hooks) |
| 47 |
- [arbitrary transpiler support (coffee-script etc)](#-compilers) |
| 48 |
- [TextMate bundle](#textmate) |
| 49 |
{:.two-column} |
| 50 |
|
| 51 |
## Table of Contents |
| 52 |
|
| 53 |
{{ toc }} |
| 54 |
{:.two-column} |
| 55 |
|
| 56 |
## Installation |
| 57 |
|
| 58 |
Install with [npm][] globally: |
| 59 |
|
| 60 |
```bash |
| 61 |
$ npm install --global mocha |
| 62 |
``` |
| 63 |
|
| 64 |
or as a development dependency for your project: |
| 65 |
|
| 66 |
```bash |
| 67 |
$ npm install --save-dev mocha |
| 68 |
``` |
| 69 |
|
| 70 |
> As of v11.0.0, Mocha requires [Node.js](https://nodejs.org) `^18.18.0 || ^20.9.0 || >=21.1.0`. |
| 71 |
|
| 72 |
## Getting Started |
| 73 |
|
| 74 |
```bash |
| 75 |
$ npm install mocha |
| 76 |
$ mkdir test |
| 77 |
$ $EDITOR test/test.js # or open with your favorite editor |
| 78 |
``` |
| 79 |
|
| 80 |
In your editor: |
| 81 |
|
| 82 |
```js |
| 83 |
var assert = require("assert"); |
| 84 |
describe("Array", function () { |
| 85 |
describe("#indexOf()", function () { |
| 86 |
it("should return -1 when the value is not present", function () { |
| 87 |
assert.equal([1, 2, 3].indexOf(4), -1); |
| 88 |
}); |
| 89 |
}); |
| 90 |
}); |
| 91 |
``` |
| 92 |
|
| 93 |
Back in the terminal: |
| 94 |
|
| 95 |
```bash |
| 96 |
$ ./node_modules/mocha/bin/mocha.js |
| 97 |
|
| 98 |
Array |
| 99 |
#indexOf() |
| 100 |
✓ should return -1 when the value is not present |
| 101 |
|
| 102 |
|
| 103 |
1 passing (9ms) |
| 104 |
``` |
| 105 |
|
| 106 |
Set up a test script in package.json: |
| 107 |
|
| 108 |
```json |
| 109 |
"scripts": { |
| 110 |
"test": "mocha" |
| 111 |
} |
| 112 |
``` |
| 113 |
|
| 114 |
Then run tests with: |
| 115 |
|
| 116 |
```bash |
| 117 |
$ npm test |
| 118 |
``` |
| 119 |
|
| 120 |
## Run Cycle Overview |
| 121 |
|
| 122 |
> Updated for v8.0.0. |
| 123 |
|
| 124 |
The following is a mid-level outline of Mocha's "flow of execution" when run in Node.js; the "less important" details have been omitted. |
| 125 |
|
| 126 |
In a browser, test files are loaded by `<script>` tags, and calling `mocha.run()` begins at step 9 [below](#serial-mode). |
| 127 |
|
| 128 |
### Serial Mode |
| 129 |
|
| 130 |
1. User (that's you) executes `mocha` |
| 131 |
2. Loads options from config files, if present |
| 132 |
3. Mocha processes any command-line options provided (see section on [configuration merging](#merging) for details) |
| 133 |
4. If known flags for the `node` executable are found: |
| 134 |
1. Mocha will spawn `node` in a child process, executing itself with these flags |
| 135 |
2. Otherwise, Mocha does not spawn a child process |
| 136 |
5. Mocha loads modules specified by `--require` |
| 137 |
1. If a file loaded this way contains known Mocha-specific exports (e.g., [root hook plugins]), Mocha "registers" these |
| 138 |
2. If not, Mocha ignores any exports of a `--require`'d module |
| 139 |
6. Mocha validates any custom reporters or interfaces which were loaded via `--require` or otherwise |
| 140 |
7. Mocha _discovers_ test files; when given no files or directories, it finds files with extensions `.js`, `.mjs` or `.cjs` in the `test` directory (but not its children), relative to the current working directory |
| 141 |
8. The (default) [bdd interface](#bdd) loads the test files _in no particular order_, which are given an interface-specific `global` context (this is how, e.g., `describe()` ends up as a global in a test file) |
| 142 |
1. When a test file is loaded, Mocha executes all of its suites and finds--_but does not execute_--any hooks and tests therein. |
| 143 |
2. Top-level hooks, tests and suites are all made members of an "invisible" _root suite_; there is only _one_ root suite for the entire process |
| 144 |
9. Mocha runs [global setup fixtures], if any |
| 145 |
10. Starting with the "root" suite, Mocha executes: |
| 146 |
11. Any "before all" hooks (for the _root_ suite, this only happens once; see [root hook plugins]) |
| 147 |
12. For each test, Mocha executes: |
| 148 |
1. Any "before each" hooks |
| 149 |
2. The test (and reports the result) |
| 150 |
3. Any "after each" hooks |
| 151 |
13. If the current suite has a child suite, repeat the steps in 10. for each child suite; each child suite _inherits_ any "before each" and "after each" hooks defined in its parent |
| 152 |
14. Any "after all" hooks (for the _root_ suite, this only happens once; see [root hook plugins]) |
| 153 |
15. Mocha prints a final summary/epilog, if applicable |
| 154 |
16. Mocha runs [global teardown fixtures], if any |
| 155 |
|
| 156 |
### Parallel Mode |
| 157 |
|
| 158 |
1. Repeat steps 1 through 6 from [Serial Mode](#serial-mode) above, skipping reporter validation |
| 159 |
2. All test files found are put into a queue (they are _not_ loaded by the main process) |
| 160 |
3. Mocha runs [global setup fixtures], if any |
| 161 |
4. Mocha creates a pool of subprocesses ("workers") |
| 162 |
5. _Immediately before_ a worker runs the first test it receives, the worker "bootstraps" itself by: |
| 163 |
1. Loading all `--require`'d modules |
| 164 |
2. Registering any root hook plugins |
| 165 |
3. _Ignoring_ global fixtures and custom reporters |
| 166 |
4. Asserting the built-in or custom interface is valid |
| 167 |
6. When a worker receives a test file to run, the worker creates a new Mocha instance _for the single test file_, and: |
| 168 |
7. The worker repeats step 8 from [above](#serial-mode) |
| 169 |
8. The worker repeats step 10 from [above](#serial-mode), with the caveat that the worker _does not_ report test results directly; it holds them in a memory buffer |
| 170 |
9. When the worker completes the test file, buffered results are returned to the main process, which then gives them to the user-specified reporter (`spec` by default) |
| 171 |
10. The worker makes itself available to the pool; the pool gives the worker another test file to run, if any remain |
| 172 |
11. Mocha prints a final summary/epilog, if applicable |
| 173 |
12. Mocha runs [global teardown fixtures], if any |
| 174 |
|
| 175 |
## Detects Multiple Calls to `done()` |
| 176 |
|
| 177 |
If you use callback-based async tests, Mocha will throw an error if `done()` is called multiple times. This is handy for catching accidental double callbacks. |
| 178 |
|
| 179 |
```javascript |
| 180 |
it("double done", function (done) { |
| 181 |
// Calling `done()` twice is an error |
| 182 |
setImmediate(done); |
| 183 |
setImmediate(done); |
| 184 |
}); |
| 185 |
``` |
| 186 |
|
| 187 |
Running the above test will give you the below error message: |
| 188 |
|
| 189 |
```bash |
| 190 |
$ ./node_modules/.bin/mocha mocha.test.js |
| 191 |
|
| 192 |
|
| 193 |
✓ double done |
| 194 |
1) double done |
| 195 |
|
| 196 |
1 passing (6ms) |
| 197 |
1 failing |
| 198 |
|
| 199 |
1) double done: |
| 200 |
Error: done() called multiple times |
| 201 |
at Object.<anonymous> (mocha.test.js:1:63) |
| 202 |
at require (internal/module.js:11:18) |
| 203 |
at Array.forEach (<anonymous>) |
| 204 |
at startup (bootstrap_node.js:187:16) |
| 205 |
at bootstrap_node.js:608:3 |
| 206 |
``` |
| 207 |
|
| 208 |
## Assertions |
| 209 |
|
| 210 |
Mocha allows you to use any assertion library you wish. In the above example, we're using Node.js' built-in [assert][node-assert] module — but generally, if it throws an `Error`, it will work! This means you can use libraries such as: |
| 211 |
|
| 212 |
- [should.js][] - BDD style shown throughout these docs |
| 213 |
- [expect.js][] - `expect()` style assertions |
| 214 |
- [chai][] - `expect()`, `assert()` and `should`-style assertions |
| 215 |
- [better-assert][] - C-style self-documenting `assert()` |
| 216 |
- [unexpected][] - "the extensible BDD assertion toolkit" |
| 217 |
|
| 218 |
## Asynchronous Code |
| 219 |
|
| 220 |
By adding an argument (usually named `done`) to `it()` to a test callback, Mocha will know that it should wait for this function to be called to complete the test. This callback accepts both an `Error` instance (or subclass thereof) _or_ a falsy value; anything else is invalid usage and throws an error (usually causing a failed test). |
| 221 |
|
| 222 |
```js |
| 223 |
describe("User", function () { |
| 224 |
describe("#save()", function () { |
| 225 |
it("should save without error", function (done) { |
| 226 |
var user = new User("Luna"); |
| 227 |
user.save(function (err) { |
| 228 |
if (err) done(err); |
| 229 |
else done(); |
| 230 |
}); |
| 231 |
}); |
| 232 |
}); |
| 233 |
}); |
| 234 |
``` |
| 235 |
|
| 236 |
Alternatively, use the `done()` callback directly (which will handle an error argument, if it exists): |
| 237 |
|
| 238 |
```js |
| 239 |
describe("User", function () { |
| 240 |
describe("#save()", function () { |
| 241 |
it("should save without error", function (done) { |
| 242 |
var user = new User("Luna"); |
| 243 |
user.save(done); |
| 244 |
}); |
| 245 |
}); |
| 246 |
}); |
| 247 |
``` |
| 248 |
|
| 249 |
### Working with Promises |
| 250 |
|
| 251 |
Alternately, instead of using the `done()` callback, you may return a [Promise][mdn-promise]. This is useful if the APIs you are testing return promises instead of taking callbacks: |
| 252 |
|
| 253 |
```js |
| 254 |
beforeEach(function () { |
| 255 |
return db.clear().then(function () { |
| 256 |
return db.save([tobi, loki, jane]); |
| 257 |
}); |
| 258 |
}); |
| 259 |
|
| 260 |
describe("#find()", function () { |
| 261 |
it("respond with matching records", function () { |
| 262 |
return db.find({ type: "User" }).should.eventually.have.length(3); |
| 263 |
}); |
| 264 |
}); |
| 265 |
``` |
| 266 |
|
| 267 |
> The latter example uses [Chai as Promised][npm-chai-as-promised] for fluent promise assertions. |
| 268 |
|
| 269 |
In Mocha v3.0.0 and newer, returning a `Promise` _and_ calling `done()` will result in an exception, as this is generally a mistake: |
| 270 |
|
| 271 |
```js |
| 272 |
const assert = require("assert"); |
| 273 |
|
| 274 |
// antipattern |
| 275 |
it("should complete this test", function (done) { |
| 276 |
return new Promise(function (resolve) { |
| 277 |
assert.ok(true); |
| 278 |
resolve(); |
| 279 |
}).then(done); |
| 280 |
}); |
| 281 |
``` |
| 282 |
|
| 283 |
The above test will fail with `Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.`. In versions older than v3.0.0, the call to `done()` is effectively ignored. |
| 284 |
|
| 285 |
### Using async / await |
| 286 |
|
| 287 |
If your JS environment supports [async / await][mdn-async], you can also write asynchronous tests like this: |
| 288 |
|
| 289 |
```js |
| 290 |
beforeEach(async function () { |
| 291 |
await db.clear(); |
| 292 |
await db.save([tobi, loki, jane]); |
| 293 |
}); |
| 294 |
|
| 295 |
describe("#find()", function () { |
| 296 |
it("responds with matching records", async function () { |
| 297 |
const users = await db.find({ type: "User" }); |
| 298 |
users.should.have.length(3); |
| 299 |
}); |
| 300 |
}); |
| 301 |
``` |
| 302 |
|
| 303 |
### Limitations of asynchronous callbacks |
| 304 |
|
| 305 |
You can use all asynchronous callbacks (`done`, `Promise`, and `async`/`await`) in callbacks for `it()`, `before()`, `after()`, `beforeEach()`, `afterEach()`) but not `describe()` -- it must be synchronous. |
| 306 |
See [#5046](https://github.com/mochajs/mocha/pull/5046) for more information. |
| 307 |
|
| 308 |
## Synchronous Code |
| 309 |
|
| 310 |
When testing synchronous code, omit the callback and Mocha will automatically continue on to the next test. |
| 311 |
|
| 312 |
```js |
| 313 |
describe("Array", function () { |
| 314 |
describe("#indexOf()", function () { |
| 315 |
it("should return -1 when the value is not present", function () { |
| 316 |
[1, 2, 3].indexOf(5).should.equal(-1); |
| 317 |
[1, 2, 3].indexOf(0).should.equal(-1); |
| 318 |
}); |
| 319 |
}); |
| 320 |
}); |
| 321 |
``` |
| 322 |
|
| 323 |
## Arrow Functions |
| 324 |
|
| 325 |
Passing [arrow functions][mdn-arrow] (aka "lambdas") to Mocha is discouraged. Lambdas lexically bind `this` and cannot access the Mocha context. For example, the following code will fail: |
| 326 |
|
| 327 |
```js |
| 328 |
describe("my suite", () => { |
| 329 |
it("my test", () => { |
| 330 |
// should set the timeout of this test to 1000 ms; instead will fail |
| 331 |
this.timeout(1000); |
| 332 |
assert.ok(true); |
| 333 |
}); |
| 334 |
}); |
| 335 |
``` |
| 336 |
|
| 337 |
_If you do not need to use_ Mocha's context, lambdas should work. Be aware that using lambdas will be more painful to refactor if the need eventually arises! |
| 338 |
|
| 339 |
Alternatively, you can override certain context variables, such as test timeouts, by chain-calling methods of the created tests and/or hooks: |
| 340 |
|
| 341 |
```js |
| 342 |
describe("my suite", () => { |
| 343 |
beforeEach(() => {}).timeout(1000); |
| 344 |
it("my test", () => { |
| 345 |
assert.ok(true); |
| 346 |
}).timeout(1000); |
| 347 |
}).timeout(1000); |
| 348 |
``` |
| 349 |
|
| 350 |
## Hooks |
| 351 |
|
| 352 |
With its default "BDD"-style interface, Mocha provides the hooks `before()`, `after()`, `beforeEach()`, and `afterEach()`. These should be used to set up preconditions and clean up after your tests. |
| 353 |
|
| 354 |
```js |
| 355 |
describe("hooks", function () { |
| 356 |
before(function () { |
| 357 |
// runs once before the first test in this block |
| 358 |
}); |
| 359 |
|
| 360 |
after(function () { |
| 361 |
// runs once after the last test in this block |
| 362 |
}); |
| 363 |
|
| 364 |
beforeEach(function () { |
| 365 |
// runs before each test in this block |
| 366 |
}); |
| 367 |
|
| 368 |
afterEach(function () { |
| 369 |
// runs after each test in this block |
| 370 |
}); |
| 371 |
|
| 372 |
// test cases |
| 373 |
}); |
| 374 |
``` |
| 375 |
|
| 376 |
> Tests can appear before, after, or interspersed with your hooks. Hooks will run in the order they are defined, as appropriate; all `before()` hooks run (once), then any `beforeEach()` hooks, tests, any `afterEach()` hooks, and finally `after()` hooks (once). |
| 377 |
|
| 378 |
### Describing Hooks |
| 379 |
|
| 380 |
Any hook can be invoked with an optional description, making it easier to pinpoint errors in your tests. If a hook is given a named function, that name will be used if no description is supplied. |
| 381 |
|
| 382 |
```js |
| 383 |
beforeEach(function () { |
| 384 |
// beforeEach hook |
| 385 |
}); |
| 386 |
|
| 387 |
beforeEach(function namedFun() { |
| 388 |
// beforeEach:namedFun |
| 389 |
}); |
| 390 |
|
| 391 |
beforeEach("some description", function () { |
| 392 |
// beforeEach:some description |
| 393 |
}); |
| 394 |
``` |
| 395 |
|
| 396 |
### Asynchronous Hooks |
| 397 |
|
| 398 |
All hooks (`before()`, `after()`, `beforeEach()`, `afterEach()`) may be sync or async as well, behaving much like a regular test-case. For example, you may wish to populate database with dummy content before each test: |
| 399 |
|
| 400 |
```js |
| 401 |
describe("Connection", function () { |
| 402 |
var db = new Connection(), |
| 403 |
tobi = new User("tobi"), |
| 404 |
loki = new User("loki"), |
| 405 |
jane = new User("jane"); |
| 406 |
|
| 407 |
beforeEach(function (done) { |
| 408 |
db.clear(function (err) { |
| 409 |
if (err) return done(err); |
| 410 |
db.save([tobi, loki, jane], done); |
| 411 |
}); |
| 412 |
}); |
| 413 |
|
| 414 |
describe("#find()", function () { |
| 415 |
it("respond with matching records", function (done) { |
| 416 |
db.find({ type: "User" }, function (err, res) { |
| 417 |
if (err) return done(err); |
| 418 |
res.should.have.length(3); |
| 419 |
done(); |
| 420 |
}); |
| 421 |
}); |
| 422 |
}); |
| 423 |
}); |
| 424 |
``` |
| 425 |
|
| 426 |
### Root-Level Hooks |
| 427 |
|
| 428 |
A hook defined at the top scope of a test file (outside of a suite) is a _root hook_. |
| 429 |
|
| 430 |
As of v8.0.0, [Root Hook Plugins] are the preferred mechanism for setting root hooks. |
| 431 |
|
| 432 |
### Delayed Root Suite |
| 433 |
|
| 434 |
> _WARNING: Delayed root suites are incompatible with [parallel mode](#parallel-tests)._ |
| 435 |
|
| 436 |
If you need to perform asynchronous operations before any of your suites are run (e.g. for dynamically generating tests), you may delay the root suite. Run `mocha` with the `--delay` flag. This will attach a special callback function, `run()`, to the global context: |
| 437 |
|
| 438 |
```js |
| 439 |
const assert = require("assert"); |
| 440 |
|
| 441 |
const fn = async (x) => { |
| 442 |
return new Promise((resolve) => { |
| 443 |
setTimeout(resolve, 3000, 2 * x); |
| 444 |
}); |
| 445 |
}; |
| 446 |
|
| 447 |
// instead of an IIFE, you can use 'setImmediate' or 'nextTick' or 'setTimeout' |
| 448 |
(async function () { |
| 449 |
const z = await fn(3); |
| 450 |
|
| 451 |
describe("my suite", function () { |
| 452 |
it(`expected value ${z}`, function () { |
| 453 |
assert.strictEqual(z, 6); |
| 454 |
}); |
| 455 |
}); |
| 456 |
|
| 457 |
run(); |
| 458 |
})(); |
| 459 |
``` |
| 460 |
|
| 461 |
## Pending Tests |
| 462 |
|
| 463 |
"Pending" — as in "someone should write these test cases eventually" — test-cases are those _without_ a callback: |
| 464 |
|
| 465 |
```js |
| 466 |
describe("Array", function () { |
| 467 |
describe("#indexOf()", function () { |
| 468 |
// pending test below |
| 469 |
it("should return -1 when the value is not present"); |
| 470 |
}); |
| 471 |
}); |
| 472 |
``` |
| 473 |
|
| 474 |
Pending tests will be included in the test results, and marked as pending. A pending test is not considered a failed test. |
| 475 |
|
| 476 |
Read the [inclusive tests section](#inclusive-tests) for an example of conditionally marking a test as pending via `this.skip()`. |
| 477 |
|
| 478 |
## Exclusive Tests |
| 479 |
|
| 480 |
> _WARNING: Exclusive tests are incompatible with [parallel mode](#parallel-tests)._ |
| 481 |
|
| 482 |
The exclusivity feature allows you to run _only_ the specified suite or test-case |
| 483 |
by appending `.only()` to the function. Here's an example of executing only a particular suite: |
| 484 |
|
| 485 |
```js |
| 486 |
describe("Array", function () { |
| 487 |
describe.only("#indexOf()", function () { |
| 488 |
// ... |
| 489 |
}); |
| 490 |
}); |
| 491 |
``` |
| 492 |
|
| 493 |
_Note_: All nested suites will still be executed. |
| 494 |
|
| 495 |
Here's an example of executing an individual test case: |
| 496 |
|
| 497 |
```js |
| 498 |
describe("Array", function () { |
| 499 |
describe("#indexOf()", function () { |
| 500 |
it.only("should return -1 unless present", function () { |
| 501 |
// ... |
| 502 |
}); |
| 503 |
|
| 504 |
it("should return the index when present", function () { |
| 505 |
// ... |
| 506 |
}); |
| 507 |
}); |
| 508 |
}); |
| 509 |
``` |
| 510 |
|
| 511 |
Previous to v3.0.0, `.only()` used string matching to decide which tests to execute; this is no longer the case. In v3.0.0 or newer, `.only()` can be used multiple times to define a subset of tests to run: |
| 512 |
|
| 513 |
```js |
| 514 |
describe("Array", function () { |
| 515 |
describe("#indexOf()", function () { |
| 516 |
it.only("should return -1 unless present", function () { |
| 517 |
// this test will be run |
| 518 |
}); |
| 519 |
|
| 520 |
it.only("should return the index when present", function () { |
| 521 |
// this test will also be run |
| 522 |
}); |
| 523 |
|
| 524 |
it("should return -1 if called with a non-Array context", function () { |
| 525 |
// this test will not be run |
| 526 |
}); |
| 527 |
}); |
| 528 |
}); |
| 529 |
``` |
| 530 |
|
| 531 |
You may also choose multiple suites: |
| 532 |
|
| 533 |
```js |
| 534 |
describe("Array", function () { |
| 535 |
describe.only("#indexOf()", function () { |
| 536 |
it("should return -1 unless present", function () { |
| 537 |
// this test will be run |
| 538 |
}); |
| 539 |
|
| 540 |
it("should return the index when present", function () { |
| 541 |
// this test will also be run |
| 542 |
}); |
| 543 |
}); |
| 544 |
|
| 545 |
describe.only("#concat()", function () { |
| 546 |
it("should return a new Array", function () { |
| 547 |
// this test will also be run |
| 548 |
}); |
| 549 |
}); |
| 550 |
|
| 551 |
describe("#slice()", function () { |
| 552 |
it("should return a new Array", function () { |
| 553 |
// this test will not be run |
| 554 |
}); |
| 555 |
}); |
| 556 |
}); |
| 557 |
``` |
| 558 |
|
| 559 |
But _tests will have precedence_: |
| 560 |
|
| 561 |
```js |
| 562 |
describe("Array", function () { |
| 563 |
describe.only("#indexOf()", function () { |
| 564 |
it.only("should return -1 unless present", function () { |
| 565 |
// this test will be run |
| 566 |
}); |
| 567 |
|
| 568 |
it("should return the index when present", function () { |
| 569 |
// this test will not be run |
| 570 |
}); |
| 571 |
}); |
| 572 |
}); |
| 573 |
``` |
| 574 |
|
| 575 |
_Note_: Hooks, if present, will still be executed. |
| 576 |
|
| 577 |
> Be mindful not to commit usages of `.only()` to version control, unless you really mean it! To do so one can run mocha with the option `--forbid-only` in the continuous integration test command (or in a git precommit hook). |
| 578 |
|
| 579 |
## Inclusive Tests |
| 580 |
|
| 581 |
This feature is the inverse of `.only()`. By appending `.skip()`, you may tell Mocha to ignore test case(s). Anything skipped will be marked as [pending](#pending-tests), and reported as such. Here's an example of skipping an individual test: |
| 582 |
|
| 583 |
```js |
| 584 |
describe("Array", function () { |
| 585 |
describe("#indexOf()", function () { |
| 586 |
it.skip("should return -1 unless present", function () { |
| 587 |
// this test will not be run |
| 588 |
}); |
| 589 |
|
| 590 |
it("should return the index when present", function () { |
| 591 |
// this test will be run |
| 592 |
}); |
| 593 |
}); |
| 594 |
}); |
| 595 |
``` |
| 596 |
|
| 597 |
You can also put `.skip()` on an entire suite. This is equivalent to appending `.skip()` onto all tests in the suite. Hooks in the suite are also skipped. |
| 598 |
|
| 599 |
```js |
| 600 |
describe("Array", function () { |
| 601 |
describe.skip("#indexOf()", function () { |
| 602 |
it("should return -1 unless present", function () { |
| 603 |
// this test will not be run |
| 604 |
}); |
| 605 |
}); |
| 606 |
}); |
| 607 |
``` |
| 608 |
|
| 609 |
_Note_: Code in skipped suites, that is placed outside of hooks or tests is still executed, as mocha will still invoke the suite function to build up the suite structure for visualization. |
| 610 |
|
| 611 |
> _Best practice_: Use `.skip()` instead of commenting tests out. |
| 612 |
|
| 613 |
You may also skip _at runtime_ using `this.skip()`. If a test needs an environment or configuration which cannot be detected beforehand, a runtime skip is appropriate. For example: |
| 614 |
|
| 615 |
```js |
| 616 |
it('should only test in the correct environment', function() { |
| 617 |
if (/* check test environment */) { |
| 618 |
// make assertions |
| 619 |
} else { |
| 620 |
this.skip(); |
| 621 |
} |
| 622 |
}); |
| 623 |
``` |
| 624 |
|
| 625 |
The above test will be reported as [pending](#pending-tests). It's also important to note that calling `this.skip()` will effectively _abort_ the test. |
| 626 |
|
| 627 |
> _Best practice_: To avoid confusion, do not execute further instructions in a test or hook after calling `this.skip()`. |
| 628 |
|
| 629 |
Contrast the above test with the following code: |
| 630 |
|
| 631 |
```js |
| 632 |
it('should only test in the correct environment', function() { |
| 633 |
if (/* check test environment */) { |
| 634 |
// make assertions |
| 635 |
} else { |
| 636 |
// do nothing |
| 637 |
} |
| 638 |
}); |
| 639 |
``` |
| 640 |
|
| 641 |
Because this test _does nothing_, it will be reported as _passing_. |
| 642 |
|
| 643 |
> _Best practice_: Don't do nothing! A test should make an assertion or use `this.skip()`. |
| 644 |
|
| 645 |
To skip _multiple_ tests in this manner, use `this.skip()` in a "before all" hook: |
| 646 |
|
| 647 |
```js |
| 648 |
before(function() { |
| 649 |
if (/* check test environment */) { |
| 650 |
// setup code |
| 651 |
} else { |
| 652 |
this.skip(); |
| 653 |
} |
| 654 |
}); |
| 655 |
``` |
| 656 |
|
| 657 |
This will skip all `it`, `beforeEach/afterEach`, and `describe` blocks within the suite. `before/after` hooks are skipped unless they are defined at the same level as the hook containing `this.skip()`. |
| 658 |
|
| 659 |
```js |
| 660 |
describe("outer", function () { |
| 661 |
before(function () { |
| 662 |
this.skip(); |
| 663 |
}); |
| 664 |
|
| 665 |
after(function () { |
| 666 |
// will be executed |
| 667 |
}); |
| 668 |
|
| 669 |
describe("inner", function () { |
| 670 |
before(function () { |
| 671 |
// will be skipped |
| 672 |
}); |
| 673 |
|
| 674 |
after(function () { |
| 675 |
// will be skipped |
| 676 |
}); |
| 677 |
}); |
| 678 |
}); |
| 679 |
``` |
| 680 |
|
| 681 |
> _Updated in v7.0.0:_ skipping a test within an "after all" hook is disallowed and will throw an exception. Use a return statement or other means to abort hook execution. |
| 682 |
|
| 683 |
Before Mocha v3.0.0, `this.skip()` was not supported in asynchronous tests and hooks. |
| 684 |
|
| 685 |
## Retry Tests |
| 686 |
|
| 687 |
You can choose to retry failed tests up to a certain number of times. This feature is designed to handle end-to-end tests (functional tests/Selenium...) where resources cannot be easily mocked/stubbed. **It's not recommended to use this feature for unit tests**. |
| 688 |
|
| 689 |
This feature does re-run a failed test and its corresponding `beforeEach/afterEach` hooks, but not `before/after` hooks. `this.retries()` has no effect on failing hooks. |
| 690 |
|
| 691 |
**NOTE**: Example below was written using Selenium webdriver (which [overwrites global Mocha hooks][selenium-webdriver-testing] for `Promise` chain). |
| 692 |
|
| 693 |
```js |
| 694 |
describe("retries", function () { |
| 695 |
// Retry all tests in this suite up to 4 times |
| 696 |
this.retries(4); |
| 697 |
|
| 698 |
beforeEach(function () { |
| 699 |
browser.get("http://www.yahoo.com"); |
| 700 |
}); |
| 701 |
|
| 702 |
it("should succeed on the 3rd try", function () { |
| 703 |
// Specify this test to only retry up to 2 times |
| 704 |
this.retries(2); |
| 705 |
expect($(".foo").isDisplayed()).to.eventually.be.true; |
| 706 |
}); |
| 707 |
}); |
| 708 |
``` |
| 709 |
|
| 710 |
## Dynamically Generating Tests |
| 711 |
|
| 712 |
Given Mocha's use of function expressions to define suites and test cases, it's straightforward to generate your tests dynamically. No special syntax is required — plain ol' JavaScript can be used to achieve functionality similar to "parameterized" tests, which you may have seen in other frameworks. |
| 713 |
|
| 714 |
Take the following example: |
| 715 |
|
| 716 |
```js |
| 717 |
const assert = require("assert"); |
| 718 |
|
| 719 |
function add(args) { |
| 720 |
return args.reduce((prev, curr) => prev + curr, 0); |
| 721 |
} |
| 722 |
|
| 723 |
describe("add()", function () { |
| 724 |
const tests = [ |
| 725 |
{ args: [1, 2], expected: 3 }, |
| 726 |
{ args: [1, 2, 3], expected: 6 }, |
| 727 |
{ args: [1, 2, 3, 4], expected: 10 }, |
| 728 |
]; |
| 729 |
|
| 730 |
tests.forEach(({ args, expected }) => { |
| 731 |
it(`correctly adds ${args.length} args`, function () { |
| 732 |
const res = add(args); |
| 733 |
assert.strictEqual(res, expected); |
| 734 |
}); |
| 735 |
}); |
| 736 |
}); |
| 737 |
``` |
| 738 |
|
| 739 |
The above code will produce a suite with three specs: |
| 740 |
|
| 741 |
```bash |
| 742 |
$ mocha |
| 743 |
|
| 744 |
add() |
| 745 |
✓ correctly adds 2 args |
| 746 |
✓ correctly adds 3 args |
| 747 |
✓ correctly adds 4 args |
| 748 |
``` |
| 749 |
|
| 750 |
Tests added inside a `.forEach` handler often don't play well with editor plugins, especially with "right-click run" features. |
| 751 |
Another way to parameterize tests is to generate them with a closure. This following example is equivalent to the one above: |
| 752 |
|
| 753 |
```js |
| 754 |
describe("add()", function () { |
| 755 |
const testAdd = ({ args, expected }) => |
| 756 |
function () { |
| 757 |
const res = add(args); |
| 758 |
assert.strictEqual(res, expected); |
| 759 |
}; |
| 760 |
|
| 761 |
it("correctly adds 2 args", testAdd({ args: [1, 2], expected: 3 })); |
| 762 |
it("correctly adds 3 args", testAdd({ args: [1, 2, 3], expected: 6 })); |
| 763 |
it("correctly adds 4 args", testAdd({ args: [1, 2, 3, 4], expected: 10 })); |
| 764 |
}); |
| 765 |
``` |
| 766 |
|
| 767 |
With `top-level await` you can collect your test data in a dynamic and asynchronous way while the test file is being loaded. |
| 768 |
|
| 769 |
See also [`--delay`](#delayed-root-suite) for CommonJS modules without `top-level await`. |
| 770 |
|
| 771 |
```js |
| 772 |
// testfile.mjs |
| 773 |
import assert from "assert"; |
| 774 |
|
| 775 |
// top-level await: Node >= v14.8.0 with ESM test file |
| 776 |
const tests = await new Promise((resolve) => { |
| 777 |
setTimeout(resolve, 5000, [ |
| 778 |
{ args: [1, 2], expected: 3 }, |
| 779 |
{ args: [1, 2, 3], expected: 6 }, |
| 780 |
{ args: [1, 2, 3, 4], expected: 10 }, |
| 781 |
]); |
| 782 |
}); |
| 783 |
|
| 784 |
// in suites ASYNCHRONOUS callbacks are NOT supported |
| 785 |
describe("add()", function () { |
| 786 |
tests.forEach(({ args, expected }) => { |
| 787 |
it(`correctly adds ${args.length} args`, function () { |
| 788 |
const res = args.reduce((sum, curr) => sum + curr, 0); |
| 789 |
assert.strictEqual(res, expected); |
| 790 |
}); |
| 791 |
}); |
| 792 |
}); |
| 793 |
``` |
| 794 |
|
| 795 |
<h2 id="test-duration">Test duration</h2> |
| 796 |
|
| 797 |
Many reporters will display test duration and flag tests that are slow (default: 75ms), as shown here with the SPEC reporter: |
| 798 |
|
| 799 |
{:class="screenshot" loading="lazy"} |
| 800 |
|
| 801 |
There are three levels of test duration (depicted in the following image): |
| 802 |
|
| 803 |
1. FAST: Tests that run within half of the "slow" threshold will show the duration in green (if at all). |
| 804 |
2. NORMAL: Tests that run exceeding half of the threshold (but still within it) will show the duration in yellow. |
| 805 |
3. SLOW: Tests that run exceeding the threshold will show the duration in red. |
| 806 |
|
| 807 |
{:class="screenshot" loading="lazy"} |
| 808 |
|
| 809 |
To tweak what's considered "slow", you can use the `slow()` method: |
| 810 |
|
| 811 |
```js |
| 812 |
describe("something slow", function () { |
| 813 |
this.slow(300000); // five minutes |
| 814 |
|
| 815 |
it("should take long enough for me to go make a sandwich", function () { |
| 816 |
// ... |
| 817 |
}); |
| 818 |
}); |
| 819 |
``` |
| 820 |
|
| 821 |
## Timeouts |
| 822 |
|
| 823 |
### Suite-level |
| 824 |
|
| 825 |
Suite-level timeouts may be applied to entire test "suites", or disabled via `this.timeout(0)`. This will be inherited by all nested suites and test-cases that do not override the value. |
| 826 |
|
| 827 |
```js |
| 828 |
describe("a suite of tests", function () { |
| 829 |
this.timeout(500); |
| 830 |
|
| 831 |
it("should take less than 500ms", function (done) { |
| 832 |
setTimeout(done, 300); |
| 833 |
}); |
| 834 |
|
| 835 |
it("should take less than 500ms as well", function (done) { |
| 836 |
setTimeout(done, 250); |
| 837 |
}); |
| 838 |
}); |
| 839 |
``` |
| 840 |
|
| 841 |
### Test-level |
| 842 |
|
| 843 |
Test-specific timeouts may also be applied, or the use of `this.timeout(0)` to disable timeouts all together: |
| 844 |
|
| 845 |
```js |
| 846 |
it("should take less than 500ms", function (done) { |
| 847 |
this.timeout(500); |
| 848 |
setTimeout(done, 300); |
| 849 |
}); |
| 850 |
``` |
| 851 |
|
| 852 |
### Hook-level |
| 853 |
|
| 854 |
Hook-level timeouts may also be applied: |
| 855 |
|
| 856 |
```js |
| 857 |
describe("a suite of tests", function () { |
| 858 |
beforeEach(function (done) { |
| 859 |
this.timeout(3000); // A very long environment setup. |
| 860 |
setTimeout(done, 2500); |
| 861 |
}); |
| 862 |
}); |
| 863 |
``` |
| 864 |
|
| 865 |
Again, use `this.timeout(0)` to disable the timeout for a hook. |
| 866 |
|
| 867 |
> In v3.0.0 or newer, a parameter passed to `this.timeout()` greater than the [maximum delay value][mdn-settimeout-maxdelay] will cause the timeout to be disabled. |
| 868 |
> In v8.0.0 or newer, `this.enableTimeouts()` has been removed. |
| 869 |
> **Warning:** With async tests if you disable timeouts via `this.timeout(0)` and then do not call `done()`, your test will exit silently. |
| 870 |
|
| 871 |
## Diffs |
| 872 |
|
| 873 |
Mocha supports the `err.expected` and `err.actual` properties of any thrown `AssertionError`s from an assertion library. Mocha will attempt to display the difference between what was expected, and what the assertion actually saw. Here's an example of a "string" diff using `--inline-diffs`: |
| 874 |
|
| 875 |
{:class="screenshot" loading="lazy"} |
| 876 |
|
| 877 |
## Command-Line Usage |
| 878 |
|
| 879 |
``` |
| 880 |
{{ usage }} |
| 881 |
``` |
| 882 |
|
| 883 |
### `--allow-uncaught` |
| 884 |
|
| 885 |
By default, Mocha will attempt to trap uncaught exceptions thrown from running tests and report these as test failures. Use `--allow-uncaught` to disable this behavior and allow uncaught exceptions to propagate. Will typically cause the process to crash. |
| 886 |
|
| 887 |
This flag is useful when debugging particularly difficult-to-track exceptions. |
| 888 |
|
| 889 |
### `--async-only, -A` |
| 890 |
|
| 891 |
Enforce a rule that tests must be written in "async" style, meaning each test provides a `done` callback or returns a `Promise`. Non-compliant tests will be marked as failures. |
| 892 |
|
| 893 |
### `--bail, -b` |
| 894 |
|
| 895 |
Causes Mocha to stop running tests after the first test failure it encounters. Corresponding "after each" and "after all" hooks are executed for potential cleanup. |
| 896 |
|
| 897 |
`--bail` does _not_ imply `--exit`. |
| 898 |
|
| 899 |
### `--check-leaks` |
| 900 |
|
| 901 |
Use this option to have Mocha check for global variables that are leaked while running tests. Specify globals that are acceptable via the `--global` option (for example: `--check-leaks --global jQuery --global MyLib`). |
| 902 |
|
| 903 |
### `--compilers` |
| 904 |
|
| 905 |
> _`--compilers` was removed in v6.0.0. See [further explanation and workarounds][mocha-wiki-compilers]._ |
| 906 |
|
| 907 |
### `--dry-run` |
| 908 |
|
| 909 |
> _Since v9.0.0_ Report tests without executing any of them, neither tests nor hooks. |
| 910 |
|
| 911 |
### `--exit` |
| 912 |
|
| 913 |
> _Updated in v4.0.0._ |
| 914 |
|
| 915 |
TL;DR: If your tests hang after an upgrade to Mocha v4.0.0 or newer, use `--exit` for a quick (though not necessarily recommended) fix. |
| 916 |
|
| 917 |
_Prior to_ version v4.0.0, _by default_, Mocha would force its own process to exit once it was finished executing all tests. This behavior enables a set of potential problems; it's indicative of tests (or fixtures, harnesses, code under test, etc.) which don't clean up after themselves properly. Ultimately, "dirty" tests can (but not always) lead to _false positive_ or _false negative_ results. |
| 918 |
|
| 919 |
"Hanging" most often manifests itself if a server is still listening on a port, or a socket is still open, etc. It can also be something like a runaway `setInterval()`, or even an errant `Promise` that never fulfilled. |
| 920 |
|
| 921 |
The _default behavior_ in v4.0.0 (and newer) is `--no-exit`, where previously it was `--exit`. |
| 922 |
|
| 923 |
**The easiest way to "fix" the issue is to pass `--exit` to the Mocha process.** It _can_ be time-consuming to debug — because it's not always obvious where the problem is — but it _is_ recommended to do so. |
| 924 |
|
| 925 |
To ensure your tests aren't leaving messes around, here are some ideas to get started: |
| 926 |
|
| 927 |
- See the [Node.js guide to debugging][node-inspector] |
| 928 |
- Use the new [`async_hooks`][node-async-hooks] API ([example][gist-async-hooks]) |
| 929 |
- Try something like [wtfnode][npm-wtfnode] |
| 930 |
- Use [`.only`](#exclusive-tests) until you find the test that causes Mocha to hang |
| 931 |
|
| 932 |
### `--pass-on-failing-test-suite` |
| 933 |
|
| 934 |
> _Since v10.7.0_ |
| 935 |
|
| 936 |
If set to `true`, Mocha returns exit code `0` even if there are failed tests during run. |
| 937 |
|
| 938 |
### `--fail-zero` |
| 939 |
|
| 940 |
> _Since v9.1.0_ |
| 941 |
|
| 942 |
Fail test run if no tests are encountered with `exit-code: 1`. |
| 943 |
|
| 944 |
### `--forbid-only` |
| 945 |
|
| 946 |
Enforce a rule that tests may not be exclusive (use of e.g., `describe.only()` or `it.only()` is disallowed). |
| 947 |
|
| 948 |
`--forbid-only` causes Mocha to fail when an exclusive ("only'd") test or suite is encountered, and it will abort further test execution. |
| 949 |
|
| 950 |
### `--forbid-pending` |
| 951 |
|
| 952 |
Enforce a rule that tests may not be skipped (use of e.g., `describe.skip()`, `it.skip()`, or `this.skip()` anywhere is disallowed). |
| 953 |
|
| 954 |
`--forbid-pending` causes Mocha to fail when a skipped ("pending") test or suite is encountered, and it will abort further test execution. |
| 955 |
|
| 956 |
### `--global <variable-name>` |
| 957 |
|
| 958 |
> _Updated in v6.0.0; the option is `--global` and `--globals` is now an alias._ |
| 959 |
|
| 960 |
Define a global variable name. For example, suppose your app deliberately exposes a global named `app` and `YUI`, you may want to add `--global app --global YUI`. |
| 961 |
|
| 962 |
`--global` accepts wildcards. You could do `--global '*bar'` and it would match `foobar`, `barbar`, etc. You can also pass in `'*'` to ignore all globals. |
| 963 |
|
| 964 |
`--global` can accept a comma-delimited list; `--global app,YUI` is equivalent to `--global app --global YUI`. |
| 965 |
|
| 966 |
By using this option in conjunction with `--check-leaks`, you can specify a whitelist of known global variables that you _expect_ to leak into global scope. |
| 967 |
|
| 968 |
### `--posix-exit-codes` |
| 969 |
|
| 970 |
Exits with standard POSIX exit codes instead of the number of failed tests. |
| 971 |
|
| 972 |
Those exit codes are: |
| 973 |
|
| 974 |
- `0`: if all tests passed |
| 975 |
- `1`: if any test failed |
| 976 |
- `128 + <signal>` if given a signal, such as: |
| 977 |
- 134: `SIGABRT` (`128 + 6`) |
| 978 |
- 143: `SIGTERM` (`128 + 15`) |
| 979 |
|
| 980 |
### `--retries <n>` |
| 981 |
|
| 982 |
Retries failed tests `n` times. |
| 983 |
|
| 984 |
Mocha does not retry test failures by default. |
| 985 |
|
| 986 |
### `--slow <ms>, -s <ms>` |
| 987 |
|
| 988 |
Specify the "slow" test threshold in milliseconds. Mocha uses this to highlight test cases that are taking too long. "Slow" tests are not considered failures. |
| 989 |
|
| 990 |
Note: A test that executes for _half_ of the "slow" time will be highlighted _in yellow_ with the default `spec` reporter; a test that executes for entire "slow" time will be highlighted _in red_. |
| 991 |
|
| 992 |
### `--timeout <ms>, -t <ms>` |
| 993 |
|
| 994 |
> _Update in v6.0.0: `--timeout 0` is implied when invoking Mocha using inspect flags. `--timeout 99999999` is no longer needed._ |
| 995 |
|
| 996 |
Specifies the test case timeout, defaulting to two (2) seconds (2000 milliseconds). Tests taking longer than this amount of time will be marked as failed. |
| 997 |
|
| 998 |
To override you may pass the timeout in milliseconds, or a value with the `s` suffix, e.g., `--timeout 2s` and `--timeout 2000` are equivalent. |
| 999 |
|
| 1000 |
To disable timeouts, use `--timeout 0`. |
| 1001 |
|
| 1002 |
Note: synchronous (blocking) tests are also bound by the timeout, but they will not complete until the code stops blocking. Infinite loops will still be infinite loops! |
| 1003 |
|
| 1004 |
### `--ui <name>, -u <name>` |
| 1005 |
|
| 1006 |
The `--ui` option lets you specify the interface to use, defaulting to `bdd`. |
| 1007 |
|
| 1008 |
### `--color, -c, --colors` |
| 1009 |
|
| 1010 |
> _Updated in v6.0.0. `--colors` is now an alias for `--color`._ |
| 1011 |
|
| 1012 |
"Force" color output to be enabled, or alternatively force it to be disabled via `--no-color`. By default, Mocha uses the [supports-color][npm-supports-color] module to decide. |
| 1013 |
|
| 1014 |
In some cases, color output will be explicitly suppressed by certain reporters outputting in a machine-readable format. |
| 1015 |
|
| 1016 |
### `--diff` |
| 1017 |
|
| 1018 |
When possible, show the difference between expected and actual values when an assertion failure is encountered. |
| 1019 |
|
| 1020 |
This flag is unusual in that it **defaults to `true`**; use `--no-diff` to suppress Mocha's own diff output. |
| 1021 |
|
| 1022 |
Some assertion libraries will supply their own diffs, in which case Mocha's will not be used, regardless of the default value. |
| 1023 |
|
| 1024 |
Mocha's own diff output does not conform to any known standards, and is designed to be human-readable. |
| 1025 |
|
| 1026 |
> _Since v9.2.1_ |
| 1027 |
|
| 1028 |
By default strings are truncated to 8192 characters before generating a diff. This is to prevent performance problems with large strings. |
| 1029 |
|
| 1030 |
It can however make the output harder to interpret when comparing large strings. Therefore it is possible to configure this value using `--reporter-option maxDiffSize=[number]`. |
| 1031 |
|
| 1032 |
A value of 0 indicates no limit, default is 8192 characters. |
| 1033 |
|
| 1034 |
### `--full-trace` |
| 1035 |
|
| 1036 |
Enable "full" stack traces. By default, Mocha attempts to distill stack traces into less noisy (though still useful) output. |
| 1037 |
|
| 1038 |
This flag is helpful when debugging a suspected issue within Mocha or Node.js itself. |
| 1039 |
|
| 1040 |
### `--inline-diffs` |
| 1041 |
|
| 1042 |
Enable "inline" diffs, an alternative output for diffing strings. |
| 1043 |
|
| 1044 |
Useful when working with large strings. |
| 1045 |
|
| 1046 |
Does nothing if an assertion library supplies its own diff output. |
| 1047 |
|
| 1048 |
### `--reporter <name>, -R <name>` |
| 1049 |
|
| 1050 |
Specify the reporter that will be used, defaulting to `spec`. |
| 1051 |
|
| 1052 |
Allows use of third-party reporters. For example, [mocha-lcov-reporter][npm-mocha-lcov-reporter] may be used with `--reporter mocha-lcov-reporter` after it has been installed. |
| 1053 |
|
| 1054 |
### `--reporter-option <option>, -O <option>, --reporter-options <option>` |
| 1055 |
|
| 1056 |
> _Updated in v6.0.0. Can be specified multiple times. `--reporter-options` is now an alias for `--reporter-option`._ |
| 1057 |
|
| 1058 |
Provide options specific to a reporter in `<key>=<value>` format, e.g., `--reporter tap --reporter-option tapVersion=13`. |
| 1059 |
|
| 1060 |
Not all reporters accept options. |
| 1061 |
|
| 1062 |
Can be specified as a comma-delimited list. |
| 1063 |
|
| 1064 |
### `--config <path>` |
| 1065 |
|
| 1066 |
> _Since v6.0.0_ |
| 1067 |
|
| 1068 |
Specify an explicit path to a [configuration file](#configuring-mocha-nodejs). |
| 1069 |
|
| 1070 |
By default, Mocha will search for a config file if `--config` is not specified; use `--no-config` to suppress this behavior. |
| 1071 |
|
| 1072 |
### `--node-option <name>, -n <name>` |
| 1073 |
|
| 1074 |
> _Since v9.1.0_ |
| 1075 |
|
| 1076 |
For Node.js and V8 options. Mocha forwards these options to Node.js by spawning a new child-process. |
| 1077 |
|
| 1078 |
The options are set without leading dashes `--`, e.g. `-n require=foo -n unhandled-rejections=strict` |
| 1079 |
|
| 1080 |
Can also be specified as a comma-delimited list: `-n require=foo,unhandled-rejections=strict` |
| 1081 |
|
| 1082 |
### `--opts <path>` |
| 1083 |
|
| 1084 |
> _Removed in v8.0.0. Please use [configuration file](#configuring-mocha-nodejs) instead._ |
| 1085 |
|
| 1086 |
### `--package <path>` |
| 1087 |
|
| 1088 |
> _Since v6.0.0_ |
| 1089 |
|
| 1090 |
Specify an explicit path to a [`package.json` file](#configuring-mocha-nodejs) (ostensibly containing configuration in a `mocha` property). |
| 1091 |
|
| 1092 |
By default, Mocha looks for a `package.json` in the current working directory or nearest ancestor, and will use the first file found (regardless of whether it contains a `mocha` property); to suppress `package.json` lookup, use `--no-package`. |
| 1093 |
|
| 1094 |
### `--extension <ext>` |
| 1095 |
|
| 1096 |
Files having this extension will be considered test files. Defaults to `js`. |
| 1097 |
|
| 1098 |
Specifying `--extension` will _remove_ `.js` as a test file extension; use `--extension js` to re-add it. For example, to load `.mjs` and `.js` test files, you must supply `--extension mjs --extension js`. |
| 1099 |
|
| 1100 |
The option can be given multiple times. The option accepts a comma-delimited list: `--extension a,b` is equivalent to `--extension a --extension b`. |
| 1101 |
|
| 1102 |
> _Since v8.2.0_ |
| 1103 |
|
| 1104 |
`--extension` now supports multipart extensions (e.g., `spec.js`), leading dots (`.js`) and combinations thereof (`.spec.js`); |
| 1105 |
|
| 1106 |
### `--file <file>` |
| 1107 |
|
| 1108 |
> _WARNING: `--file` is incompatible with [parallel mode](#parallel-tests)._ |
| 1109 |
|
| 1110 |
Explicitly _include_ a test file to be loaded before other test files. Multiple uses of `--file` are allowed, and will be loaded in order given. |
| 1111 |
|
| 1112 |
Useful if you want to declare, for example, hooks to be run before every test across all other test files. |
| 1113 |
|
| 1114 |
Files specified this way are not affected by `--sort` or `--recursive`. |
| 1115 |
|
| 1116 |
Files specified in this way should contain one or more suites, tests or hooks. If this is not the case, consider `--require` instead. |
| 1117 |
|
| 1118 |
### `--ignore <file|directory|glob>, --exclude <file|directory|glob>,` |
| 1119 |
|
| 1120 |
Explicitly ignore one or more test files, directories or globs (e.g., `some/**/files*`) that would otherwise be loaded. |
| 1121 |
|
| 1122 |
Can be specified multiple times. |
| 1123 |
|
| 1124 |
> _Since v10.0.0:_ In Windows always use forward-slashes `/` as path separator. |
| 1125 |
|
| 1126 |
Files specified using `--file` _are not affected_ by this option. |
| 1127 |
|
| 1128 |
### `--recursive` |
| 1129 |
|
| 1130 |
When looking for test files, recurse into subdirectories. |
| 1131 |
|
| 1132 |
See `--extension` for defining which files are considered test files. |
| 1133 |
|
| 1134 |
### `--require <module>, -r <module>` |
| 1135 |
|
| 1136 |
Require a module before loading the user interface or test files. This is useful for: |
| 1137 |
|
| 1138 |
- Test harnesses |
| 1139 |
- Assertion libraries that augment built-ins or global scope (such as [should.js][npm-should.js]) |
| 1140 |
- Compilers such as Babel via [@babel/register][npm-babel-register] or TypeScript via [ts-node][npm-ts-node] (using `--require ts-node/register`). See [Babel][example-babel] or [TypeScript][example-typescript] working examples. |
| 1141 |
|
| 1142 |
Modules required in this manner are expected to do work synchronously; Mocha won't wait for async tasks in a required module to finish. |
| 1143 |
|
| 1144 |
**You cannot use `--require` to set hooks**. If you want to set hooks to run, e.g., before each test, use a [Root Hook Plugin](#root-hook-plugins). |
| 1145 |
|
| 1146 |
> As of v8.0.0, Mocha supports `--require` for [NodeJS native ESM](#nodejs-native-esm-support). There is no separate `--import` flag. |
| 1147 |
|
| 1148 |
### `--sort, -S` |
| 1149 |
|
| 1150 |
> _WARNING: `--sort` is incompatible with [parallel mode](#parallel-tests)._ |
| 1151 |
|
| 1152 |
Sort test files (by absolute path) using [Array.prototype.sort][mdn-array-sort]. |
| 1153 |
|
| 1154 |
### `--watch, -w` |
| 1155 |
|
| 1156 |
Rerun tests on file changes. |
| 1157 |
|
| 1158 |
The `--watch-files` and `--watch-ignore` options can be used to control which files are watched for changes. |
| 1159 |
|
| 1160 |
Tests may be rerun manually by typing ⓡ ⓢ ⏎ (same shortcut as `nodemon`). |
| 1161 |
|
| 1162 |
### `--watch-files <file|directory|glob>` |
| 1163 |
|
| 1164 |
> _Since v7.0.0_ |
| 1165 |
|
| 1166 |
List of paths or globs to watch when `--watch` is set. If a file matching the given glob changes or is added or removed mocha will rerun all tests. |
| 1167 |
|
| 1168 |
If the path is a directory all files and subdirectories will be watched. |
| 1169 |
|
| 1170 |
By default all files in the current directory having one of the extensions provided by `--extension` and not contained in the `node_modules` or `.git` folders are watched. |
| 1171 |
|
| 1172 |
The option can be given multiple times. The option accepts a comma-delimited list: `--watch-files a,b` is equivalent to `--watch-files a --watch-files b` |
| 1173 |
|
| 1174 |
### `--watch-ignore <file|directory|glob>` |
| 1175 |
|
| 1176 |
> _Since v7.0.0_ |
| 1177 |
|
| 1178 |
List of paths or globs to exclude from watching. Defaults to `node_modules` and `.git`. |
| 1179 |
|
| 1180 |
To exclude all files in a directory it is preferable to use `foo/bar` instead of `foo/bar/**/*`. The latter will still watch the directory `foo/bar` but will ignore all changes to the content of that directory. |
| 1181 |
|
| 1182 |
The option can be given multiple times. The option accepts a comma-delimited list: `--watch-ignore a,b` is equivalent to `--watch-ignore a --watch-ignore b` |
| 1183 |
|
| 1184 |
### `--fgrep <string>, -f <string>` |
| 1185 |
|
| 1186 |
> _BREAKING CHANGE in v6.0.0; now mutually exclusive with `--grep`._ |
| 1187 |
|
| 1188 |
Cause Mocha to only run tests having titles containing the given `string`. |
| 1189 |
|
| 1190 |
Mutually exclusive with `--grep`. |
| 1191 |
|
| 1192 |
### `--grep <regexp>, -g <regexp>` |
| 1193 |
|
| 1194 |
> _BREAKING CHANGE in v6.0.0; now mutually exclusive with `--fgrep`._ |
| 1195 |
|
| 1196 |
Cause Mocha to only run tests matching the given `regexp`, which is internally compiled to a [RegExp][mdn-regexp]. |
| 1197 |
|
| 1198 |
Suppose, for example, you have "api" related tests, as well as "app" related tests, as shown in the following snippet; One could use `--grep api` or `--grep app` to run one or the other. The same goes for any other part of a suite or test-case title, `--grep users` would be valid as well, or even `--grep GET`. |
| 1199 |
|
| 1200 |
And another option with double quotes: `--grep "groupA|groupB"`. |
| 1201 |
|
| 1202 |
And for more complex criteria: `--grep "/get/i"`. Some shells as e.g. Git-Bash-for-Windows may require: `--grep "'/get/i'"`. Using flags other than the `ignoreCase /i` (especially `/g` and `/y`) may lead to unpredictable results. |
| 1203 |
|
| 1204 |
```js |
| 1205 |
describe("api", function () { |
| 1206 |
describe("GET /api/users groupA", function () { |
| 1207 |
it("respond with an array of users", function () { |
| 1208 |
// ... |
| 1209 |
}); |
| 1210 |
}); |
| 1211 |
}); |
| 1212 |
|
| 1213 |
describe("app", function () { |
| 1214 |
describe("GET /users groupB", function () { |
| 1215 |
it("respond with an array of users", function () { |
| 1216 |
// ... |
| 1217 |
}); |
| 1218 |
}); |
| 1219 |
}); |
| 1220 |
``` |
| 1221 |
|
| 1222 |
Mutually exclusive with `--fgrep`. |
| 1223 |
|
| 1224 |
### `--invert` |
| 1225 |
|
| 1226 |
Use the _inverse_ of the match specified by `--grep` or `fgrep`. |
| 1227 |
|
| 1228 |
Requires either `--grep` or `--fgrep` (but not both). |
| 1229 |
|
| 1230 |
### `--inspect, --inspect-brk, inspect` |
| 1231 |
|
| 1232 |
Enables Node.js' inspector. |
| 1233 |
|
| 1234 |
Use `--inspect` / `--inspect-brk` to launch the V8 inspector for use with Chrome Dev Tools. |
| 1235 |
|
| 1236 |
Use `inspect` to launch Node.js' internal debugger. |
| 1237 |
|
| 1238 |
All of these options are mutually exclusive. |
| 1239 |
|
| 1240 |
Implies `--timeout 0`. |
| 1241 |
|
| 1242 |
### `--parallel, -p` |
| 1243 |
|
| 1244 |
> _Since v.8.0.0._ |
| 1245 |
|
| 1246 |
Use the `--parallel` flag to run tests in a worker pool. |
| 1247 |
|
| 1248 |
Each test file will be put into a queue and executed as workers become available. |
| 1249 |
|
| 1250 |
**NOTICE**: `--parallel` has certain implications for Mocha's behavior which you must be aware of. Read more about [running tests in parallel](#parallel-tests). |
| 1251 |
|
| 1252 |
### `--jobs <count>, -j <count>` |
| 1253 |
|
| 1254 |
> _Since v.8.0.0._ |
| 1255 |
|
| 1256 |
Use `--jobs <count>` to specify the _maximum_ number of processes in the worker pool. |
| 1257 |
|
| 1258 |
The default value is the _number of CPU cores_ less 1. |
| 1259 |
|
| 1260 |
Hint: Use `--jobs 0` or `--jobs 1` to temporarily disable `--parallel`. |
| 1261 |
|
| 1262 |
Has no effect unless used with [`--parallel`](#-parallel-p). |
| 1263 |
|
| 1264 |
### About Option Types |
| 1265 |
|
| 1266 |
> _Updated in v6.0.0._ |
| 1267 |
|
| 1268 |
Each flag annotated of type `[boolean]` in Mocha's `--help` output can be _negated_ by prepending `--no-` to the flag name. For example, `--no-color` will disable Mocha's color output, which is enabled by default. |
| 1269 |
|
| 1270 |
Unless otherwise noted, _all_ boolean flags default to `false`. |
| 1271 |
|
| 1272 |
### About `node` Flags |
| 1273 |
|
| 1274 |
The `mocha` executable supports all applicable flags which the `node` executable supports. |
| 1275 |
|
| 1276 |
These flags vary depending on your version of Node.js. |
| 1277 |
|
| 1278 |
`node` flags can be defined in Mocha's [configuration](#configuring-mocha-nodejs). |
| 1279 |
|
| 1280 |
> _Since v9.1.0_ You can also pass `node` flags to Node.js using [`--node-option`](#-node-option-name-n-name). |
| 1281 |
|
| 1282 |
### `--enable-source-maps` |
| 1283 |
|
| 1284 |
> _Since Node.js v12.12.0_ |
| 1285 |
|
| 1286 |
If the [`--enable-source-maps`](https://nodejs.org/dist/latest-v12.x/docs/api/cli.html#cli_enable_source_maps) flag |
| 1287 |
is passed to mocha, source maps will be collected and used to provide accurate stack traces for transpiled code: |
| 1288 |
|
| 1289 |
```bash |
| 1290 |
Error: cool |
| 1291 |
at Object.<anonymous> (/Users/fake-user/bigco/nodejs-tasks/build/src/index.js:27:7) |
| 1292 |
-> /Users/fake-user/bigco/nodejs-tasks/src/index.ts:24:7 |
| 1293 |
``` |
| 1294 |
|
| 1295 |
### About V8 Flags |
| 1296 |
|
| 1297 |
Prepend `--v8-` to any flag listed in the output of `node --v8-options` (excluding `--v8-options` itself) to use it. |
| 1298 |
|
| 1299 |
V8 flags can be defined in Mocha's [configuration](#configuring-mocha-nodejs). |
| 1300 |
|
| 1301 |
> _Since v9.1.0_ You can also pass V8 flags (without `--v8-`) to Node.js using [`--node-option`](#-node-option-name-n-name). |
| 1302 |
|
| 1303 |
## Parallel Tests |
| 1304 |
|
| 1305 |
> _Since v.8.0.0._ |
| 1306 |
|
| 1307 |
Depending on the number and nature of your tests, you may find a significant performance benefit when running tests in parallel (using the [`--parallel`](#-parallel-p) flag). |
| 1308 |
|
| 1309 |
Parallel tests should work out-of-the box for many use cases. However, you must be aware of some important implications of the behavior. |
| 1310 |
|
| 1311 |
> _Note: Authors of third-party libraries built on Mocha should read this!_ |
| 1312 |
|
| 1313 |
### Reporter Limitations |
| 1314 |
|
| 1315 |
Due to the nature of the following reporters, they cannot work when running tests in parallel: |
| 1316 |
|
| 1317 |
- [`markdown`](#markdown) |
| 1318 |
- [`progress`](#progress) |
| 1319 |
- [`json-stream`](#json-stream) |
| 1320 |
{:.single-column} |
| 1321 |
|
| 1322 |
These reporters expect Mocha to know _how many tests it plans to run_ before execution. This information is unavailable in parallel mode, as test files are loaded only when they are about to be run. |
| 1323 |
|
| 1324 |
In serial mode, tests results will "stream" as they occur. In parallel mode, reporter output is _buffered_; reporting will occur after each file is completed. In practice, the reporter output will appear in "chunks" (but will otherwise be identical). If a test file is particularly slow, there may be a significant pause while it's running. |
| 1325 |
|
| 1326 |
### Exclusive Tests are Disallowed |
| 1327 |
|
| 1328 |
**You cannot use `it.only`, `describe.only`, `this.only()`, etc., in parallel mode.** This is for the same reason as the incompatible reporters noted above: in parallel mode, Mocha does not load all files and suites into memory before running tests. |
| 1329 |
|
| 1330 |
Suggested workarounds: |
| 1331 |
|
| 1332 |
1. Use [`--grep`](#-grep-regexp-g-regexp) or [`--fgrep`](#-fgrep-string-f-string) instead; it's not particularly efficient, but it will work. |
| 1333 |
1. Don't use parallel mode. Likely, you won't be running very many exclusive tests, so you won't see a great benefit from parallel mode anyhow. |
| 1334 |
|
| 1335 |
> _TIP: If parallel mode is defined in your config file, you can temporarily disable it on the command-line by using either the `--no-parallel` flag or reducing the job count, e.g., `--jobs=0`._ |
| 1336 |
|
| 1337 |
### File Order is Non-Deterministic |
| 1338 |
|
| 1339 |
In parallel mode, Mocha does not guarantee the order in which test files will run, nor which worker process runs them. |
| 1340 |
|
| 1341 |
Because of this, the following options, which depend on order, _cannot be used_ in parallel mode: |
| 1342 |
|
| 1343 |
- [`--file`](#-file-file) |
| 1344 |
- [`--sort`](#-sort-s) |
| 1345 |
- [`--delay`](#delayed-root-suite) |
| 1346 |
{:.single-column} |
| 1347 |
|
| 1348 |
### Test Duration Variability |
| 1349 |
|
| 1350 |
Running tests in parallel mode will naturally use more system resources. The OS may take extra time to schedule and complete some operations, depending on system load. For this reason, the timeouts of _individual tests_ may need to be increased either [globally](#-timeout-ms-t-ms) or [otherwise](#timeouts). |
| 1351 |
|
| 1352 |
### "Bail" is "Best Effort" |
| 1353 |
|
| 1354 |
When used with `--bail` (or `this.bail()`) to exit after the first failure, it's likely other tests will be running at the same time. Mocha must shut down its worker processes before exiting. |
| 1355 |
|
| 1356 |
Likewise, subprocesses may throw uncaught exceptions. When used with `--allow-uncaught`, Mocha will "bubble" this exception to the main process, but still must shut down its processes. |
| 1357 |
|
| 1358 |
Either way, Mocha will abort the test run "very soon." |
| 1359 |
|
| 1360 |
### Root Hooks Are Not Global |
| 1361 |
|
| 1362 |
> _NOTE: This only applies when running in parallel mode._ |
| 1363 |
|
| 1364 |
A _root hook_ is a hook in a test file which is _not defined_ within a suite. An example using the `bdd` interface: |
| 1365 |
|
| 1366 |
```js |
| 1367 |
// test/setup.js |
| 1368 |
|
| 1369 |
// root hook to run before every test (even in other files) |
| 1370 |
beforeEach(function () { |
| 1371 |
doMySetup(); |
| 1372 |
}); |
| 1373 |
|
| 1374 |
// root hook to run after every test (even in other files) |
| 1375 |
afterEach(function () { |
| 1376 |
doMyTeardown(); |
| 1377 |
}); |
| 1378 |
``` |
| 1379 |
|
| 1380 |
When run (in the default "serial" mode) via this command: |
| 1381 |
|
| 1382 |
```bash |
| 1383 |
mocha --file "./test/setup.js" "./test/**/*.spec.js" |
| 1384 |
``` |
| 1385 |
|
| 1386 |
`setup.js` will be executed _first_, and install the two hooks shown above for every test found in `./test/**/*.spec.js`. |
| 1387 |
|
| 1388 |
**The above example does not work in parallel mode.** |
| 1389 |
|
| 1390 |
When Mocha runs in parallel mode, **test files do not share the same process,** nor do they share the same instance of Mocha. Consequently, a hypothetical root hook defined in test file _A_ **will not be present** in test file _B_. |
| 1391 |
|
| 1392 |
Here are a couple suggested workarounds: |
| 1393 |
|
| 1394 |
1. `require('./setup.js')` or `import './setup.js'` at the top of every test file. Best avoided for those averse to boilerplate. |
| 1395 |
1. _Recommended_: Define root hooks in a "required" file, using the new (also as |
| 1396 |
of v8.0.0) [Root Hook Plugin](#root-hook-plugins) system. |
| 1397 |
|
| 1398 |
If you need to run some code _once and only once_, use a [global |
| 1399 |
fixture](#global-fixtures) instead. |
| 1400 |
|
| 1401 |
### No Browser Support |
| 1402 |
|
| 1403 |
Parallel mode is only available in Node.js, for now. |
| 1404 |
|
| 1405 |
### Limited Reporter API for Third-Party Reporters |
| 1406 |
|
| 1407 |
Third-party reporters may encounter issues when attempting to access non-existent properties within `Test`, `Suite`, and `Hook` objects. If a third-party reporter does not work in parallel mode (but otherwise works in serial mode), please [file an issue](https://github.com/mochajs/mocha/issues/new). |
| 1408 |
|
| 1409 |
### Troubleshooting Parallel Mode |
| 1410 |
|
| 1411 |
If you find your tests don't work properly when run with [`--parallel`](#-parallel-p), either shrug and move on, or use this handy-dandy checklist to get things working: |
| 1412 |
|
| 1413 |
- :white_check_mark: Ensure you are using a [supported reporter](#reporter-limitations). |
| 1414 |
- :white_check_mark: Ensure you are not using [other unsupported flags](#file-order-is-non-deterministic). |
| 1415 |
- :white_check_mark: Double-check your [config file](#configuring-mocha-nodejs); options set in config files will be merged with any command-line option. |
| 1416 |
- :white_check_mark: Look for root hooks (they look like [this](#root-hooks-are-not-global)) in your tests. Move them into a [Root Hook Plugin](#root-hook-plugins). |
| 1417 |
- :white_check_mark: Do any assertion, mock, or other test libraries you're consuming use root hooks? They may need to be [migrated](#migrating-a-library-to-use-root-hook-plugins) for compatibility with parallel mode. |
| 1418 |
- :white_check_mark: If tests are unexpectedly timing out, you may need to increase the default test timeout (via [`--timeout`](#-timeout-ms-t-ms)) |
| 1419 |
- :white_check_mark: Ensure your tests do not depend on being run in a specific order. |
| 1420 |
- :white_check_mark: Ensure your tests clean up after themselves; remove temp files, handles, sockets, etc. Don't try to share state or resources between test files. |
| 1421 |
|
| 1422 |
### Caveats About Testing in Parallel |
| 1423 |
|
| 1424 |
Some types of tests are _not_ so well-suited to run in parallel. For example, extremely timing-sensitive tests, or tests which make I/O requests to a limited pool of resources (such as opening ports, or automating browser windows, hitting a test DB, or remote server, etc.). |
| 1425 |
|
| 1426 |
Free-tier cloud CI services may not provide a suitable multi-core container or VM for their build agents. Regarding expected performance gains in CI: your mileage may vary. It may help to use a conditional in a `.mocharc.js` to check for `process.env.CI`, and adjust the job count as appropriate. |
| 1427 |
|
| 1428 |
It's unlikely (but not impossible) to see a performance gain from a [job count](#-jobs-count-j-count) _greater than_ the number of available CPU cores. That said, _play around with the job count_--there's no one-size-fits all, and the unique characteristics of your tests will determine the optimal number of jobs; it may even be that fewer is faster! |
| 1429 |
|
| 1430 |
### Parallel Mode Worker IDs |
| 1431 |
|
| 1432 |
> _Since v9.2.0_ |
| 1433 |
|
| 1434 |
Each process launched by parallel mode is assigned a unique id, from 0 for the first process to be launched, to N-1 for the Nth process. This worker id may be accessed in tests via the environment variable `MOCHA_WORKER_ID`. It can be used for example to assign a different database, service port, etc for each test process. |
| 1435 |
|
| 1436 |
## Root Hook Plugins |
| 1437 |
|
| 1438 |
> _Since v8.0.0_ |
| 1439 |
|
| 1440 |
In some cases, you may want a [hook](#hooks) before (or after) every test in every file. These are called _root hooks_. Previous to v8.0.0, the way to accomplish this was to use `--file` combined with root hooks (see [example above](#root-hooks-are-not-global)). This still works in v8.0.0, but _not_ when running tests in parallel mode! For that reason, running root hooks using this method is _strongly discouraged_, and may be deprecated in the future. |
| 1441 |
|
| 1442 |
A _Root Hook Plugin_ is a JavaScript file loaded via [`--require`](#-require-module-r-module) which "registers" one or more root hooks to be used across all test files. |
| 1443 |
|
| 1444 |
In browsers you can set root hooks directly via a `rootHooks` object: `mocha.setup({ rootHooks: {beforeEach() {...}} })`, see [`mocha.setup()`](#running-mocha-in-the-browser) |
| 1445 |
|
| 1446 |
### Defining a Root Hook Plugin |
| 1447 |
|
| 1448 |
A Root Hook Plugin file is a script which exports (via `module.exports`) a `mochaHooks` property. It is loaded via `--require <file>`. |
| 1449 |
|
| 1450 |
Here's a simple example which defines a root hook, written using CJS and ESM syntax. |
| 1451 |
|
| 1452 |
#### With CommonJS |
| 1453 |
|
| 1454 |
```js |
| 1455 |
// test/hooks.js |
| 1456 |
|
| 1457 |
exports.mochaHooks = { |
| 1458 |
beforeEach(done) { |
| 1459 |
// do something before every test |
| 1460 |
done(); |
| 1461 |
}, |
| 1462 |
}; |
| 1463 |
``` |
| 1464 |
|
| 1465 |
#### With ES Modules |
| 1466 |
|
| 1467 |
We're using the `.mjs` extension in these examples. |
| 1468 |
|
| 1469 |
> _Tip: If you're having trouble getting ES modules to work, refer to [the Node.js documentation](https://nodejs.org/api/esm.html)._ |
| 1470 |
|
| 1471 |
```js |
| 1472 |
// test/hooks.mjs |
| 1473 |
|
| 1474 |
export const mochaHooks = { |
| 1475 |
beforeEach(done) { |
| 1476 |
// do something before every test |
| 1477 |
done(); |
| 1478 |
}, |
| 1479 |
}; |
| 1480 |
``` |
| 1481 |
|
| 1482 |
> _Note: Further examples will use ESM syntax._ |
| 1483 |
|
| 1484 |
### Available Root Hooks |
| 1485 |
|
| 1486 |
Root hooks work with any interface, but _the property names do not change_. In other words, if you are using the `tdd` interface, `suiteSetup` maps to `beforeAll`, and `setup` maps to `beforeEach`. |
| 1487 |
|
| 1488 |
Available root hooks and their behavior: |
| 1489 |
|
| 1490 |
- `beforeAll`: |
| 1491 |
- In **serial** mode (Mocha's default), _before all tests begin, once only_ |
| 1492 |
- In **parallel** mode, run _before all tests begin, for each file_ |
| 1493 |
- `beforeEach`: |
| 1494 |
- In **both** modes, run _before each test_ |
| 1495 |
- `afterAll`: |
| 1496 |
- In **serial** mode, run _after all tests end, once only_ |
| 1497 |
- In **parallel** mode, run _after all tests end, for each file_ |
| 1498 |
- `afterEach`: |
| 1499 |
- In **both** modes, run _after every test_ |
| 1500 |
|
| 1501 |
{:.single-column} |
| 1502 |
|
| 1503 |
> _Tip: If you need to ensure code runs once and only once in any mode, use [global fixtures](#global-fixtures)._ |
| 1504 |
|
| 1505 |
As with other hooks, `this` refers to the current context object: |
| 1506 |
|
| 1507 |
```js |
| 1508 |
// test/hooks.mjs |
| 1509 |
|
| 1510 |
export const mochaHooks = { |
| 1511 |
beforeAll() { |
| 1512 |
// skip all tests for bob |
| 1513 |
if (require("os").userInfo().username === "bob") { |
| 1514 |
return this.skip(); |
| 1515 |
} |
| 1516 |
}, |
| 1517 |
}; |
| 1518 |
``` |
| 1519 |
|
| 1520 |
### Multiple Root Hooks in a Single Plugin |
| 1521 |
|
| 1522 |
Multiple root hooks can be defined in a single plugin, for organizational purposes. For example: |
| 1523 |
|
| 1524 |
```js |
| 1525 |
// test/hooks.mjs |
| 1526 |
|
| 1527 |
export const mochaHooks = { |
| 1528 |
beforeEach: [ |
| 1529 |
function (done) { |
| 1530 |
// do something before every test, |
| 1531 |
// then run the next hook in this array |
| 1532 |
}, |
| 1533 |
async function () { |
| 1534 |
// async or Promise-returning functions allowed |
| 1535 |
}, |
| 1536 |
], |
| 1537 |
}; |
| 1538 |
``` |
| 1539 |
|
| 1540 |
### Root Hook Plugins Can Export a Function |
| 1541 |
|
| 1542 |
If you need to perform some logic--such as choosing a root hook conditionally, based on the environment--`mochaHooks` can be a _function_ which returns the expected object. |
| 1543 |
|
| 1544 |
```js |
| 1545 |
// test/hooks.mjs |
| 1546 |
|
| 1547 |
export const mochaHooks = () => { |
| 1548 |
if (process.env.CI) { |
| 1549 |
// root hooks object |
| 1550 |
return { |
| 1551 |
beforeEach: [ |
| 1552 |
function () { |
| 1553 |
// CI-specific beforeEach |
| 1554 |
}, |
| 1555 |
function () { |
| 1556 |
// some other CI-specific beforeEach |
| 1557 |
}, |
| 1558 |
], |
| 1559 |
}; |
| 1560 |
} |
| 1561 |
// root hooks object |
| 1562 |
return { |
| 1563 |
beforeEach() { |
| 1564 |
// regular beforeEach |
| 1565 |
}, |
| 1566 |
}; |
| 1567 |
}; |
| 1568 |
``` |
| 1569 |
|
| 1570 |
If you need to perform an async operation, `mochaHooks` can be `Promise`-returning: |
| 1571 |
|
| 1572 |
```js |
| 1573 |
// test/hooks.mjs |
| 1574 |
|
| 1575 |
export const mochaHooks = async () => { |
| 1576 |
const result = await checkSomething(); |
| 1577 |
// only use a root hook if `result` is truthy |
| 1578 |
if (result) { |
| 1579 |
// root hooks object |
| 1580 |
return { |
| 1581 |
beforeEach() { |
| 1582 |
// something |
| 1583 |
}, |
| 1584 |
}; |
| 1585 |
} |
| 1586 |
}; |
| 1587 |
``` |
| 1588 |
|
| 1589 |
### Multiple Root Hook Plugins |
| 1590 |
|
| 1591 |
Multiple root hook plugins can be registered by using `--require` multiple times. For example, to register the root hooks in `hooks-a.js` and `hooks-b.js`, use `--require hooks-a.js --require hooks-b.js`. These will be registered (and run) _in order_. |
| 1592 |
|
| 1593 |
### Migrating Tests to use Root Hook Plugins |
| 1594 |
|
| 1595 |
To migrate your tests using root hooks to a root hook plugin: |
| 1596 |
|
| 1597 |
1. Find your root hooks (hooks defined _outside_ of a suite--usually `describe()` callback). |
| 1598 |
1. Create a new file, e.g., `test/hooks.js`. |
| 1599 |
1. _Move_ your root hooks into `test/hooks.js`. |
| 1600 |
1. In `test/hooks.js`, make your hooks a member of an exported `mochaHooks` property. |
| 1601 |
1. Use `--require test/hooks.js` (even better: use a [config file](#configuring-mocha-nodejs) with `{"require": "test/hooks.js"}`) when running your tests. |
| 1602 |
|
| 1603 |
For example, given the following file, `test/test.spec.js`, containing root hooks: |
| 1604 |
|
| 1605 |
```js |
| 1606 |
// test/test.spec.js |
| 1607 |
|
| 1608 |
beforeEach(function () { |
| 1609 |
// global setup for all tests |
| 1610 |
}); |
| 1611 |
|
| 1612 |
after(function () { |
| 1613 |
// one-time final cleanup |
| 1614 |
}); |
| 1615 |
|
| 1616 |
describe("my test suite", function () { |
| 1617 |
it("should have run my global setup", function () { |
| 1618 |
// make assertion |
| 1619 |
}); |
| 1620 |
}); |
| 1621 |
``` |
| 1622 |
|
| 1623 |
Your `test/hooks.js` (for this example, a CJS module) should contain: |
| 1624 |
|
| 1625 |
```js |
| 1626 |
// test/hooks.js |
| 1627 |
|
| 1628 |
exports.mochaHooks = { |
| 1629 |
beforeEach: function () { |
| 1630 |
// global setup for all tests |
| 1631 |
}, |
| 1632 |
afterAll: function () { |
| 1633 |
// one-time final cleanup |
| 1634 |
}, |
| 1635 |
}; |
| 1636 |
``` |
| 1637 |
|
| 1638 |
> _NOTE: Careful! `after` becomes `afterAll` and `before` becomes `beforeAll`._ |
| 1639 |
|
| 1640 |
Your original `test/test.spec.js` should now contain: |
| 1641 |
|
| 1642 |
```js |
| 1643 |
// test/test.spec.js |
| 1644 |
|
| 1645 |
describe("my test suite", function () { |
| 1646 |
it("should have run my global setup", function () { |
| 1647 |
// make assertion |
| 1648 |
}); |
| 1649 |
}); |
| 1650 |
``` |
| 1651 |
|
| 1652 |
Running `mocha --require test/hooks.js test/test.spec.js` will run as before (and is now ready to be used with [`--parallel`](#-parallel-p)). |
| 1653 |
|
| 1654 |
### Migrating a Library to use Root Hook PLugins |
| 1655 |
|
| 1656 |
If you're a library maintainer, and your library uses root hooks, you can migrate by refactoring your entry point: |
| 1657 |
|
| 1658 |
- Your library should _always_ export a [`mochaHooks` object](#defining-a-root-hook-plugin). |
| 1659 |
- To maintain backwards compatibility, run your root hooks _if and only if_ `global.beforeEach` (or other relevant hook) exists. |
| 1660 |
- Instruct your users to `--require <your-package>` when running `mocha`. |
| 1661 |
|
| 1662 |
## Global Fixtures |
| 1663 |
|
| 1664 |
> _Since v8.2.0_ |
| 1665 |
|
| 1666 |
At first glance, _global fixtures_ seem similar to [root hooks](#root-hook-plugins). However, unlike root hooks, global fixtures: |
| 1667 |
|
| 1668 |
1. Are _guaranteed_ to execute _once and only once_ |
| 1669 |
1. Work identically parallel mode, watch mode, and serial mode |
| 1670 |
1. Do not share a context with tests, suites, or other hooks |
| 1671 |
|
| 1672 |
There are two types of global fixtures: [global setup fixtures] and [global teardown fixtures]. |
| 1673 |
|
| 1674 |
### Global Setup Fixtures |
| 1675 |
|
| 1676 |
To create a global setup fixture, export `mochaGlobalSetup` from a script, e.g.,: |
| 1677 |
|
| 1678 |
```js |
| 1679 |
// fixtures.cjs |
| 1680 |
|
| 1681 |
// can be async or not |
| 1682 |
exports.mochaGlobalSetup = async function () { |
| 1683 |
this.server = await startSomeServer({ port: process.env.TEST_PORT }); |
| 1684 |
console.log(`server running on port ${this.server.port}`); |
| 1685 |
}; |
| 1686 |
``` |
| 1687 |
|
| 1688 |
...or an ES module: |
| 1689 |
|
| 1690 |
```js |
| 1691 |
// fixtures.mjs |
| 1692 |
|
| 1693 |
// can be async or not |
| 1694 |
export async function mochaGlobalSetup() { |
| 1695 |
this.server = await startSomeServer({ port: process.env.TEST_PORT }); |
| 1696 |
console.log(`server running on port ${this.server.port}`); |
| 1697 |
} |
| 1698 |
``` |
| 1699 |
|
| 1700 |
To use it, load this file when running Mocha via `mocha --require fixtures.cjs` (or whatever you have named the file). |
| 1701 |
|
| 1702 |
> Remember: you can define "requires" in a [configuration file](#configuring-mocha-nodejs). |
| 1703 |
|
| 1704 |
Now, before Mocha loads and runs your tests, it will execute the above global setup fixture, starting a server for testing. This won't shut _down_ the server when Mocha is done, however! To do that, use a [_global teardown fixture_](#global-teardown-fixtures). |
| 1705 |
|
| 1706 |
### Global Teardown Fixtures |
| 1707 |
|
| 1708 |
Just like a [global setup fixture](#global-setup-fixtures), a _global teardown fixture_ can be created by exporting from a "required" script (we can put both types of fixtures in a single file): |
| 1709 |
|
| 1710 |
```js |
| 1711 |
// fixtures.cjs, cont'd |
| 1712 |
|
| 1713 |
// can be async or not |
| 1714 |
exports.mochaGlobalTeardown = async function () { |
| 1715 |
await this.server.stop(); |
| 1716 |
console.log("server stopped!"); |
| 1717 |
}; |
| 1718 |
``` |
| 1719 |
|
| 1720 |
...or an ES module: |
| 1721 |
|
| 1722 |
```js |
| 1723 |
// fixtures.mjs, cont'd |
| 1724 |
|
| 1725 |
// can be async or not |
| 1726 |
export async function mochaGlobalTeardown() { |
| 1727 |
await this.server.stop(); |
| 1728 |
console.log("server stopped!"); |
| 1729 |
} |
| 1730 |
``` |
| 1731 |
|
| 1732 |
You'll note that we used `this` in the fixture examples. Global setup fixtures and global teardown fixtures _share a context_, which means we can add properties to the context object (`this`) in the setup fixture, and reference them later in the teardown fixture. This is more useful when the fixtures are in separate files, since you can just use JS' variable scoping rules instead ([example below](#when-not-to-use-global-fixtures)). |
| 1733 |
|
| 1734 |
As explained [above](#global-fixtures)--and [below](#when-not-to-use-global-fixtures)--test files _do not_ have access to this context object. |
| 1735 |
|
| 1736 |
### When To Use Global Fixtures |
| 1737 |
|
| 1738 |
Global fixtures are good for spinning up a server, opening a socket, or otherwise creating a resource that your tests will repeatedly access via I/O. |
| 1739 |
|
| 1740 |
### When Not To Use Global Fixtures |
| 1741 |
|
| 1742 |
If you need to access an in-memory value (such as a file handle or database connection), _don't_ use global fixtures to do this, because your tests will not have access to the value. |
| 1743 |
|
| 1744 |
> You could be clever and try to get around this restriction by assigning something to the `global` object, but this will _not_ work in parallel mode. It's probably best to play by the rules! |
| 1745 |
|
| 1746 |
Instead, use the global fixture to _start_ the database, and use [root hook plugins](#root-hook-plugins) or plain ol' [hooks](#hooks) to create a connection. |
| 1747 |
|
| 1748 |
Here's an example of using global fixtures and "before all" hooks to get the job done. Note that we do not reference the `server` object anywhere in our tests! |
| 1749 |
|
| 1750 |
First, use a global fixture to start and stop a test server: |
| 1751 |
|
| 1752 |
```js |
| 1753 |
// fixtures.mjs |
| 1754 |
|
| 1755 |
let server; |
| 1756 |
|
| 1757 |
export const mochaGlobalSetup = async () => { |
| 1758 |
server = await startSomeServer({ port: process.env.TEST_PORT }); |
| 1759 |
console.log(`server running on port ${server.port}`); |
| 1760 |
}; |
| 1761 |
|
| 1762 |
export const mochaGlobalTeardown = async () => { |
| 1763 |
await server.stop(); |
| 1764 |
console.log("server stopped!"); |
| 1765 |
}; |
| 1766 |
``` |
| 1767 |
|
| 1768 |
Then, connect to the server in your tests: |
| 1769 |
|
| 1770 |
```js |
| 1771 |
// test.spec.mjs |
| 1772 |
|
| 1773 |
import { connect } from "my-server-connector-thingy"; |
| 1774 |
|
| 1775 |
describe("my API", function () { |
| 1776 |
let connection; |
| 1777 |
|
| 1778 |
before(async function () { |
| 1779 |
connection = await connect({ port: process.env.TEST_PORT }); |
| 1780 |
}); |
| 1781 |
|
| 1782 |
it("should be a nice API", function () { |
| 1783 |
// assertions here |
| 1784 |
}); |
| 1785 |
|
| 1786 |
after(async function () { |
| 1787 |
return connection.close(); |
| 1788 |
}); |
| 1789 |
}); |
| 1790 |
``` |
| 1791 |
|
| 1792 |
Finally, use this command to bring it together: `mocha --require fixtures.mjs test.spec.mjs`. |
| 1793 |
|
| 1794 |
## Test Fixture Decision-Tree Wizard Thing |
| 1795 |
|
| 1796 |
This flowchart will help you decide which of [hooks], [root hook plugins] or |
| 1797 |
[global fixtures] you should use. |
| 1798 |
|
| 1799 |
{% include 'fixture-wizard.html' %} |
| 1800 |
|
| 1801 |
## Interfaces |
| 1802 |
|
| 1803 |
Mocha's "interface" system allows developers to choose their style of DSL. Mocha has **BDD**, **TDD**, **Exports**, **QUnit** and **Require**-style interfaces. |
| 1804 |
|
| 1805 |
### BDD |
| 1806 |
|
| 1807 |
The **BDD** interface provides `describe()`, `context()`, `it()`, `specify()`, `before()`, `after()`, `beforeEach()`, and `afterEach()`. |
| 1808 |
|
| 1809 |
`context()` is just an alias for `describe()`, and behaves the same way; it provides a way to keep tests easier to read and organized. Similarly, `specify()` is an alias for `it()`. |
| 1810 |
|
| 1811 |
> All of the previous examples were written using the **BDD** interface. |
| 1812 |
|
| 1813 |
```js |
| 1814 |
describe("Array", function () { |
| 1815 |
before(function () { |
| 1816 |
// ... |
| 1817 |
}); |
| 1818 |
|
| 1819 |
describe("#indexOf()", function () { |
| 1820 |
context("when not present", function () { |
| 1821 |
it("should not throw an error", function () { |
| 1822 |
(function () { |
| 1823 |
[1, 2, 3].indexOf(4); |
| 1824 |
}).should.not.throw(); |
| 1825 |
}); |
| 1826 |
it("should return -1", function () { |
| 1827 |
[1, 2, 3].indexOf(4).should.equal(-1); |
| 1828 |
}); |
| 1829 |
}); |
| 1830 |
context("when present", function () { |
| 1831 |
it("should return the index where the element first appears in the array", function () { |
| 1832 |
[1, 2, 3].indexOf(3).should.equal(2); |
| 1833 |
}); |
| 1834 |
}); |
| 1835 |
}); |
| 1836 |
}); |
| 1837 |
``` |
| 1838 |
|
| 1839 |
### TDD |
| 1840 |
|
| 1841 |
The **TDD** interface provides `suite()`, `test()`, `suiteSetup()`, `suiteTeardown()`, `setup()`, and `teardown()`: |
| 1842 |
|
| 1843 |
```js |
| 1844 |
suite("Array", function () { |
| 1845 |
setup(function () { |
| 1846 |
// ... |
| 1847 |
}); |
| 1848 |
|
| 1849 |
suite("#indexOf()", function () { |
| 1850 |
test("should return -1 when not present", function () { |
| 1851 |
assert.equal(-1, [1, 2, 3].indexOf(4)); |
| 1852 |
}); |
| 1853 |
}); |
| 1854 |
}); |
| 1855 |
``` |
| 1856 |
|
| 1857 |
### Exports |
| 1858 |
|
| 1859 |
The **Exports** interface allows for organizing tests in a modular fashion. It is particularly useful in larger projects where test suites can be segmented into different files. |
| 1860 |
|
| 1861 |
**Note**: The Exports interface is not supported in browser environments. This limitation arises because browsers handle module exports differently from Node.js. If you intend to run tests in a browser, consider using the BDD or TDD interfaces, which are fully supported. |
| 1862 |
|
| 1863 |
The Exports interface is much like Mocha's predecessor [expresso][]. The keys `before`, `after`, `beforeEach`, and `afterEach` are special-cased, object values are suites, and function values are test-cases: |
| 1864 |
|
| 1865 |
```js |
| 1866 |
module.exports = { |
| 1867 |
before: function () { |
| 1868 |
// ... |
| 1869 |
}, |
| 1870 |
|
| 1871 |
Array: { |
| 1872 |
"#indexOf()": { |
| 1873 |
"should return -1 when not present": function () { |
| 1874 |
[1, 2, 3].indexOf(4).should.equal(-1); |
| 1875 |
}, |
| 1876 |
}, |
| 1877 |
}, |
| 1878 |
}; |
| 1879 |
``` |
| 1880 |
|
| 1881 |
### QUnit |
| 1882 |
|
| 1883 |
The [QUnit][]-inspired interface matches the "flat" look of QUnit, where the test suite title is defined _before_ the test-cases. Like TDD, it uses `suite()` and `test()`, but resembling BDD, it also contains `before()`, `after()`, `beforeEach()`, and `afterEach()`. |
| 1884 |
|
| 1885 |
```js |
| 1886 |
function ok(expr, msg) { |
| 1887 |
if (!expr) throw new Error(msg); |
| 1888 |
} |
| 1889 |
|
| 1890 |
suite("Array"); |
| 1891 |
|
| 1892 |
test("#length", function () { |
| 1893 |
var arr = [1, 2, 3]; |
| 1894 |
ok(arr.length == 3); |
| 1895 |
}); |
| 1896 |
|
| 1897 |
test("#indexOf()", function () { |
| 1898 |
var arr = [1, 2, 3]; |
| 1899 |
ok(arr.indexOf(1) == 0); |
| 1900 |
ok(arr.indexOf(2) == 1); |
| 1901 |
ok(arr.indexOf(3) == 2); |
| 1902 |
}); |
| 1903 |
|
| 1904 |
suite("String"); |
| 1905 |
|
| 1906 |
test("#length", function () { |
| 1907 |
ok("foo".length == 3); |
| 1908 |
}); |
| 1909 |
``` |
| 1910 |
|
| 1911 |
### Require |
| 1912 |
|
| 1913 |
The `require` interface allows you to require the `describe` and friend words directly using `require` and call them whatever you want. This interface is also useful if you want to avoid global variables in your tests. |
| 1914 |
|
| 1915 |
_Note_: The `require` interface cannot be run via the `node` executable, and must be run via `mocha`. |
| 1916 |
|
| 1917 |
```js |
| 1918 |
var testCase = require("mocha").describe; |
| 1919 |
var pre = require("mocha").before; |
| 1920 |
var assertions = require("mocha").it; |
| 1921 |
var assert = require("chai").assert; |
| 1922 |
|
| 1923 |
testCase("Array", function () { |
| 1924 |
pre(function () { |
| 1925 |
// ... |
| 1926 |
}); |
| 1927 |
|
| 1928 |
testCase("#indexOf()", function () { |
| 1929 |
assertions("should return -1 when not present", function () { |
| 1930 |
assert.equal([1, 2, 3].indexOf(4), -1); |
| 1931 |
}); |
| 1932 |
}); |
| 1933 |
}); |
| 1934 |
``` |
| 1935 |
|
| 1936 |
## Reporters |
| 1937 |
|
| 1938 |
Mocha reporters adjust to the terminal window, and always disable ANSI-escape coloring when the stdio streams are not associated with a TTY. |
| 1939 |
|
| 1940 |
### Spec |
| 1941 |
|
| 1942 |
Alias: `Spec`, `spec` |
| 1943 |
|
| 1944 |
This is the default reporter. The Spec reporter outputs a hierarchical view nested just as the test cases are. |
| 1945 |
|
| 1946 |
{:class="screenshot" loading="lazy"} |
| 1947 |
{:class="screenshot" loading="lazy"} |
| 1948 |
|
| 1949 |
### Dot Matrix |
| 1950 |
|
| 1951 |
Alias: `Dot`, `dot` |
| 1952 |
|
| 1953 |
The Dot Matrix reporter is a series of characters which represent test cases. Failures highlight in red exclamation marks (`!`), pending tests with a blue comma (`,`), and slow tests as yellow. Good if you prefer minimal output. |
| 1954 |
|
| 1955 |
{:class="screenshot" loading="lazy"} |
| 1956 |
|
| 1957 |
### Nyan |
| 1958 |
|
| 1959 |
Alias: `Nyan`, `nyan` |
| 1960 |
|
| 1961 |
The Nyan reporter is exactly what you might expect: |
| 1962 |
|
| 1963 |
{:class="screenshot" loading="lazy"} |
| 1964 |
|
| 1965 |
### TAP |
| 1966 |
|
| 1967 |
Alias: `TAP`, `tap` |
| 1968 |
|
| 1969 |
The TAP reporter emits lines for a [Test-Anything-Protocol][] consumer. |
| 1970 |
|
| 1971 |
{:class="screenshot" loading="lazy"} |
| 1972 |
|
| 1973 |
### Landing Strip |
| 1974 |
|
| 1975 |
Alias: `Landing`, `landing` |
| 1976 |
|
| 1977 |
The Landing Strip reporter is a gimmicky test reporter simulating a plane landing :) unicode ftw |
| 1978 |
|
| 1979 |
{:class="screenshot" loading="lazy"} |
| 1980 |
{:class="screenshot" loading="lazy"} |
| 1981 |
|
| 1982 |
### List |
| 1983 |
|
| 1984 |
Alias: `List`, `list` |
| 1985 |
|
| 1986 |
The List reporter outputs a simple specifications list as test cases pass or fail, outputting the failure details at the bottom of the output. |
| 1987 |
|
| 1988 |
{:class="screenshot" loading="lazy"} |
| 1989 |
|
| 1990 |
### Progress |
| 1991 |
|
| 1992 |
Alias: `Progress`, `progress` |
| 1993 |
|
| 1994 |
The Progress reporter implements a simple progress-bar: |
| 1995 |
|
| 1996 |
{:class="screenshot" loading="lazy"} |
| 1997 |
|
| 1998 |
### JSON |
| 1999 |
|
| 2000 |
Alias: `JSON`, `json` |
| 2001 |
|
| 2002 |
The JSON reporter outputs a single large JSON object when the tests have completed (failures or not). |
| 2003 |
|
| 2004 |
By default, it will output to the console. To write directly to a file, use `--reporter-option output=filename.json`. |
| 2005 |
|
| 2006 |
{:class="screenshot" loading="lazy"} |
| 2007 |
|
| 2008 |
### JSON Stream |
| 2009 |
|
| 2010 |
Alias: `JSONStream`, `json-stream` |
| 2011 |
|
| 2012 |
The JSON Stream reporter outputs newline-delimited JSON "events" as they occur, beginning with a "start" event, followed by test passes or failures, and then the final "end" event. |
| 2013 |
|
| 2014 |
{:class="screenshot" loading="lazy"} |
| 2015 |
|
| 2016 |
### Min |
| 2017 |
|
| 2018 |
Alias: `Min`, `min` |
| 2019 |
|
| 2020 |
The Min reporter displays the summary only, while still outputting errors on failure. This reporter works great with `--watch` as it clears the terminal in order to keep your test summary at the top. |
| 2021 |
|
| 2022 |
{:class="screenshot" loading="lazy"} |
| 2023 |
|
| 2024 |
### Doc |
| 2025 |
|
| 2026 |
Alias: `Doc`, `doc` |
| 2027 |
|
| 2028 |
The Doc reporter outputs a hierarchical HTML body representation of your tests. Wrap it with a header, footer, and some styling, then you have some fantastic documentation! |
| 2029 |
|
| 2030 |
{:class="screenshot" loading="lazy"} |
| 2031 |
|
| 2032 |
For example, suppose you have the following JavaScript: |
| 2033 |
|
| 2034 |
```js |
| 2035 |
describe("Array", function () { |
| 2036 |
describe("#indexOf()", function () { |
| 2037 |
it("should return -1 when the value is not present", function () { |
| 2038 |
[1, 2, 3].indexOf(5).should.equal(-1); |
| 2039 |
[1, 2, 3].indexOf(0).should.equal(-1); |
| 2040 |
}); |
| 2041 |
}); |
| 2042 |
}); |
| 2043 |
``` |
| 2044 |
|
| 2045 |
The command `mocha --reporter doc array` would yield: |
| 2046 |
|
| 2047 |
```html |
| 2048 |
<section class="suite"> |
| 2049 |
<h1>Array</h1> |
| 2050 |
<dl> |
| 2051 |
<section class="suite"> |
| 2052 |
<h1>#indexOf()</h1> |
| 2053 |
<dl> |
| 2054 |
<dt>should return -1 when the value is not present</dt> |
| 2055 |
<dd> |
| 2056 |
<pre><code>[1,2,3].indexOf(5).should.equal(-1); |
| 2057 |
[1,2,3].indexOf(0).should.equal(-1);</code></pre> |
| 2058 |
</dd> |
| 2059 |
</dl> |
| 2060 |
</section> |
| 2061 |
</dl> |
| 2062 |
</section> |
| 2063 |
``` |
| 2064 |
|
| 2065 |
The SuperAgent request library [test documentation][superagent-docs-test] was generated with Mocha's doc reporter using this Bash command: |
| 2066 |
|
| 2067 |
```bash |
| 2068 |
$ mocha --reporter=doc | cat docs/head.html - docs/tail.html > docs/test.html |
| 2069 |
``` |
| 2070 |
|
| 2071 |
View SuperAgent's [Makefile][superagent-makefile] for reference. |
| 2072 |
|
| 2073 |
### Markdown |
| 2074 |
|
| 2075 |
Alias: `Markdown`, `markdown` |
| 2076 |
|
| 2077 |
The Markdown reporter generates a markdown TOC and body for your test suite. |
| 2078 |
This is great if you want to use the tests as documentation within a Github |
| 2079 |
wiki page, or a markdown file in the repository that Github can render. For |
| 2080 |
example, here is the Connect [test output][connect-test-output]. |
| 2081 |
|
| 2082 |
### XUnit |
| 2083 |
|
| 2084 |
Alias: `XUnit`, `xunit` |
| 2085 |
|
| 2086 |
The XUnit reporter is also available. It outputs an XUnit-compatible XML document, often applicable in CI servers. |
| 2087 |
|
| 2088 |
By default, it will output to the console. To write directly to a file, use `--reporter-option output=filename.xml`. |
| 2089 |
|
| 2090 |
To specify custom report title, use `--reporter-option suiteName="Custom name"`. |
| 2091 |
|
| 2092 |
The reporter shows absolute file paths by default. To show relative paths instead, use `--reporter-option showRelativePaths`. |
| 2093 |
|
| 2094 |
### Third-Party Reporters |
| 2095 |
|
| 2096 |
Mocha allows you to define custom reporters. For more information see the [wiki][mocha-wiki-more-reporters]. |
| 2097 |
|
| 2098 |
Examples: |
| 2099 |
|
| 2100 |
- the [TeamCity reporter][mocha-teamcity-reporter] |
| 2101 |
- our [working example][example-third-party-reporter] |
| 2102 |
|
| 2103 |
### HTML Reporter |
| 2104 |
|
| 2105 |
Alias: `HTML`, `html` |
| 2106 |
|
| 2107 |
**The HTML reporter is not intended for use on the command-line.** |
| 2108 |
|
| 2109 |
## Node.JS native ESM support |
| 2110 |
|
| 2111 |
> _Since v7.1.0_ |
| 2112 |
|
| 2113 |
Mocha supports writing your tests as ES modules, and not just using CommonJS. For example: |
| 2114 |
|
| 2115 |
```js |
| 2116 |
// test.mjs |
| 2117 |
import { add } from "./add.mjs"; |
| 2118 |
import assert from "assert"; |
| 2119 |
|
| 2120 |
it("should add to numbers from an es module", () => { |
| 2121 |
assert.equal(add(3, 5), 8); |
| 2122 |
}); |
| 2123 |
``` |
| 2124 |
|
| 2125 |
To enable this you don't need to do anything special. Write your test file as an ES module. In Node.js |
| 2126 |
this means either ending the file with a `.mjs` extension, or, if you want to use the regular `.js` extension, by |
| 2127 |
adding `"type": "module"` to your `package.json`. |
| 2128 |
More information can be found in the [Node.js documentation](https://nodejs.org/api/esm.html). |
| 2129 |
|
| 2130 |
### Current Limitations |
| 2131 |
|
| 2132 |
- [Watch mode](#-watch-w) does not support ES Module test files |
| 2133 |
- [Custom reporters](#third-party-reporters) and [custom interfaces](#interfaces) |
| 2134 |
can only be CommonJS files |
| 2135 |
- [Configuration file](#configuring-mocha-nodejs) can only be a CommonJS file (`.mocharc.js` or `.mocharc.cjs`) |
| 2136 |
- Mocha in Node.js version 24.4.0 or older [silently ignored top level errors in ESM files](https://github.com/mochajs/mocha/issues/5396). |
| 2137 |
If you cannot upgrade to a newer Node.js version, you can add `--no-experimental-require-module` to the `NODE_OPTIONS` environment variable. |
| 2138 |
- When using module-level mocks via libs like `proxyquire`, `rewiremock` or `rewire`, |
| 2139 |
hold off on using ES modules for your test files. You can switch to using `testdouble`, |
| 2140 |
which does support ESM. |
| 2141 |
|
| 2142 |
## Running Mocha in the Browser |
| 2143 |
|
| 2144 |
Mocha runs in the browser. Every release of Mocha will have new builds of `./mocha.js` and `./mocha.css` for use in the browser. |
| 2145 |
|
| 2146 |
A typical setup might look something like the following, where we call `mocha.setup('bdd')` to use the **BDD** interface before loading the test scripts, running them `onload` with `mocha.run()`. |
| 2147 |
|
| 2148 |
```html |
| 2149 |
<!DOCTYPE html> |
| 2150 |
<html lang="en"> |
| 2151 |
<head> |
| 2152 |
<meta charset="utf-8" /> |
| 2153 |
<title>Mocha Tests</title> |
| 2154 |
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> |
| •2155 |
<link rel="stylesheet" href="/javascript/mocha/mocha.css" /> |
| 2156 |
</head> |
| 2157 |
<body> |
| 2158 |
<div id="mocha"></div> |
| 2159 |
|
| •2160 |
<script src="/javascript/chai/chai.js"></script> |
| 2161 |
<script src="/javascript/mocha/mocha.js"></script> |
| 2162 |
|
| 2163 |
<script class="mocha-init"> |
| 2164 |
mocha.setup("bdd"); |
| 2165 |
mocha.checkLeaks(); |
| 2166 |
</script> |
| 2167 |
<script src="test.array.js"></script> |
| 2168 |
<script src="test.object.js"></script> |
| 2169 |
<script src="test.xhr.js"></script> |
| 2170 |
<script class="mocha-exec"> |
| 2171 |
mocha.run(); |
| 2172 |
</script> |
| 2173 |
</body> |
| 2174 |
</html> |
| 2175 |
``` |
| 2176 |
|
| 2177 |
Mocha supports the latest major versions of evergreen browsers available when Mocha's oldest supported Node.js major version was released. |
| 2178 |
As of Mocha v11.0.0, that includes the following browser versions that were stable as of [Node.js 18.10.0](https://nodejs.org/en/blog/release/v18.0.0)'s release on April 19, 2022: |
| 2179 |
|
| 2180 |
- [Chrome 100](https://developer.chrome.com/blog/new-in-chrome-100) |
| 2181 |
- [Edge 100](https://learn.microsoft.com/en-us/deployedge/microsoft-edge-relnote-archive-stable-channel#version-1000118544-april-15) |
| 2182 |
- [Firefox 99](https://www.mozilla.org/en-US/firefox/99.0/releasenotes) |
| 2183 |
- [Safari 15.4](https://developer.apple.com/documentation/safari-release-notes/safari-15_4-release-notes) |
| 2184 |
|
| 2185 |
### Grep |
| 2186 |
|
| 2187 |
The browser may use the `--grep` as functionality. Append a query-string to your URL: `?grep=api`. |
| 2188 |
|
| 2189 |
### Browser Configuration |
| 2190 |
|
| 2191 |
Mocha options can be set via `mocha.setup()`. Examples: |
| 2192 |
|
| 2193 |
```js |
| 2194 |
// Use "tdd" interface. This is a shortcut to setting the interface; |
| 2195 |
// any other options must be passed via an object. |
| 2196 |
mocha.setup('tdd'); |
| 2197 |
|
| 2198 |
// This is equivalent to the above. |
| 2199 |
mocha.setup({ |
| 2200 |
ui: 'tdd' |
| 2201 |
}); |
| 2202 |
|
| 2203 |
// Examples of options: |
| 2204 |
mocha.setup({ |
| 2205 |
allowUncaught: true, |
| 2206 |
asyncOnly: true, |
| 2207 |
bail: true, |
| 2208 |
checkLeaks: true, |
| 2209 |
dryRun: true, |
| 2210 |
failZero: true, |
| 2211 |
forbidOnly: true, |
| 2212 |
forbidPending: true, |
| 2213 |
global: ['MyLib'], |
| 2214 |
retries: 3, |
| 2215 |
rootHooks: { beforeEach(done) { ... done();} }, |
| 2216 |
slow: '100', |
| 2217 |
timeout: '2000', |
| 2218 |
ui: 'bdd' |
| 2219 |
}); |
| 2220 |
``` |
| 2221 |
|
| 2222 |
### Browser-specific Option(s) |
| 2223 |
|
| 2224 |
Browser Mocha supports many, but not all [cli options](#command-line-usage). |
| 2225 |
To use a [cli option](#command-line-usage) that contains a "-", please convert the option to camel-case, (eg. `check-leaks` to `checkLeaks`). |
| 2226 |
|
| 2227 |
#### Options that differ slightly from [cli options](#command-line-usage): |
| 2228 |
|
| 2229 |
`reporter` _{string|constructor}_ |
| 2230 |
You can pass a reporter's name or a custom reporter's constructor. You can find **recommended** reporters for the browser [here](#reporting). It is possible to use [built-in reporters](#reporters) as well. Their employment in browsers is neither recommended nor supported, open the console to see the test results. |
| 2231 |
|
| 2232 |
#### Options that _only_ function in browser context: |
| 2233 |
|
| 2234 |
`noHighlighting` _{boolean}_ |
| 2235 |
If set to `true`, do not attempt to use syntax highlighting on output test code. |
| 2236 |
|
| 2237 |
### Reporting |
| 2238 |
|
| 2239 |
The HTML reporter is the default reporter when running Mocha in the browser. It looks like this: |
| 2240 |
|
| 2241 |
{:class="screenshot" loading="lazy"} |
| 2242 |
|
| 2243 |
[Mochawesome][npm-mochawesome] is a great alternative to the default HTML reporter. |
| 2244 |
|
| 2245 |
## Configuring Mocha (Node.js) |
| 2246 |
|
| 2247 |
> _Since v6.0.0_ |
| 2248 |
|
| 2249 |
Mocha supports configuration files, typical of modern command-line tools, in several formats: |
| 2250 |
|
| 2251 |
- **JavaScript**: Create a `.mocharc.js` (or `.mocharc.cjs` when using [`"type"="module"`](#nodejs-native-esm-support) in your `package.json`) |
| 2252 |
in your project's root directory, and export an object (`module.exports = {/* ... */}`) containing your configuration. |
| 2253 |
- **YAML**: Create a `.mocharc.yaml` (or `.mocharc.yml`) in your project's root directory. |
| 2254 |
- **JSON**: Create a `.mocharc.json` (or `.mocharc.jsonc`) in your project's root directory. Comments — while not valid JSON — are allowed in this file, and will be ignored by Mocha. |
| 2255 |
- **package.json**: Create a `mocha` property in your project's `package.json`. |
| 2256 |
|
| 2257 |
### Custom Locations |
| 2258 |
|
| 2259 |
You can specify a custom location for your configuration file with the `--config <path>` option. Mocha will use the file's extension to determine how to parse the file, and will assume JSON if unknown. |
| 2260 |
|
| 2261 |
You can specify a custom `package.json` location as well, using the `--package <path>` option. |
| 2262 |
|
| 2263 |
### Ignoring Config Files |
| 2264 |
|
| 2265 |
To skip looking for config files, use `--no-config`. Likewise, use `--no-package` to stop Mocha from looking for configuration in a `package.json`. |
| 2266 |
|
| 2267 |
### Priorities |
| 2268 |
|
| 2269 |
If no custom path was given, and if there are multiple configuration files in the same directory, Mocha will search for — and use — only one. The priority is: |
| 2270 |
|
| 2271 |
1. `.mocharc.js` |
| 2272 |
1. `.mocharc.yaml` |
| 2273 |
1. `.mocharc.yml` |
| 2274 |
1. `.mocharc.jsonc` |
| 2275 |
1. `.mocharc.json` |
| 2276 |
|
| 2277 |
### Environment Variables |
| 2278 |
|
| 2279 |
The `MOCHA_OPTIONS` environment variable may be used to specify command line arguments. These arguments take priority over those found in configuration files. |
| 2280 |
|
| 2281 |
For example, setting the `bail` and `retries` options: |
| 2282 |
|
| 2283 |
```bash |
| 2284 |
$ MOCHA_OPTIONS="--bail --retries 3" mocha |
| 2285 |
``` |
| 2286 |
|
| 2287 |
### Merging |
| 2288 |
|
| 2289 |
Mocha will also _merge_ any options found in `package.json` into its run-time configuration. In case of conflict, the priority is: |
| 2290 |
|
| 2291 |
1. Arguments specified on command-line |
| 2292 |
1. Arguments specified in `MOCHA_OPTIONS` environment variable. |
| 2293 |
1. Configuration file (`.mocharc.js`, `.mocharc.yml`, etc.) |
| 2294 |
1. `mocha` property of `package.json` |
| 2295 |
|
| 2296 |
Options which can safely be repeated (e.g., `--require`) will be _concatenated_, with higher-priority configuration sources appearing earlier in the list. For example, a `.mocharc.json` containing `"require": "bar"` coupled with execution of `mocha --require foo` would cause Mocha to require `foo`, then `bar`, in that order. |
| 2297 |
|
| 2298 |
This also includes `spec`. For example, a `.mocharc.json` containing `"spec": ["**/*.test.js"]` coupled with execution of `mocha bar.spec.js` would be the same as runninng `mocha bar.spec.js **/*.test.js`, and it would still run all `.test.js` files. To workaround this, you can comment out the `spec` property or use a different config file via `--config`. |
| 2299 |
|
| 2300 |
### Extending Configuration |
| 2301 |
|
| 2302 |
Configurations can inherit from other modules using the `extends` keyword. See [here][yargs-configobject-extends] for more information. |
| 2303 |
|
| 2304 |
### Configuration Format |
| 2305 |
|
| 2306 |
- Any "boolean" flag (which doesn't require a parameter, such as `--bail`), can be specified using a boolean value, e.g.: `"bail": true`. |
| 2307 |
- Any "array"-type option (see `mocha --help` for a list) can be a single string value. |
| 2308 |
- For options containing a dash (`-`), the option name can be specified using camelCase. |
| 2309 |
- Aliases are valid names, e.g., `R` instead of `reporter`. |
| 2310 |
- Test files can be specified using `spec`, e.g., `"spec": "test/**/*.spec.js"`. |
| 2311 |
- Flags to `node` are _also_ supported in configuration files. Use caution, as these can vary between versions of Node.js! |
| 2312 |
|
| 2313 |
**For more configuration examples, see the [`example/config`][example-mocha-config] directory on GitHub.** |
| 2314 |
|
| 2315 |
## The `test/` Directory |
| 2316 |
|
| 2317 |
By default, `mocha` looks for the glob `"./test/*.{js,cjs,mjs}"`, so you may want to put |
| 2318 |
your tests in `test/` folder. If you want to include subdirectories, pass the |
| 2319 |
`--recursive` option. |
| 2320 |
|
| 2321 |
To configure where `mocha` looks for tests, you may pass your own glob: |
| 2322 |
|
| 2323 |
```bash |
| 2324 |
$ mocha --recursive "./spec/*.js" |
| 2325 |
``` |
| 2326 |
|
| 2327 |
Some shells support recursive matching by using the globstar (`**`) wildcard. Bash >= 4.3 supports this with the [`globstar` option][bash-globbing] which [must be enabled](https://github.com/mochajs/mocha/pull/3348#issuecomment-383937247) to get the same results as passing the `--recursive` option ([ZSH][zsh-globbing] and [Fish][fish-globbing] support this by default). With recursive matching enabled, the following is the same as passing `--recursive`: |
| 2328 |
|
| 2329 |
```bash |
| 2330 |
$ mocha "./spec/**/*.js" |
| 2331 |
``` |
| 2332 |
|
| 2333 |
You should _always_ quote your globs in npm scripts. If you |
| 2334 |
use quotes, the [`node-glob`][npm-glob] module will |
| 2335 |
handle its expansion. For maximum compatibility, |
| 2336 |
surround the entire expression with double quotes and refrain |
| 2337 |
from `$`, `"`, `^`, and `\` within your expression. |
| 2338 |
|
| 2339 |
See this [tutorial][gist-globbing-tutorial] on using globs. |
| 2340 |
|
| 2341 |
_Note_: Double quotes around the glob are recommended for portability. |
| 2342 |
|
| 2343 |
## Error Codes |
| 2344 |
|
| 2345 |
> _Since v6.0.0_ |
| 2346 |
|
| 2347 |
When Mocha itself throws exception, the associated `Error` will have a `code` property. Where applicable, consumers should check the `code` property instead of string-matching against the `message` property. The following table describes these error codes: |
| 2348 |
|
| 2349 |
| Code | Description | |
| 2350 |
| ---------------------------------- | ------------------------------------------------------------ | |
| 2351 |
| `ERR_MOCHA_INVALID_ARG_TYPE` | wrong type was passed for a given argument | |
| 2352 |
| `ERR_MOCHA_INVALID_ARG_VALUE` | invalid or unsupported value was passed for a given argument | |
| 2353 |
| `ERR_MOCHA_INVALID_EXCEPTION` | a falsy or otherwise underspecified exception was thrown | |
| 2354 |
| `ERR_MOCHA_INVALID_INTERFACE` | interface specified in options not found | |
| 2355 |
| `ERR_MOCHA_INVALID_REPORTER` | reporter specified in options not found | |
| 2356 |
| `ERR_MOCHA_NO_FILES_MATCH_PATTERN` | test file(s) could not be found | |
| 2357 |
| `ERR_MOCHA_UNSUPPORTED` | requested behavior, option, or parameter is unsupported | |
| 2358 |
|
| 2359 |
## Editor Plugins |
| 2360 |
|
| 2361 |
The following editor-related packages are available: |
| 2362 |
|
| 2363 |
### TextMate |
| 2364 |
|
| 2365 |
The [Mocha TextMate bundle][textmate-mocha] includes snippets to make writing tests quicker and more enjoyable. |
| 2366 |
|
| 2367 |
### JetBrains |
| 2368 |
|
| 2369 |
[JetBrains][] provides a [NodeJS plugin][jetbrains-plugin] for its suite of IDEs (IntelliJ IDEA, WebStorm, etc.), which contains a Mocha test runner, among other things. |
| 2370 |
|
| 2371 |
{:class="screenshot" loading="lazy"} |
| 2372 |
|
| 2373 |
The plugin is titled **NodeJS**, and can be installed via **Preferences** > **Plugins**, assuming your license allows it. |
| 2374 |
|
| 2375 |
### Wallaby.js |
| 2376 |
|
| 2377 |
[Wallaby.js][] is a continuous testing tool that enables real-time code coverage for Mocha with any assertion library in VS Code, Atom, JetBrains IDEs (IntelliJ IDEA, WebStorm, etc.), Sublime Text and Visual Studio for both browser and node.js projects. |
| 2378 |
|
| 2379 |
{:class="screenshot" loading="lazy"} |
| 2380 |
|
| 2381 |
### Emacs |
| 2382 |
|
| 2383 |
[Emacs][] support for running Mocha tests is available via a 3rd party package [mocha.el][emacs-mocha.el]. The package is available on MELPA, and can be installed via `M-x package-install mocha`. |
| 2384 |
|
| 2385 |
{:class="screenshot" loading="lazy"} |
| 2386 |
|
| 2387 |
### Mocha Sidebar (VS Code) |
| 2388 |
|
| 2389 |
[Mocha sidebar][vscode-mocha-sidebar] is the most complete mocha extension for vs code. |
| 2390 |
|
| 2391 |
#### Features |
| 2392 |
|
| 2393 |
- see all tests in VS Code sidebar menu |
| 2394 |
- run & debug tests for each level hierarchy from all tests to a single test (and each suite) |
| 2395 |
- auto run tests on file save |
| 2396 |
- see tests results directly in the code editor |
| 2397 |
|
| 2398 |
{:class="screenshot" loading="lazy"} |
| 2399 |
|
| 2400 |
## Examples |
| 2401 |
|
| 2402 |
Real live example code: |
| 2403 |
|
| 2404 |
- [Mocha examples][mocha-examples] |
| 2405 |
- [Express][example-express-test] |
| 2406 |
- [Connect][example-connect-test] |
| 2407 |
- [SuperAgent][example-superagent-test] |
| 2408 |
- [WebSocket.io][example-websocket.io-test] |
| 2409 |
- [Mocha tests][example-mocha-test] |
| 2410 |
|
| 2411 |
## Testing Mocha |
| 2412 |
|
| 2413 |
To run Mocha's tests, you will need GNU Make or compatible; Cygwin should work. |
| 2414 |
|
| 2415 |
```bash |
| 2416 |
$ cd /path/to/mocha |
| 2417 |
$ npm install |
| 2418 |
$ npm test |
| 2419 |
``` |
| 2420 |
|
| 2421 |
## More Information |
| 2422 |
|
| 2423 |
In addition to chatting with us on [our Discord][discord-mocha], for additional information such as using |
| 2424 |
spies, mocking, and shared behaviours be sure to check out the [Mocha Wiki][mocha-wiki] on GitHub. |
| 2425 |
For a running example of Mocha, view [example/tests.html](example/tests.html). For the JavaScript API, view the [API documentation](api/) |
| 2426 |
or the [source](https://github.com/mochajs/mocha/blob/main/lib/mocha.js). |
| 2427 |
|
| 2428 |
[//]: # "Cross reference section" |
| 2429 |
[bash-globbing]: https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html |
| 2430 |
[better-assert]: https://github.com/visionmedia/better-assert |
| 2431 |
[caniuse-notifications]: https://caniuse.com/#feat=notifications |
| 2432 |
[caniuse-promises]: https://caniuse.com/#feat=promises |
| 2433 |
[chai]: https://www.chaijs.com/ |
| 2434 |
[connect-test-output]: https://github.com/senchalabs/connect/blob/90a725343c2945aaee637e799b1cd11e065b2bff/tests.md |
| 2435 |
[discord-mocha]: https://discord.gg/KeDn2uXhER |
| 2436 |
[emacs]: https://www.gnu.org/software/emacs/ |
| 2437 |
[emacs-mocha.el]: https://github.com/scottaj/mocha.el |
| 2438 |
[example-babel]: https://github.com/mochajs/mocha-examples/tree/main/packages/babel |
| 2439 |
[example-connect-test]: https://github.com/senchalabs/connect/tree/master/test |
| 2440 |
[example-express-test]: https://github.com/visionmedia/express/tree/master/test |
| 2441 |
[example-mocha-test]: https://github.com/mochajs/mocha/tree/main/test |
| 2442 |
[example-mocha-config]: https://github.com/mochajs/mocha/tree/main/example/config |
| 2443 |
[example-superagent-test]: https://github.com/visionmedia/superagent/tree/master/test/node |
| 2444 |
[example-third-party-reporter]: https://github.com/mochajs/mocha-examples/tree/main/packages/third-party-reporter |
| 2445 |
[example-typescript]: https://github.com/mochajs/mocha-examples/tree/main/packages/typescript |
| 2446 |
[example-websocket.io-test]: https://github.com/LearnBoost/websocket.io/tree/master/test |
| 2447 |
[expect.js]: https://github.com/LearnBoost/expect.js |
| 2448 |
[expresso]: https://github.com/tj/expresso |
| 2449 |
[fish-globbing]: https://fishshell.com/docs/current/#expand-wildcard |
| 2450 |
[github-mocha]: https://github.com/mochajs/mocha |
| 2451 |
[gist-async-hooks]: https://gist.github.com/boneskull/7fe75b63d613fa940db7ec990a5f5843 |
| 2452 |
[gist-globbing-tutorial]: https://gist.github.com/reggi/475793ea1846affbcfe8 |
| 2453 |
[jetbrains]: https://www.jetbrains.com/ |
| 2454 |
[jetbrains-plugin]: https://www.jetbrains.com/idea/features/nodejs.html |
| 2455 |
[mdn-array-sort]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort |
| 2456 |
[mdn-arrow]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions |
| 2457 |
[mdn-async]: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/async_function |
| 2458 |
[mdn-promise]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise |
| 2459 |
[mdn-regexp]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Regexp |
| 2460 |
[mdn-settimeout-maxdelay]: https://developer.mozilla.org/docs/Web/API/WindowTimers/setTimeout#Maximum_delay_value |
| 2461 |
[mocha-examples]: https://github.com/mochajs/mocha-examples |
| 2462 |
[mocha-teamcity-reporter]: https://github.com/travisjeffery/mocha-teamcity-reporter |
| 2463 |
[mocha-website]: https://mochajs.org/ |
| 2464 |
[mocha-wiki]: https://github.com/mochajs/mocha/wiki |
| 2465 |
[mocha-wiki-compilers]: https://github.com/mochajs/mocha/wiki/compilers-deprecation |
| 2466 |
[mocha-wiki-more-reporters]: https://github.com/mochajs/mocha/wiki/Third-party-reporters |
| 2467 |
[node.js]: https://nodejs.org/ |
| 2468 |
[node-assert]: https://nodejs.org/api/assert.html |
| 2469 |
[node-async-hooks]: https://github.com/nodejs/node/blob/master/doc/api/async_hooks.md |
| 2470 |
[node-inspector]: https://nodejs.org/en/docs/inspector/ |
| 2471 |
[npm]: https://npmjs.org/ |
| 2472 |
[npm-babel-register]: https://npm.im/@babel/register |
| 2473 |
[npm-chai-as-promised]: https://www.npmjs.com/package/chai-as-promised |
| 2474 |
[npm-glob]: https://www.npmjs.com/package/glob |
| 2475 |
[npm-mocha-lcov-reporter]: https://npm.im/mocha-lcov-reporter |
| 2476 |
[npm-mochawesome]: https://npm.im/mochawesome |
| 2477 |
[npm-should.js]: https://npm.im/should |
| 2478 |
[npm-supports-color]: https://npm.im/supports-color |
| 2479 |
[npm-ts-node]: https://npm.im/ts-node |
| 2480 |
[npm-wtfnode]: https://npm.im/wtfnode |
| 2481 |
[qunit]: https://qunitjs.com/ |
| 2482 |
[selenium-webdriver-testing]: https://github.com/SeleniumHQ/selenium/blob/c10e8a955883f004452cdde18096d70738397788/javascript/node/selenium-webdriver/testing/index.js |
| 2483 |
[should.js]: https://github.com/shouldjs/should.js |
| 2484 |
[superagent-docs-test]: https://ladjs.github.io/superagent/docs/test.html |
| 2485 |
[superagent-makefile]: https://github.com/visionmedia/superagent/blob/master/Makefile |
| 2486 |
[test-anything-protocol]: https://en.wikipedia.org/wiki/Test_Anything_Protocol |
| 2487 |
[textmate-mocha]: https://github.com/mochajs/mocha.tmbundle |
| 2488 |
[unexpected]: https://unexpected.js.org/ |
| 2489 |
[vscode-mocha-sidebar]: https://marketplace.visualstudio.com/items?itemName=maty.vscode-mocha-sidebar |
| 2490 |
[wallaby.js]: https://wallabyjs.com/ |
| 2491 |
[yargs-configobject-extends]: http://yargs.js.org/docs/#api-reference-configobject-extends-keyword |
| 2492 |
[zsh-globbing]: http://zsh.sourceforge.net/Doc/Release/Expansion.html#Recursive-Globbing |
| 2493 |
[root hook plugins]: #root-hook-plugins |
| 2494 |
[global setup fixtures]: #global-setup-fixtures |
| 2495 |
[global teardown fixtures]: #global-teardown-fixtures |
| 2496 |
[global fixtures]: #global-fixtures |
| 2497 |
[hooks]: #hooks |