Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

docs: modernize code examples (#5687)

Copilot9c4966a47e7d
diff --git a/docs/src/content/docs/declaring/dynamic-tests.mdx b/docs/src/content/docs/declaring/dynamic-tests.mdx
index b2921727..d5ddc752 100644
--- a/docs/src/content/docs/declaring/dynamic-tests.mdx
+++ b/docs/src/content/docs/declaring/dynamic-tests.mdx
@@ -9,7 +9,7 @@ No special syntax is required--plain old JavaScript can be used to achieve funct
Take the following example:
```js
-const assert = require("assert");
+import assert from "node:assert";
function add(args) {
return args.reduce((prev, curr) => prev + curr, 0);
@@ -66,9 +66,9 @@ See also [`--delay`](/features/hooks#delayed-root-suite) for CommonJS modules wi
```js
// testfile.mjs
-import assert from "assert";
+import assert from "node:assert";
-// top-level await: Node >= v14.8.0 with ESM test file
+// top-level await: requires ESM test files (.mjs or "type": "module" in package.json)
const tests = await new Promise((resolve) => {
setTimeout(resolve, 5000, [
{ args: [1, 2], expected: 3 },
diff --git a/docs/src/content/docs/declaring/inclusive-tests.mdx b/docs/src/content/docs/declaring/inclusive-tests.mdx
index 1797eb4e..26a94110 100644
--- a/docs/src/content/docs/declaring/inclusive-tests.mdx
+++ b/docs/src/content/docs/declaring/inclusive-tests.mdx
@@ -47,7 +47,7 @@ If a test needs an environment or configuration which cannot be detected beforeh
For example:
```js
-it('should only test in the correct environment', function() {
+it("should only test in the correct environment", function () {
if (/* check test environment */) {
// make assertions
} else {
@@ -66,7 +66,7 @@ To avoid confusion, do not execute further instructions in a test or hook after
Contrast the above test with the following code:
```js
-it('should only test in the correct environment', function() {
+it("should only test in the correct environment", function () {
if (/* check test environment */) {
// make assertions
} else {
@@ -85,7 +85,7 @@ A test should make an assertion or use `this.skip()`.
To skip _multiple_ tests in this manner, use `this.skip()` in a "before all" hook:
```js
-before(function() {
+before(function () {
if (/* check test environment */) {
// setup code
} else {
diff --git a/docs/src/content/docs/explainers/environment-variables.mdx b/docs/src/content/docs/explainers/environment-variables.mdx
index 90a0c305..e9218ec7 100644
--- a/docs/src/content/docs/explainers/environment-variables.mdx
+++ b/docs/src/content/docs/explainers/environment-variables.mdx
@@ -29,11 +29,11 @@ if (process.env.CI === "STAGE") // do something
The value is available from anywhere in a spec file allowing you to set values from it before the tests run. e.g.
```javascript
-import { equal } from "assert";
+import { equal } from "node:assert";
import { loadPage } from "your-code";
const URL = `${process.env.APP_HOST}/${process.env.APP_URI}`;
-describe('Test the page loads', () {
- it('goes to URL', () => {
+describe("Test the page loads", () => {
+ it("goes to URL", () => {
const page = loadPage(URL);
equal(page.url, URL);
});
diff --git a/docs/src/content/docs/explainers/global-variables.mdx b/docs/src/content/docs/explainers/global-variables.mdx
index cb1b255a..d254f123 100644
--- a/docs/src/content/docs/explainers/global-variables.mdx
+++ b/docs/src/content/docs/explainers/global-variables.mdx
@@ -8,15 +8,15 @@ Related issue [#1582](https://github.com/mochajs/mocha/issues/1582)
If your test manipulates global variables, a reasonable expectation is that you will clean up after yourself. This includes commonly called methods such as `process.stdout.write()` or `console.log()`.
```js
-var expect = require("chai").expect;
+import { expect } from "chai";
describe("my nice test", function () {
- var write,
+ let write,
log,
output = "";
// restore process.stdout.write() and console.log() to their previous glory
- var cleanup = function () {
+ const cleanup = function () {
process.stdout.write = write;
console.log = log;
output = "";
diff --git a/docs/src/content/docs/explainers/nodejs-native-esm-support.mdx b/docs/src/content/docs/explainers/nodejs-native-esm-support.mdx
index bc4f6125..a7cf7056 100644
--- a/docs/src/content/docs/explainers/nodejs-native-esm-support.mdx
+++ b/docs/src/content/docs/explainers/nodejs-native-esm-support.mdx
@@ -12,7 +12,7 @@ For example:
```js
// test.mjs
import { add } from "./add.mjs";
-import assert from "assert";
+import assert from "node:assert";
it("should add to numbers from an es module", () => {
assert.equal(add(3, 5), 8);
diff --git a/docs/src/content/docs/explainers/programmatic-usage.mdx b/docs/src/content/docs/explainers/programmatic-usage.mdx
index d21faf5d..973282a2 100644
--- a/docs/src/content/docs/explainers/programmatic-usage.mdx
+++ b/docs/src/content/docs/explainers/programmatic-usage.mdx
@@ -8,20 +8,20 @@ There are a lot of reasons why you might want to automate running the tests usin
Here is an example of using Mocha programmatically:
```javascript
-var Mocha = require("mocha"),
- fs = require("fs"),
- path = require("path");
+import Mocha from "mocha";
+import fs from "node:fs";
+import path from "node:path";
// Instantiate a Mocha instance.
-var mocha = new Mocha();
+const mocha = new Mocha();
-var testDir = "some/dir/test";
+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.substr(-3) === ".js";
+ return file.endsWith(".js");
})
.forEach(function (file) {
mocha.addFile(path.join(testDir, file));
@@ -48,7 +48,7 @@ There are two ways to set the options to run the tests.
Firstly, you can set these options in the constructor object:
```javascript
-var mocha = new Mocha({
+const mocha = new Mocha({
ui: "tdd",
reporter: "list",
});
diff --git a/docs/src/content/docs/explainers/shared-behaviours.mdx b/docs/src/content/docs/explainers/shared-behaviours.mdx
index e95eaa79..ef670e96 100644
--- a/docs/src/content/docs/explainers/shared-behaviours.mdx
+++ b/docs/src/content/docs/explainers/shared-behaviours.mdx
@@ -8,7 +8,7 @@ Mocha currently has no concept of a "shared behaviour" however the "contexts" fa
shared.js:
```js
-exports.shouldBehaveLikeAUser = function () {
+export function shouldBehaveLikeAUser() {
it("should have .name.first", function () {
this.user.name.first.should.equal("tobi");
});
@@ -22,22 +22,21 @@ exports.shouldBehaveLikeAUser = function () {
this.user.fullname().should.equal("tobi holowaychuk");
});
});
-};
+}
```
test.js:
```js
-var User = require("./user").User,
- Admin = require("./user").Admin,
- shared = require("./shared");
+import { User, Admin } from "./user.js";
+import { shouldBehaveLikeAUser } from "./shared.js";
describe("User", function () {
beforeEach(function () {
this.user = new User("tobi", "holowaychuk");
});
- shared.shouldBehaveLikeAUser();
+ shouldBehaveLikeAUser();
});
describe("Admin", function () {
@@ -45,7 +44,7 @@ describe("Admin", function () {
this.user = new Admin("tobi", "holowaychuk");
});
- shared.shouldBehaveLikeAUser();
+ shouldBehaveLikeAUser();
it("should be an .admin", function () {
this.user.admin.should.be.true;
@@ -56,24 +55,23 @@ describe("Admin", function () {
user.js:
```js
-exports.User = User;
-exports.Admin = Admin;
-
-function User(first, last) {
- this.name = {
- first: first,
- last: last,
- };
+export class User {
+ constructor(first, last) {
+ this.name = {
+ first: first,
+ last: last,
+ };
+ }
+
+ fullname() {
+ return this.name.first + " " + this.name.last;
+ }
}
-User.prototype.fullname = function () {
- return this.name.first + " " + this.name.last;
-};
-
-function Admin(first, last) {
- User.call(this, first, last);
- this.admin = true;
+export class Admin extends User {
+ constructor(first, last) {
+ super(first, last);
+ this.admin = true;
+ }
}
-
-Admin.prototype.__proto__ = User.prototype;
```
diff --git a/docs/src/content/docs/explainers/spies.mdx b/docs/src/content/docs/explainers/spies.mdx
index 13ec9717..3ce5dabe 100644
--- a/docs/src/content/docs/explainers/spies.mdx
+++ b/docs/src/content/docs/explainers/spies.mdx
@@ -6,13 +6,13 @@ title: Spies
Mocha does not come equipped with spies, though libraries like [Sinon](https://github.com/sinonjs/sinon) provide this behaviour if desired. The following is an example of Mocha utilizing Sinon and [Should.js](https://github.com/shouldjs/should.js) to test an EventEmitter:
```javascript
-var sinon = require("sinon"),
- EventEmitter = require("events").EventEmitter;
+import sinon from "sinon";
+import { EventEmitter } from "node:events";
describe("EventEmitter", function () {
describe("#emit()", function () {
it("should invoke the callback", function () {
- var spy = sinon.spy(),
+ const spy = sinon.spy(),
emitter = new EventEmitter();
emitter.on("foo", spy);
@@ -21,7 +21,7 @@ describe("EventEmitter", function () {
});
it("should pass arguments to the callbacks", function () {
- var spy = sinon.spy(),
+ const spy = sinon.spy(),
emitter = new EventEmitter();
emitter.on("foo", spy);
@@ -39,14 +39,14 @@ The following is the same test, performed without any special spy library, utili
describe("EventEmitter", function () {
describe("#emit()", function () {
it("should invoke the callback", function (done) {
- var emitter = new EventEmitter();
+ const emitter = new EventEmitter();
emitter.on("foo", done);
emitter.emit("foo");
});
it("should pass arguments to the callbacks", function (done) {
- var emitter = new EventEmitter();
+ const emitter = new EventEmitter();
emitter.on("foo", function (a, b) {
a.should.equal("bar");
diff --git a/docs/src/content/docs/explainers/stub-stdout.mdx b/docs/src/content/docs/explainers/stub-stdout.mdx
index cfa9a2a1..2e36c67b 100644
--- a/docs/src/content/docs/explainers/stub-stdout.mdx
+++ b/docs/src/content/docs/explainers/stub-stdout.mdx
@@ -8,12 +8,12 @@ If you want to stub `stdout` inside your own code (via `process.stdout.write` or
i.e.
```javascript
-it('should do, but it do not', function() {
+it("should do, but it do not", function () {
// user wants to hide output generated by console.log calls in fn 'foo'
- console.log = function() {};
+ console.log = function () {};
foo();
- expect(...)
+ expect(...);
});
```
@@ -22,12 +22,12 @@ This will result in a faulty reporter output.
The correct way to handle this is to stub before and restore after the function call.
```javascript
-it('will do', function() {
- var consoleLogStub = sinon.stub(console, 'log');
+it("will do", function () {
+ const consoleLogStub = sinon.stub(console, "log");
foo();
consoleLogStub.restore();
- expect(...)
+ expect(...);
});
```
diff --git a/docs/src/content/docs/explainers/third-party-reporters.mdx b/docs/src/content/docs/explainers/third-party-reporters.mdx
index 7ecab677..29820f57 100644
--- a/docs/src/content/docs/explainers/third-party-reporters.mdx
+++ b/docs/src/content/docs/explainers/third-party-reporters.mdx
@@ -9,13 +9,12 @@ Here is a minimalistic sample reporter, which you can use by executing: `mocha -
```js
// my-reporter.js
-var mocha = require("mocha");
-module.exports = MyReporter;
+import mocha from "mocha";
-function MyReporter(runner) {
+export default function MyReporter(runner) {
mocha.reporters.Base.call(this, runner);
- var passes = 0;
- var failures = 0;
+ let passes = 0;
+ let failures = 0;
runner.on("pass", function (test) {
passes++;
diff --git a/docs/src/content/docs/explainers/third-party-uis.mdx b/docs/src/content/docs/explainers/third-party-uis.mdx
index 3ad304bb..c89431f5 100644
--- a/docs/src/content/docs/explainers/third-party-uis.mdx
+++ b/docs/src/content/docs/explainers/third-party-uis.mdx
@@ -109,7 +109,7 @@ function ExampleUI(suite) {
* attribute on a test to modify its presentation.
*/
context.comment = function (title) {
- var suite, comment;
+ let suite, comment;
suite = suites[0];
comment = new Test(title, null);
@@ -132,7 +132,7 @@ function ExampleUI(suite) {
* and/or tests.
*/
context.suite = function (title, fn) {
- var suite = Suite.create(suites[0], title);
+ const suite = Suite.create(suites[0], title);
suite.file = file;
suites.unshift(suite);
@@ -146,7 +146,7 @@ function ExampleUI(suite) {
* The default TDD pending suite functionality.
*/
context.suite.skip = function (title, fn) {
- var suite = Suite.create(suites[0], title);
+ const suite = Suite.create(suites[0], title);
suite.pending = true;
suites.unshift(suite);
@@ -158,7 +158,7 @@ function ExampleUI(suite) {
* Default TDD exclusive test-case logic.
*/
context.suite.only = function (title, fn) {
- var suite = context.suite(title, fn);
+ const suite = context.suite(title, fn);
mocha.grep(suite.fullTitle());
};
@@ -167,7 +167,7 @@ function ExampleUI(suite) {
* with the given `title` and callback `fn` acting as a thunk.
*/
context.test = function (title, fn) {
- var suite, test;
+ let suite, test;
suite = suites[0];
if (suite.pending) fn = null;
@@ -182,7 +182,7 @@ function ExampleUI(suite) {
* Exclusive test-case.
*/
context.test.only = function (title, fn) {
- var test, reString;
+ let test, reString;
test = context.test(title, fn);
reString = "^" + escapeStringRegexp(test.fullTitle()) + "$";
diff --git a/docs/src/content/docs/features/asynchronous-code.mdx b/docs/src/content/docs/features/asynchronous-code.mdx
index 83a95b41..767b21ce 100644
--- a/docs/src/content/docs/features/asynchronous-code.mdx
+++ b/docs/src/content/docs/features/asynchronous-code.mdx
@@ -10,7 +10,7 @@ This callback accepts both an `Error` instance _or_ a falsy value; anything else
describe("User", function () {
describe("#save()", function () {
it("should save without error", function (done) {
- var user = new User("Luna");
+ const user = new User("Luna");
user.save(function (err) {
if (err) done(err);
else done();
@@ -26,7 +26,7 @@ Alternatively, use the `done()` callback directly (which will handle an error ar
describe("User", function () {
describe("#save()", function () {
it("should save without error", function (done) {
- var user = new User("Luna");
+ const user = new User("Luna");
user.save(done);
});
});
@@ -59,7 +59,7 @@ The latter example uses [Chai as Promised](https://www.npmjs.com/package/chai-as
In Mocha v3.0.0 and newer, returning a `Promise` _and_ calling `done()` will result in an exception, as this is generally a mistake:
```js
-const assert = require("assert");
+import assert from "node:assert";
// antipattern
it("should complete this test", function (done) {
diff --git a/docs/src/content/docs/features/hooks.mdx b/docs/src/content/docs/features/hooks.mdx
index 2de1e438..f26f9e58 100644
--- a/docs/src/content/docs/features/hooks.mdx
+++ b/docs/src/content/docs/features/hooks.mdx
@@ -59,7 +59,7 @@ For example, you may wish to populate database with dummy content before each te
```js
describe("Connection", function () {
- var db = new Connection(),
+ const db = new Connection(),
tobi = new User("tobi"),
loki = new User("loki"),
jane = new User("jane");
@@ -103,7 +103,7 @@ With `--delay`, Mocha loads your test file and executes its top-level code as us
Place your `describe()` and `it()` calls inside the asynchronous code so that suites are registered after setup completes, then call `run()` to begin execution:
```js
-const assert = require("assert");
+import assert from "node:assert";
const fn = async (x) => {
return new Promise((resolve) => {
diff --git a/docs/src/content/docs/features/root-hook-plugins.mdx b/docs/src/content/docs/features/root-hook-plugins.mdx
index 824e5db2..5bfde72d 100644
--- a/docs/src/content/docs/features/root-hook-plugins.mdx
+++ b/docs/src/content/docs/features/root-hook-plugins.mdx
@@ -86,10 +86,12 @@ As with other hooks, `this` refers to the current context object:
```js
// test/hooks.mjs
+import os from "node:os";
+
export const mochaHooks = {
beforeAll() {
// skip all tests for bob
- if (require("os").userInfo().username === "bob") {
+ if (os.userInfo().username === "bob") {
return this.skip();
}
},
diff --git a/docs/src/content/docs/interfaces/require.mdx b/docs/src/content/docs/interfaces/require.mdx
index ecc4bd63..e25ff142 100644
--- a/docs/src/content/docs/interfaces/require.mdx
+++ b/docs/src/content/docs/interfaces/require.mdx
@@ -11,10 +11,8 @@ The `require` interface cannot be run via the `node` executable, and must be run
:::
```js
-var testCase = require("mocha").describe;
-var pre = require("mocha").before;
-var assertions = require("mocha").it;
-var assert = require("chai").assert;
+import { describe as testCase, before as pre, it as assertions } from "mocha";
+import { assert } from "chai";
testCase("Array", function () {
pre(function () {