### Example Test File
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/getting-started.mdx
Create the following `example.test.js` file under a `test/` directory.
```javascript
// test/example.test.js
import assert from "node:assert";
describe("Array", function () {
describe("#indexOf()", function () {
it("should return -1 when the value is not present", function () {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});
```
--------------------------------
### Example HTML setup for running Mocha in a browser
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/running/browsers.mdx
This HTML file demonstrates a typical setup for running Mocha tests in a browser. It includes loading Mocha and Chai, setting up the Mocha interface, and loading test scripts.
```html
Mocha Tests
```
--------------------------------
### Running Mocha Command
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/getting-started.mdx
Now, run `npx mocha` to execute the Mocha package on the newly created test file.
```shell
npx mocha
```
--------------------------------
### Running the Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/third-party-uis.mdx
This section shows the command-line instructions to install dependencies, run the custom Mocha UI with a test file, and the expected output, including a passing test and a failing test.
```bash
$ # install both dependencies
$ npm install mocha escape-string-regexp
$ # Run our example
$ mocha --require ./example-ui.js --ui example-ui test.js
Example
- Here's the addition we made to the UI
✓ passing test
1) failing test
1 passing (5ms)
1 pending
1 failing
1) Example failing test:
Error: it failed!
at Context. (/Users/danielstjules/Desktop/example/test.js:11:11)
at callFn (/Users/danielstjules/Desktop/example/node_modules/mocha/lib/runnable.js:266:21)
at Test.Runnable.run
....
```
--------------------------------
### Optional: `test` script in package.json
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/getting-started.mdx
Most projects include a [`package.json` "test" script](https://docs.npmjs.com/cli/commands/npm-test):
```json
// package.json
{
"scripts": {
"test": "mocha"
}
}
```
--------------------------------
### Global Setup Fixture (ES Module)
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/features/global-fixtures.mdx
Example of a global setup fixture using ES module format.
```js
// fixtures.mjs
// can be async or not
export async function mochaGlobalSetup() {
this.server = await startSomeServer({ port: process.env.TEST_PORT });
console.log(`server running on port ${this.server.port}`);
}
```
--------------------------------
### Global Setup Fixture (CommonJS)
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/features/global-fixtures.mdx
Example of a global setup fixture using CommonJS module format.
```js
// fixtures.cjs
// can be async or not
exports.mochaGlobalSetup = async function () {
this.server = await startSomeServer({ port: process.env.TEST_PORT });
console.log(`server running on port ${this.server.port}`);
};
```
--------------------------------
### Browser Configuration Examples
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/running/browsers.mdx
Examples of how to configure Mocha in the browser using `mocha.setup()`. This includes setting the interface and various other options.
```js
// Use "tdd" interface. This is a shortcut to setting the interface;
// any other options must be passed via an object.
mocha.setup('tdd');
// This is equivalent to the above.
mocha.setup({
ui: 'tdd'
});
// Examples of options:
mocha.setup({
allowUncaught: true,
asyncOnly: true,
bail: true,
checkLeaks: true,
dryRun: true,
failZero: true,
forbidOnly: true,
forbidPending: true,
global: ['MyLib'],
retries: 3,
rootHooks: { beforeEach(done) { ... done();} },
slow: '100',
timeout: '2000',
ui: 'bdd'
});
```
--------------------------------
### Hello World Example - Run Command
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/typescript.mdx
Command to run the Hello World TypeScript example with Mocha.
```bash
npx mocha --extension ts src/add.test.ts
```
--------------------------------
### Simple UI Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/third-party-uis.mdx
An example of a simple UI with only a 'test' function.
```javascript
import Mocha from "mocha";
import { createCommon as MochaInterface } from "mocha/lib/interfaces/common.mjs";
const Test = Mocha.Test;
/**
* A simple UI that only exposes a single function: test
*/
function SimpleUI(suite) {
suite.on("pre-require", function (context, file, mocha) {
const common = MochaInterface([suite], context);
context.run = mocha.options.delay && common.runWithSuite(suite);
/**
* Describes a specification or test-case with the given `title`
* and callback `fn` acting as a thunk.
*/
context.test = function (title, fn) {
const test = new Test(title, fn);
test.file = file;
suite.addTest(test);
return test;
};
});
}
Mocha.interfaces["simple-ui"] = SimpleUI;
export default SimpleUI;
```
```javascript
test("pass", function () {
// pass
});
test("fail", function () {
throw new Error("oops!");
});
```
```bash
$ # Install dependencies
$ npm install mocha
$ mocha --require ./simple-ui.js --ui simple-ui test.js
✓ pass
1) fail
1 passing (4ms)
1 failing
1) fail:
Error: oops!
at Context. (/Users/danielstjules/Desktop/example/test.js:6:9)
...
```
--------------------------------
### BDD Interface Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/interfaces/bdd.mdx
An example demonstrating the BDD interface with describe, context, and it blocks.
```javascript
describe("Array", function () {
before(function () {
// ...
});
describe("#indexOf()", function () {
context("when not present", function () {
it("should not throw an error", function () {
(function () {
[1, 2, 3].indexOf(4);
}).should.not.throw();
});
it("should return -1", function () {
[1, 2, 3].indexOf(4).should.equal(-1);
});
});
context("when present", function () {
it("should return the index where the element first appears in the array", function () {
[1, 2, 3].indexOf(3).should.equal(2);
});
});
});
});
```
--------------------------------
### Enable Source Maps Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/running/cli.mdx
Demonstrates how to use the `--enable-source-maps` flag to collect and use source maps for accurate stack traces with transpiled code, showing an example stack trace with original source file information.
```bash
# Example usage (not a direct code block, but illustrates the flag's effect)
# The following is a representation of the output when --enable-source-maps is used:
# Error: cool
# at Object. (/Users/fake-user/bigco/nodejs-tasks/build/src/index.js:27:7)
# -> /Users/fake-user/bigco/nodejs-tasks/src/index.ts:24:7
```
--------------------------------
### Run the site
Source: https://github.com/mochajs/mocha/blob/main/docs/README.md
Commands to install dependencies, generate the site, and run the development server.
```shell
cd docs
npm i
npm run generate
npm run dev
```
--------------------------------
### Delayed Root Suite Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/features/hooks.mdx
With `--delay`, Mocha loads your test file and executes its top-level code as usual, but waits to run tests until you call `run()`. Place your `describe()` and `it()` calls inside the asynchronous code so that suites are registered after setup completes, then call `run()` to begin execution:
```javascript
import assert from "node:assert";
const fn = async (x) => {
return new Promise((resolve) => {
setTimeout(resolve, 3000, 2 * x);
});
};
// instead of an IIFE, you can use 'setImmediate' or 'nextTick' or 'setTimeout'
(async function () {
const z = await fn(3);
describe("my suite", function () {
it(`expected value ${z}`, function () {
assert.strictEqual(z, 6);
});
});
run();
})();
```
--------------------------------
### Combined Global Fixtures (ES Module)
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/features/global-fixtures.mdx
Example of a single file containing both global setup and teardown fixtures using ES module format.
```js
// fixtures.mjs
let server;
export const mochaGlobalSetup = async () => {
server = await startSomeServer({ port: process.env.TEST_PORT });
console.log(`server running on port ${server.port}`);
};
export const mochaGlobalTeardown = async () => {
await server.stop();
console.log("server stopped!");
};
```
--------------------------------
### Example test structure with tags
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/tagging.mdx
This example demonstrates how to tag test suites and test cases using custom strings like '@fast' and '@slow'.
```javascript
describe("app", function () {
describe("GET /login", function () {
it("should respond with the login form @fast", function () {
// ...
});
});
describe("GET /download/:file", function () {
it("should respond with the file @slow", function () {
// ...
});
});
});
```
--------------------------------
### Require Interface Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/interfaces/require.mdx
Example of using the require interface to import describe, before, and it functions from Mocha.
```javascript
import { describe as testCase, before as pre, it as assertions } from "mocha";
import { assert } from "chai";
testCase("Array", function () {
pre(function () {
// ...
});
testCase("#indexOf()", function () {
assertions("should return -1 when not present", function () {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
});
```
--------------------------------
### QUnit Interface Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/interfaces/qunit.mdx
An example demonstrating the QUnit test interface for Mocha, including suite and test definitions.
```javascript
function ok(expr, msg) {
if (!expr) throw new Error(msg);
}
suite("Array");
test("#length", function () {
var arr = [1, 2, 3];
ok(arr.length == 3);
});
test("#indexOf()", function () {
var arr = [1, 2, 3];
ok(arr.indexOf(1) == 0);
ok(arr.indexOf(2) == 1);
ok(arr.indexOf(3) == 2);
});
suite("String");
test("#length", function () {
ok("foo".length == 3);
});
```
--------------------------------
### TDD Interface Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/interfaces/tdd.mdx
An example demonstrating the TDD interface with nested suites and tests.
```javascript
suite("Array", function () {
setup(function () {
// ...
});
suite("#indexOf()", function () {
test("should return -1 when not present", function () {
assert.equal(-1, [1, 2, 3].indexOf(4));
});
});
});
```
--------------------------------
### Grep Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/running/cli.mdx
Illustrates how to use the `--grep` option to filter tests based on titles, showing examples for 'api' and 'app' suites, and demonstrating different quoting and pattern syntaxes.
```javascript
describe("api", function () {
describe("GET /api/users groupA", function () {
it("respond with an array of users", function () {
// ...
});
});
});
describe("app", function () {
describe("GET /users groupB", function () {
it("respond with an array of users", function () {
// ...
});
});
});
```
--------------------------------
### Exports Interface Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/interfaces/exports.mdx
An example demonstrating the structure and usage of the Exports interface in MochaJS.
```javascript
module.exports = {
before: function () {
// ...
},
Array: {
"#indexOf()": {
"should return -1 when not present": function () {
[1, 2, 3].indexOf(4).should.equal(-1);
},
},
},
};
```
--------------------------------
### Hello World Example - Test File
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/typescript.mdx
A minimal TypeScript test file 'src/add.test.ts' for the 'add' function.
```typescript
import assert from "node:assert/strict";
import { add } from "./add.ts";
describe("add", function () {
it("should add two numbers", function () {
assert.strictEqual(add(1, 2), 3);
});
});
```
--------------------------------
### Root Hook Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/features/parallel-mode.mdx
An example of root hooks in Mocha's BDD interface.
```javascript
// test/setup.js
// root hook to run before every test (even in other files)
beforeEach(function () {
doMySetup();
});
// root hook to run after every test (even in other files)
afterEach(function () {
doMyTeardown();
});
```
--------------------------------
### Choosing multiple suites
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/declaring/exclusive-tests.mdx
This example demonstrates how to select multiple suites for execution using `.only()`.
```javascript
describe("Array", function () {
describe.only("#indexOf()", function () {
it("should return -1 unless present", function () {
// this test will be run
});
it("should return the index when present", function () {
// this test will also be run
});
});
describe.only("#concat()", function () {
it("should return a new Array", function () {
// this test will also be run
});
});
describe("#slice()", function () {
it("should return a new Array", function () {
// this test will not be run
});
});
});
```
--------------------------------
### Example ES Module Test File
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/nodejs-native-esm-support.mdx
An example of a test file written as an ES module using `.mjs` extension.
```javascript
// test.mjs
import { add } from "./add.mjs";
import assert from "node:assert";
it("should add to numbers from an es module", () => {
assert.equal(add(3, 5), 8);
});
```
--------------------------------
### Basic programmatic usage
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/programmatic-usage.mdx
An example of using Mocha programmatically to add and run tests.
```javascript
import Mocha from "mocha";
import fs from "node:fs";
import path from "node:path";
// Instantiate a Mocha instance.
const mocha = new Mocha();
const testDir = "some/dir/test";
// Add each .js file to the mocha instance
fs.readdirSync(testDir)
.filter(function (file) {
// Only keep the .js files
return file.endsWith(".js");
})
.forEach(function (file) {
mocha.addFile(path.join(testDir, file));
});
// Run the tests.
mocha.run(function (failures) {
process.exitCode = failures ? 1 : 0; // exit with non-zero status if there were failures
});
```
--------------------------------
### Runtime skip using this.skip()
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/declaring/inclusive-tests.mdx
This example illustrates skipping a test at runtime based on environment conditions.
```javascript
it("should only test in the correct environment", function () {
if (/* check test environment */) {
// make assertions
} else {
this.skip();
}
});
```
--------------------------------
### Skipping an individual test
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/declaring/inclusive-tests.mdx
This example demonstrates how to skip a single test case using `.skip()`.
```javascript
describe("Array", function () {
describe("#indexOf()", function () {
it.skip("should return -1 unless present", function () {
// this test will not be run
});
it("should return the index when present", function () {
// this test will be run
});
});
});
```
--------------------------------
### Skipping an entire suite
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/declaring/inclusive-tests.mdx
This example shows how to skip all tests within a suite using `.skip()` on the describe block.
```javascript
describe("Array", function () {
describe.skip("#indexOf()", function () {
it("should return -1 unless present", function () {
// this test will not be run
});
});
});
```
--------------------------------
### Example of updating package.json for TypeScript
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/compilers-deprecation.mdx
Shows how to update package.json to use require instead of compilers for TypeScript.
```bash
--require ts-node/register
```
--------------------------------
### Test Spec Using Global Fixtures
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/features/global-fixtures.mdx
Example of a test spec that connects to a server started by a global fixture.
```js
// test.spec.mjs
import { connect } from "my-server-connector-thingy";
describe("my API", function () {
let connection;
before(async function () {
connection = await connect({ port: process.env.TEST_PORT });
});
it("should be a nice API", function () {
// assertions here
});
after(async function () {
return connection.close();
});
});
```
--------------------------------
### Reporter option
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/running/cli.mdx
Specify the reporter that will be used, defaulting to spec. Allows use of third-party reporters. For example, mocha-lcov-reporter may be used with --reporter mocha-lcov-reporter after it has been installed.
```bash
--reporter , -R
```
--------------------------------
### Example Test Suite
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/third-party-uis.mdx
This JavaScript code demonstrates how to use the custom 'example-ui' interface to define a test suite with comments and passing/failing tests.
```javascript
suite("Example", function () {
comment("Here's the addition we made to the UI");
test("passing test", function () {
// Pass
});
test("failing test", function () {
throw new Error("it failed!");
});
});
```
--------------------------------
### Fast Sanity Check Commands
Source: https://github.com/mochajs/mocha/blob/main/AGENTS.md
Commands for a fast sanity check, recommended before and after focused edits.
```bash
npm run clean
npm run build
npm run tsc
npm run test-smoke
Targeted tests relevant to changed area (see below)
```
--------------------------------
### Quick Start - Command Line
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/typescript.mdx
Run Mocha against ts files matching your spec pattern by specifying --extension.
```bash
mocha --extension ts
```
--------------------------------
### Hello World Example - Source File
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/typescript.mdx
A minimal TypeScript source file 'src/add.ts' using ESM import syntax.
```typescript
export function add(a: number, b: number) {
return a + b;
}
```
--------------------------------
### Bootstrap Commands
Source: https://github.com/mochajs/mocha/blob/main/AGENTS.md
Commands to bootstrap the project, including a note on using `npm ci --ignore-scripts` for clean CI reproduction.
```bash
npm install
(Docs work only) cd docs && npm install
```
--------------------------------
### Retry Tests Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/declaring/retrying-tests.mdx
Example demonstrating how to configure test retries in MochaJS.
```javascript
describe("retries", function () {
// Retry all tests in this suite up to 4 times
this.retries(4);
beforeEach(function () {
browser.get("http://www.yahoo.com");
});
it("should succeed by the 3rd try", function () {
// Specify this test to only retry up to 2 times
this.retries(2);
expect($(".foo").isDisplayed()).to.eventually.be.true;
});
});
```
--------------------------------
### Targeted Browser Tests
Source: https://github.com/mochajs/mocha/blob/main/AGENTS.md
Commands for running targeted browser tests.
```bash
npm run test-browser:reporters:bdd
npm run test-browser
```
--------------------------------
### Quick Start - Configuration File
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/typescript.mdx
Configure Mocha to discover .ts files by adding 'ts' to the extension array in a configuration file.
```javascript
export default {
extension: ["js", "ts"],
spec: "test/**/*.ts",
};
```
--------------------------------
### Pending Test Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/declaring/pending-tests.mdx
An example of a pending test case in Mocha.js, which is defined with a name but without a callback function.
```javascript
describe("Array", function () {
describe("#indexOf()", function () {
// pending test below
it("should return -1 when the value is not present");
});
});
```
--------------------------------
### Full Local Gate Commands
Source: https://github.com/mochajs/mocha/blob/main/AGENTS.md
Commands to perform a full local gate, aiming for closest parity with CI intent.
```bash
npm run format:check
npm run lint
npm run test-node
npm run test-browser
npm run tsc
```
--------------------------------
### Global variables example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/global-variables.mdx
This example demonstrates how to manage global variables in Mocha tests, specifically focusing on cleaning up after manipulating `process.stdout.write` and `console.log`.
```javascript
import { expect } from "chai";
describe("my nice test", function () {
let write,
log,
output = "";
// restore process.stdout.write() and console.log() to their previous glory
const cleanup = function () {
process.stdout.write = write;
console.log = log;
output = "";
};
beforeEach(function () {
// store these functions to restore later because we are messing with them
write = process.stdout.write;
log = console.log;
// our stub will concatenate any output to a string
process.stdout.write = console.log = function (s) {
output += s;
};
});
// restore after each test
afterEach(cleanup);
it("should suppress all output if a non-AssertionError was thrown", function () {
process.stdout.write("foo");
console.log("bar");
// uncomment below line to suppress output, which is bad
// expect(output).to.equal(foobar);
expect(output).to.equal("foobar");
});
it("should not suppress any output", function () {
try {
process.stdout.write("foo");
console.log("bar");
// uncomment below line to just throw an AssertionError
// expect(output).to.equal('barfoo');
expect(output).to.equal(foobar); // ReferenceError
} catch (e) {
cleanup();
throw e;
}
});
});
```
--------------------------------
### Double done() call example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/detecting-multiple-calls-to-done.mdx
This example demonstrates how Mocha throws an error when the `done()` callback is invoked more than once in an asynchronous test.
```javascript
it("double done", function (done) {
// Calling `done()` twice is an error
setImmediate(done);
setImmediate(done);
});
```
--------------------------------
### Dynamic Test Generation with forEach
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/declaring/dynamic-tests.mdx
This example demonstrates how to dynamically generate test cases using a forEach loop in JavaScript.
```javascript
import assert from "node:assert";
function add(args) {
return args.reduce((prev, curr) => prev + curr, 0);
}
describe("add()", function () {
const tests = [
{ args: [1, 2], expected: 3 },
{ args: [1, 2, 3], expected: 6 },
{ args: [1, 2, 3, 4], expected: 10 },
];
tests.forEach(({ args, expected }) => {
it(`correctly adds ${args.length} args`, function () {
const res = add(args);
assert.strictEqual(res, expected);
});
});
});
```
--------------------------------
### Test that does nothing
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/declaring/inclusive-tests.mdx
This example shows a test that does nothing, which will be reported as passing.
```javascript
it("should only test in the correct environment", function () {
if (/* check test environment */) {
// make assertions
} else {
// do nothing
}
});
```
--------------------------------
### Targeted Node Tests
Source: https://github.com/mochajs/mocha/blob/main/AGENTS.md
Commands for running targeted Node.js tests for different areas of the project.
```bash
npm run test-node:unit
npm run test-node:integration
npm run test-node:interfaces
npm run test-node:reporters
```
--------------------------------
### Using Sinon spies
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/spies.mdx
An example of Mocha utilizing Sinon and Should.js to test an EventEmitter.
```javascript
import sinon from "sinon";
import { EventEmitter } from "node:events";
describe("EventEmitter", function () {
describe("#emit()", function () {
it("should invoke the callback", function () {
const spy = sinon.spy(),
emitter = new EventEmitter();
emitter.on("foo", spy);
emitter.emit("foo");
spy.called.should.equal.true;
});
it("should pass arguments to the callbacks", function () {
const spy = sinon.spy(),
emitter = new EventEmitter();
emitter.on("foo", spy);
emitter.emit("foo", "bar", "baz");
sinon.assert.calledOnce(spy);
sinon.assert.calledWith(spy, "bar", "baz");
});
});
});
```
--------------------------------
### Extending TDD Interface Example
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/third-party-uis.mdx
Extends the TDD interface with a 'comment' function.
```javascript
import Mocha from "mocha";
import { createCommon as MochaInterface } from "mocha/lib/interfaces/common.mjs";
import escapeStringRegexp from "escape-string-regexp";
const Test = Mocha.Test;
const Suite = Mocha.Suite;
/**
* This example is identical to the TDD interface, but with the addition of a
* "comment" function:
* https://github.com/mochajs/mocha/blob/master/lib/interfaces/tdd.js
*/
function ExampleUI(suite) {
var suites = [suite];
suite.on("pre-require", function (context, file, mocha) {
var common = MochaInterface([suite], context);
/**
* Use all existing hook logic common to UIs. Common logic can be found in
* https://github.com/mochajs/mocha/blob/master/lib/interfaces/common.js
*/
context.setup = common.beforeEach;
context.teardown = common.afterEach;
context.suiteSetup = common.before;
context.suiteTeardown = common.after;
context.run = mocha.options.delay && common.runWithSuite(suite);
/**
* Our addition. A comment function that creates a pending test and
* adds an isComment attribute to the test for identification by a
* third party, custom reporter. The comment will be printed just like
* a pending test. But any custom reporter could check for the isComment
* attribute on a test to modify its presentation.
*/
context.comment = function (title) {
let suite, comment;
suite = suites[0];
comment = new Test(title, null);
comment.pending = true;
comment.isComment = true;
comment.file = file;
suite.addTest(comment);
return comment;
};
// Remaining logic is from the tdd interface, but is necessary for a
// complete example
// https://github.com/mochajs/mocha/blob/master/lib/interfaces/tdd.js
/**
* The default TDD suite functionality. Describes a suite with the
* given title and callback, fn`, which may contain nested suites
* and/or tests.
*/
context.suite = function (title, fn) {
const suite = Suite.create(suites[0], title);
suite.file = file;
suites.unshift(suite);
fn.call(suite);
suites.shift();
return suite;
};
/**
* The default TDD pending suite functionality.
*/
context.suite.skip = function (title, fn) {
const suite = Suite.create(suites[0], title);
suite.pending = true;
suites.unshift(suite);
fn.call(suite);
suites.shift();
};
/**
* Default TDD exclusive test-case logic.
*/
context.suite.only = function (title, fn) {
const suite = context.suite(title, fn);
mocha.grep(suite.fullTitle());
};
/**
```
--------------------------------
### Mocha CLI Help Output
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/running/cli.mdx
The output of `npx mocha --help` displays all available commands, rules, and options for running Mocha via the command line.
```plaintext
mocha [spec..]
Run tests with Mocha
Commands
mocha inspect [spec..] Run tests with Mocha [default]
mocha init create a client-side Mocha setup at
Rules & Behavior
--allow-uncaught Allow uncaught errors to propagate [boolean]
-A, --async-only Require all tests to use a callback (async)
or return a Promise [boolean]
-b, --bail Abort ("bail") after first test failure
[boolean]
--check-leaks Check for global variable leaks [boolean]
--delay Delay initial execution of root suite
[boolean]
--dry-run Report tests without executing them[boolean]
--exit Force Mocha to quit after tests complete
[boolean]
--pass-on-failing-test-suite Not fail test run if tests were failed
[boolean] [default: false]
--fail-zero Fail test run if no test(s) encountered
[boolean]
--forbid-only Fail if exclusive test(s) encountered
[boolean]
--forbid-pending Fail if pending test(s) encountered[boolean]
--global, --globals List of allowed global variables [array]
-j, --jobs Number of concurrent jobs for --parallel;
use 1 to run in serial
[number] [default: (number of CPU cores - 1)]
-p, --parallel Run tests in parallel [boolean]
--retries Retry failed tests this many times [number]
-s, --slow Specify "slow" test threshold (in
milliseconds) [string] [default: 75]
-t, --timeout, --timeouts Specify test timeout threshold (in
milliseconds) [string] [default: 2000]
-u, --ui Specify user interface
[string] [default: "bdd"]
Reporting & Output
-c, --color, --colors Force-enable color output [boolean]
--diff Show diff on failure
[boolean] [default: true]
--full-trace Display full stack traces [boolean]
--inline-diffs Display actual/expected differences
inline within each string [boolean]
-R, --reporter Specify reporter to use
[string] [default: "spec"]
-O, --reporter-option, Reporter-specific options
--reporter-options () [array]
Configuration
--config Path to config file [string] [default: (nearest rc file)]
-n, --node-option Node or V8 option (no leading "--") [array]
--package Path to package.json for config [string]
File Handling
--extension File extension(s) to load
[array] [default: ["js","cjs","mjs"]]
--file Specify file(s) to be loaded prior to root suite
execution [array] [default: (none)]
--ignore, --exclude Ignore file(s) or glob pattern(s)
[array] [default: (none)]
--recursive Look for tests in subdirectories [boolean]
-r, --require Require module [array] [default: (none)]
-S, --sort Sort test files [boolean]
-w, --watch Watch files in the current working directory for
changes [boolean]
--watch-files List of paths or globs to watch [array]
--watch-ignore List of paths or globs to exclude from watching
[array] [default: ["node_modules",".git"]]
Test Filters
-f, --fgrep Only run tests containing this string [string]
```
--------------------------------
### Using --watch with --watch-extensions
Source: https://github.com/mochajs/mocha/blob/main/docs/src/content/docs/explainers/compilers-deprecation.mdx
Demonstrates how to use --watch-extensions to specify file extensions when using --watch.
```bash
$ mocha --require coffeescript/register --watch --watch-extensions js,coffee "test/**/*.{js,coffee}"
```