Skip to content

armgit / mocha

Public Imported from GitHub
0

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

chore: applied formatting to all files (#5493)

Josh Goldberg ✨76d719495d09
diff --git a/.eleventy.js b/.eleventy.js
index 98d9faeb..8bf60513 100644
--- a/.eleventy.js
+++ b/.eleventy.js
@@ -1,58 +1,58 @@
-'use strict';
+"use strict";
module.exports = function (eleventyConfig) {
eleventyConfig.addPlugin(
- require('@11ty/eleventy-plugin-inclusive-language'),
+ require("@11ty/eleventy-plugin-inclusive-language"),
{
words:
- 'simply,obviously,basically,of course,clearly,everyone knows,however,easy'
- }
+ "simply,obviously,basically,of course,clearly,everyone knows,however,easy",
+ },
);
- eleventyConfig.addPassthroughCopy('docs/css');
- eleventyConfig.addPassthroughCopy('docs/js');
- eleventyConfig.addPassthroughCopy('docs/images');
- eleventyConfig.addPassthroughCopy('docs/CNAME');
- eleventyConfig.addPassthroughCopy('docs/_headers');
- eleventyConfig.addPassthroughCopy('docs/favicon.ico');
- eleventyConfig.addPassthroughCopy('docs/example');
- eleventyConfig.addPassthroughCopy('docs/api/images');
- eleventyConfig.addPassthroughCopy('docs/api/scripts');
- eleventyConfig.addPassthroughCopy('docs/api/styles');
+ eleventyConfig.addPassthroughCopy("docs/css");
+ eleventyConfig.addPassthroughCopy("docs/js");
+ eleventyConfig.addPassthroughCopy("docs/images");
+ eleventyConfig.addPassthroughCopy("docs/CNAME");
+ eleventyConfig.addPassthroughCopy("docs/_headers");
+ eleventyConfig.addPassthroughCopy("docs/favicon.ico");
+ eleventyConfig.addPassthroughCopy("docs/example");
+ eleventyConfig.addPassthroughCopy("docs/api/images");
+ eleventyConfig.addPassthroughCopy("docs/api/scripts");
+ eleventyConfig.addPassthroughCopy("docs/api/styles");
/* Markdown Plugins */
- const markdown = require('markdown-it')({
+ const markdown = require("markdown-it")({
html: true,
linkify: true,
- typographer: true
+ typographer: true,
});
- markdown.use(require('markdown-it-anchor'), {
- slugify: require('uslug'),
+ markdown.use(require("markdown-it-anchor"), {
+ slugify: require("uslug"),
permalink: true,
permalinkBefore: true,
- permalinkClass: 'direct-link',
- permalinkSymbol: '#'
+ permalinkClass: "direct-link",
+ permalinkSymbol: "#",
});
- markdown.use(require('markdown-it-attrs'), {
- leftDelimiter: '{:',
- rightDelimiter: '}'
+ markdown.use(require("markdown-it-attrs"), {
+ leftDelimiter: "{:",
+ rightDelimiter: "}",
});
- markdown.use(require('markdown-it-prism'));
+ markdown.use(require("markdown-it-prism"));
- markdown.use(require('markdown-it-emoji'));
+ markdown.use(require("markdown-it-emoji"));
- eleventyConfig.setLibrary('md', markdown);
+ eleventyConfig.setLibrary("md", markdown);
eleventyConfig.setUseGitIgnore(false);
return {
passthroughFileCopy: true,
dir: {
- input: 'docs',
- output: 'docs/_site'
- }
+ input: "docs",
+ output: "docs/_site",
+ },
};
};
diff --git a/.github/ISSUE_TEMPLATE/01-bug.yml b/.github/ISSUE_TEMPLATE/01-bug.yml
index b46ae9d9..d5f7037c 100644
--- a/.github/ISSUE_TEMPLATE/01-bug.yml
+++ b/.github/ISSUE_TEMPLATE/01-bug.yml
@@ -41,7 +41,7 @@ body:
type: textarea
description: Report a bug trying to run the code
labels:
- - 'status: in triage'
- - 'type: bug'
+ - "status: in triage"
+ - "type: bug"
name: 🐛 Bug
-title: '🐛 Bug: <short description of the bug>'
+title: "🐛 Bug: <short description of the bug>"
diff --git a/.github/ISSUE_TEMPLATE/02-documentation.yml b/.github/ISSUE_TEMPLATE/02-documentation.yml
index 0a98e59f..10ebdb54 100644
--- a/.github/ISSUE_TEMPLATE/02-documentation.yml
+++ b/.github/ISSUE_TEMPLATE/02-documentation.yml
@@ -21,7 +21,7 @@ body:
type: textarea
description: Report a typo or missing area of documentation
labels:
- - 'area: documentation'
- - 'status: in triage'
+ - "area: documentation"
+ - "status: in triage"
name: 📝 Docs
-title: '📝 Docs: <short description of the request>'
+title: "📝 Docs: <short description of the request>"
diff --git a/.github/ISSUE_TEMPLATE/03-feature-request.yml b/.github/ISSUE_TEMPLATE/03-feature-request.yml
index c3784396..5bb23234 100644
--- a/.github/ISSUE_TEMPLATE/03-feature-request.yml
+++ b/.github/ISSUE_TEMPLATE/03-feature-request.yml
@@ -33,7 +33,7 @@ body:
type: textarea
description: Request that a new feature be added or an existing feature improved
labels:
- - 'status: in triage'
- - 'type: feature'
+ - "status: in triage"
+ - "type: feature"
name: 🚀 Feature
-title: '🚀 Feature: <short description of the feature>'
+title: "🚀 Feature: <short description of the feature>"
diff --git a/.github/ISSUE_TEMPLATE/04-performance.yml b/.github/ISSUE_TEMPLATE/04-performance.yml
index 590508cf..d4d27cbd 100644
--- a/.github/ISSUE_TEMPLATE/04-performance.yml
+++ b/.github/ISSUE_TEMPLATE/04-performance.yml
@@ -45,7 +45,7 @@ body:
type: textarea
description: Suggest a way to make Mocha faster, more memory- and/or space-efficient, or otherwise improve performance
labels:
- - 'area: performance'
- - 'status: in triage'
+ - "area: performance"
+ - "status: in triage"
name: ⚡️ Performance
-title: '⚡️ Performance: <short description of the change>'
+title: "⚡️ Performance: <short description of the change>"
diff --git a/.github/ISSUE_TEMPLATE/05-repository-tooling.yml b/.github/ISSUE_TEMPLATE/05-repository-tooling.yml
index 7e6c6a57..0337126e 100644
--- a/.github/ISSUE_TEMPLATE/05-repository-tooling.yml
+++ b/.github/ISSUE_TEMPLATE/05-repository-tooling.yml
@@ -25,7 +25,7 @@ body:
type: textarea
description: Report a bug or request an enhancement in the Mocha repository's internal tooling
labels:
- - 'area: repository tooling'
- - 'status: in triage'
+ - "area: repository tooling"
+ - "status: in triage"
name: 🛠 Repository Tooling
-title: '🛠 Repo: <short description of the change>'
+title: "🛠 Repo: <short description of the change>"
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index 7220d994..f6faee69 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -1,10 +1,10 @@
version: 2
updates:
- - package-ecosystem: 'github-actions'
- directory: '/'
+ - package-ecosystem: "github-actions"
+ directory: "/"
schedule:
- interval: 'weekly'
+ interval: "weekly"
groups:
github-actions:
patterns:
- - '*'
+ - "*"
diff --git a/.github/release-please/manifest.json b/.github/release-please/manifest.json
index e4b29476..8d590b79 100644
--- a/.github/release-please/manifest.json
+++ b/.github/release-please/manifest.json
@@ -1 +1 @@
-{".":"11.7.4"}
+{ ".": "11.7.4" }
diff --git a/.github/workflows/browser-test.yml b/.github/workflows/browser-test.yml
index 9e7db64e..6d2aa56f 100644
--- a/.github/workflows/browser-test.yml
+++ b/.github/workflows/browser-test.yml
@@ -11,7 +11,7 @@ permissions:
jobs:
test-browser:
- name: 'Browser Tests'
+ name: "Browser Tests"
if: contains(github.event.pull_request.labels.*.name, 'run-browser-test')
uses: ./.github/workflows/npm-script.yml
secrets: inherit
diff --git a/.github/workflows/mocha.yml b/.github/workflows/mocha.yml
index 3ed66966..e7fa179e 100644
--- a/.github/workflows/mocha.yml
+++ b/.github/workflows/mocha.yml
@@ -4,11 +4,11 @@ on:
push:
branches:
- main
- paths-ignore: ['*.md', 'docs/**']
+ paths-ignore: ["*.md", "docs/**"]
pull_request:
branches:
- main
- paths-ignore: ['*.md', 'docs/**']
+ paths-ignore: ["*.md", "docs/**"]
workflow_dispatch:
permissions:
@@ -16,6 +16,11 @@ permissions:
id-token: write # for Codecov OIDC
jobs:
+ format:
+ uses: ./.github/workflows/npm-script.yml
+ with:
+ npm-script: format
+
lint:
uses: ./.github/workflows/npm-script.yml
with:
@@ -24,7 +29,7 @@ jobs:
smoke:
uses: ./.github/workflows/npm-script.yml
with:
- node-versions: '20,22,24'
+ node-versions: "20,22,24"
npm-script: test-smoke
test-node-lts:
@@ -68,10 +73,10 @@ jobs:
- test-part: jsapi
coverage: false
with:
- os: 'ubuntu-latest,windows-latest'
+ os: "ubuntu-latest,windows-latest"
# We pin exact versions here per https://github.com/mochajs/mocha/issues/5052
# Ref https://nodejs.org/en/about/previous-releases
- node-versions: '20.19.4,22.18.0,24.6.0'
+ node-versions: "20.19.4,22.18.0,24.6.0"
npm-script: test-node:${{ matrix.test-part }}
coverage: ${{ matrix.coverage }}
diff --git a/.github/workflows/nightly-site-deploy.yml b/.github/workflows/nightly-site-deploy.yml
index 217ca78e..6e4e5de9 100644
--- a/.github/workflows/nightly-site-deploy.yml
+++ b/.github/workflows/nightly-site-deploy.yml
@@ -6,7 +6,7 @@ name: Nightly mochajs.org Deploy
on:
schedule:
- - cron: '0 0 * * *'
+ - cron: "0 0 * * *"
permissions:
contents: read
@@ -18,5 +18,5 @@ jobs:
- name: Webhook Action
uses: joelwmale/webhook-action@cc1a66f987e1591785273fd6f9d2f7a9d8d7c9cd
env:
- data: ''
+ data: ""
WEBHOOK_URL: ${{ secrets.NETLIFY_NIGHTLY_DEPLOY_URL }}
diff --git a/.github/workflows/npm-script.yml b/.github/workflows/npm-script.yml
index 0b862130..16150537 100644
--- a/.github/workflows/npm-script.yml
+++ b/.github/workflows/npm-script.yml
@@ -4,23 +4,23 @@ on:
workflow_call:
inputs:
npm-script:
- description: 'npm script'
+ description: "npm script"
required: true
type: string
browsers:
- description: 'A comma separated list of browser names to test with.'
+ description: "A comma separated list of browser names to test with."
required: false
type: string
node-versions:
- description: 'A comma separated list of Node versions to test with.'
+ description: "A comma separated list of Node versions to test with."
required: false
type: string
os:
- description: 'A comma separated list of operating systems to test on.'
+ description: "A comma separated list of operating systems to test on."
required: false
type: string
coverage:
- description: 'Whether to set up coverage reporting or not'
+ description: "Whether to set up coverage reporting or not"
required: false
type: boolean
@@ -65,13 +65,13 @@ jobs:
- uses: actions/setup-node@v5
with:
node-version: ${{ matrix.node_version }}
- cache: 'npm'
+ cache: "npm"
- run: npm ci --ignore-scripts
- run: npm run ${{ inputs.npm-script }}
env:
BROWSER: ${{ matrix.browser }}
COVERAGE: ${{ inputs.coverage && '1'}}
- NODE_OPTIONS: '--trace-warnings'
+ NODE_OPTIONS: "--trace-warnings"
SAUCE_USERNAME: ${{ secrets.SAUCE_USERNAME }}
SAUCE_ACCESS_KEY: ${{ secrets.SAUCE_ACCESS_KEY }}
# Generate and upload coverage, even if tests fail
@@ -86,4 +86,3 @@ jobs:
with:
fail_ci_if_error: true
use_oidc: true
-
diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml
index d23f9b57..e1eb7dad 100644
--- a/.github/workflows/release-please.yml
+++ b/.github/workflows/release-please.yml
@@ -39,8 +39,8 @@ jobs:
- uses: actions/setup-node@v5
with:
# The 22.11.0 is instead of lts per https://github.com/mochajs/mocha/issues/5278
- node-version: '22.11.0'
- registry-url: 'https://registry.npmjs.org'
+ node-version: "22.11.0"
+ registry-url: "https://registry.npmjs.org"
- name: Install dependencies
run: npm ci --ignore-scripts --force --no-fund --no-audit
diff --git a/.knip.jsonc b/.knip.jsonc
index 4238fd49..ca5b835f 100644
--- a/.knip.jsonc
+++ b/.knip.jsonc
@@ -5,12 +5,12 @@
"bin/_mocha!",
"browser-entry.js!",
"index.js!",
- "lib/cli/index.js!"
+ "lib/cli/index.js!",
],
"project": ["{bin,lib,scripts,test}/**/*.{js,ts,mjs,cjs}"],
"ignore": [
"test/integration/fixtures/esm/type-module/test-that-imports-non-existing-module.fixture.js",
- "test/integration/fixtures/options/watch/test-with-dependency.fixture.js"
+ "test/integration/fixtures/options/watch/test-with-dependency.fixture.js",
],
"ignoreDependencies": [
"@mocha/docdash",
@@ -18,15 +18,15 @@
"coffeescript",
"fake",
"jsdoc-ts-utils",
- "non-existent-package"
+ "non-existent-package",
],
"mocha": {
- "entry": ["test/**/*.{js,ts,mjs,cjs}"]
+ "entry": ["test/**/*.{js,ts,mjs,cjs}"],
},
"webpack": {
- "config": "test/browser-specific/fixtures/webpack/webpack.config.js"
+ "config": "test/browser-specific/fixtures/webpack/webpack.config.js",
},
"rules": {
- "exports": "off"
- }
+ "exports": "off",
+ },
}
diff --git a/.mocharc.yml b/.mocharc.yml
index 5f788099..dda702d0 100644
--- a/.mocharc.yml
+++ b/.mocharc.yml
@@ -1,13 +1,13 @@
-require: 'test/setup'
-ui: 'bdd'
+require: "test/setup"
+ui: "bdd"
global:
- - 'okGlobalA,okGlobalB'
- - 'okGlobalC'
- - 'callback*'
+ - "okGlobalA,okGlobalB"
+ - "okGlobalC"
+ - "callback*"
timeout: 1000
watch-ignore:
- - '.*'
- - 'docs/_site/**'
- - 'node_modules'
- - 'coverage'
- - 'cache'
+ - ".*"
+ - "docs/_site/**"
+ - "node_modules"
+ - "coverage"
+ - "cache"
diff --git a/.nycrc b/.nycrc
index aac56b80..d81951ae 100644
--- a/.nycrc
+++ b/.nycrc
@@ -1,8 +1,5 @@
{
- "reporter": [
- "json",
- "text-summary"
- ],
+ "reporter": ["json", "text-summary"],
"exclude": [
"coverage/**",
"docs/**",
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 00000000..6b59af95
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1,11 @@
+/.karma/
+/.nyc_output
+/CHANGELOG.md
+/coverage
+/docs/_site/
+/docs/api/
+/docs/css/normalize.css
+/docs/css/prism.css
+/docs/js/
+/pnpm-lock.yaml
+/test/*/fixtures/**
diff --git a/.wallaby.js b/.wallaby.js
index 9d5d4bf5..a9692061 100644
--- a/.wallaby.js
+++ b/.wallaby.js
@@ -1,54 +1,54 @@
-'use strict';
+"use strict";
module.exports = () => {
return {
files: [
- 'index.js',
- 'lib/**/*.{js,json}',
- 'test/setup.js',
- 'test/assertions.js',
+ "index.js",
+ "lib/**/*.{js,json}",
+ "test/setup.js",
+ "test/assertions.js",
{
- pattern: 'test/node-unit/**/*.fixture.js',
- instrument: false
+ pattern: "test/node-unit/**/*.fixture.js",
+ instrument: false,
},
{
- pattern: 'test/unit/**/*.fixture.js',
- instrument: false
+ pattern: "test/unit/**/*.fixture.js",
+ instrument: false,
},
- 'package.json',
- 'mocharc.yml',
- '!lib/browser/growl.js'
+ "package.json",
+ "mocharc.yml",
+ "!lib/browser/growl.js",
],
filesWithNoCoverageCalculated: [
- 'test/**/*.fixture.js',
- 'test/setup.js',
- 'test/assertions.js',
- 'lib/browser/**/*.js'
+ "test/**/*.fixture.js",
+ "test/setup.js",
+ "test/assertions.js",
+ "lib/browser/**/*.js",
],
- tests: ['test/unit/**/*.spec.js', 'test/node-unit/**/*.spec.js'],
+ tests: ["test/unit/**/*.spec.js", "test/node-unit/**/*.spec.js"],
env: {
- type: 'node',
- runner: 'node'
+ type: "node",
+ runner: "node",
},
- workers: {recycle: true},
- testFramework: {type: 'mocha', path: __dirname},
+ workers: { recycle: true },
+ testFramework: { type: "mocha", path: __dirname },
setup(wallaby) {
// running mocha instance is not the same as mocha under test,
// running mocha is the project's source code mocha, mocha under test is instrumented version of the source code
const runningMocha = wallaby.testFramework;
runningMocha.timeout(1000);
// to expose it/describe etc. on the mocha under test
- const MochaUnderTest = require('./');
+ const MochaUnderTest = require("./");
const mochaUnderTest = new MochaUnderTest();
mochaUnderTest.suite.emit(
MochaUnderTest.Suite.constants.EVENT_FILE_PRE_REQUIRE,
global,
- '',
- mochaUnderTest
+ "",
+ mochaUnderTest,
);
- require('./test/setup');
+ require("./test/setup");
},
debug: true,
- runMode: 'onsave'
+ runMode: "onsave",
};
};
diff --git a/FUNDING.md b/FUNDING.md
index 2a7c2417..23a45920 100644
--- a/FUNDING.md
+++ b/FUNDING.md
@@ -4,8 +4,8 @@ This project follows [Collective Funds Guidelines 0.1](https://github.com/collec
## Rates
-* TSC Members: $75.00 USD/hour
-* Project Contributors: $50.00 USD/hour
+- TSC Members: $75.00 USD/hour
+- Project Contributors: $50.00 USD/hour
## Additional notes
diff --git a/bin/_mocha b/bin/_mocha
index 2ea83174..9572d94c 100755
--- a/bin/_mocha
+++ b/bin/_mocha
@@ -1,5 +1,5 @@
#!/usr/bin/env node
-'use strict';
+"use strict";
/**
* This file remains for backwards compatibility only.
@@ -7,4 +7,4 @@
* @see module:lib/cli
*/
-require('../lib/cli').main();
+require("../lib/cli").main();
diff --git a/bin/mocha.js b/bin/mocha.js
index d6359cd3..01a97232 100755
--- a/bin/mocha.js
+++ b/bin/mocha.js
@@ -1,6 +1,6 @@
#!/usr/bin/env node
-'use strict';
+"use strict";
/**
* This wrapper executable checks for known node flags and appends them when found,
@@ -10,16 +10,16 @@
* @private
*/
-const os = require('node:os');
-const {loadOptions} = require('../lib/cli/options');
+const os = require("node:os");
+const { loadOptions } = require("../lib/cli/options");
const {
unparseNodeFlags,
isNodeFlag,
- impliesNoTimeouts
-} = require('../lib/cli/node-flags');
-const unparse = require('yargs-unparser');
-const debug = require('debug')('mocha:cli:mocha');
-const {aliases} = require('../lib/cli/run-option-metadata');
+ impliesNoTimeouts,
+} = require("../lib/cli/node-flags");
+const unparse = require("yargs-unparser");
+const debug = require("debug")("mocha:cli:mocha");
+const { aliases } = require("../lib/cli/run-option-metadata");
const mochaArgs = {};
const nodeArgs = {};
@@ -27,16 +27,16 @@ const SIGNAL_OFFSET = 128;
let hasInspect = false;
const opts = loadOptions(process.argv.slice(2));
-debug('loaded opts', opts);
+debug("loaded opts", opts);
/**
* Given option/command `value`, disable timeouts if applicable
* @param {string} [value] - Value to check
* @ignore
*/
-const disableTimeouts = value => {
+const disableTimeouts = (value) => {
if (impliesNoTimeouts(value)) {
- debug('option %s disabled timeouts', value);
+ debug("option %s disabled timeouts", value);
mochaArgs.timeout = 0;
}
};
@@ -47,11 +47,11 @@ const disableTimeouts = value => {
* @returns {string} `value` with prefix (maybe) removed
* @ignore
*/
-const trimV8Option = value =>
- value !== 'v8-options' && /^v8-/.test(value) ? value.slice(3) : value;
+const trimV8Option = (value) =>
+ value !== "v8-options" && /^v8-/.test(value) ? value.slice(3) : value;
// sort options into "node" and "mocha" buckets
-Object.keys(opts).forEach(opt => {
+Object.keys(opts).forEach((opt) => {
if (isNodeFlag(opt)) {
nodeArgs[trimV8Option(opt)] = opts[opt];
} else {
@@ -60,9 +60,9 @@ Object.keys(opts).forEach(opt => {
});
// disable 'timeout' for debugFlags
-Object.keys(nodeArgs).forEach(opt => disableTimeouts(opt));
-mochaArgs['node-option'] &&
- mochaArgs['node-option'].forEach(opt => disableTimeouts(opt));
+Object.keys(nodeArgs).forEach((opt) => disableTimeouts(opt));
+mochaArgs["node-option"] &&
+ mochaArgs["node-option"].forEach((opt) => disableTimeouts(opt));
// Native debugger handling
// see https://nodejs.org/api/debugger.html#debugger_debugger
@@ -71,78 +71,80 @@ mochaArgs['node-option'] &&
// A deprecation warning will be printed by node, if applicable.
// (mochaArgs._ are "positional" arguments, not prefixed with - or --)
if (mochaArgs._) {
- const i = mochaArgs._.findIndex(val => val === 'inspect');
+ const i = mochaArgs._.findIndex((val) => val === "inspect");
if (i > -1) {
mochaArgs._.splice(i, 1);
- disableTimeouts('inspect');
+ disableTimeouts("inspect");
hasInspect = true;
}
}
-if (mochaArgs['node-option'] || Object.keys(nodeArgs).length || hasInspect) {
- const {spawn} = require('node:child_process');
- const mochaPath = require.resolve('../lib/cli/cli.js');
+if (mochaArgs["node-option"] || Object.keys(nodeArgs).length || hasInspect) {
+ const { spawn } = require("node:child_process");
+ const mochaPath = require.resolve("../lib/cli/cli.js");
const nodeArgv =
- (mochaArgs['node-option'] && mochaArgs['node-option'].map(v => '--' + v)) ||
+ (mochaArgs["node-option"] &&
+ mochaArgs["node-option"].map((v) => "--" + v)) ||
unparseNodeFlags(nodeArgs);
- if (hasInspect) nodeArgv.unshift('inspect');
- delete mochaArgs['node-option'];
+ if (hasInspect) nodeArgv.unshift("inspect");
+ delete mochaArgs["node-option"];
- debug('final node argv', nodeArgv);
+ debug("final node argv", nodeArgv);
const args = [].concat(
nodeArgv,
mochaPath,
- unparse(mochaArgs, {alias: aliases})
+ unparse(mochaArgs, { alias: aliases }),
);
debug(
- 'forking child process via command: %s %s',
+ "forking child process via command: %s %s",
process.execPath,
- args.join(' ')
+ args.join(" "),
);
const proc = spawn(process.execPath, args, {
- stdio: 'inherit'
+ stdio: "inherit",
});
- proc.on('exit', (code, signal) => {
- process.on('exit', () => {
+ proc.on("exit", (code, signal) => {
+ process.on("exit", () => {
if (signal) {
- signal = typeof signal === 'string' ? os.constants.signals[signal] : signal;
- if (mochaArgs['posix-exit-codes'] === true) {
+ signal =
+ typeof signal === "string" ? os.constants.signals[signal] : signal;
+ if (mochaArgs["posix-exit-codes"] === true) {
process.exitCode = SIGNAL_OFFSET + signal;
}
process.kill(process.pid, signal);
} else {
- process.exit(Math.min(code, mochaArgs['posix-exit-codes'] ? 1 : 255));
+ process.exit(Math.min(code, mochaArgs["posix-exit-codes"] ? 1 : 255));
}
});
});
// terminate children.
- process.on('SIGINT', () => {
+ process.on("SIGINT", () => {
// XXX: a previous comment said this would abort the runner, but I can't see that it does
// anything with the default runner.
- debug('main process caught SIGINT');
- proc.kill('SIGINT');
+ debug("main process caught SIGINT");
+ proc.kill("SIGINT");
// if running in parallel mode, we will have a proper SIGINT handler, so the below won't
// be needed.
if (!args.parallel || args.jobs < 2) {
// win32 does not support SIGTERM, so use next best thing.
- if (os.platform() === 'win32') {
- proc.kill('SIGKILL');
+ if (os.platform() === "win32") {
+ proc.kill("SIGKILL");
} else {
// using SIGKILL won't cleanly close the output streams, which can result
// in cut-off text or a befouled terminal.
- debug('sending SIGTERM to child process');
- proc.kill('SIGTERM');
+ debug("sending SIGTERM to child process");
+ proc.kill("SIGTERM");
}
}
});
} else {
- debug('running Mocha in-process');
- require('../lib/cli/cli').main([], mochaArgs);
+ debug("running Mocha in-process");
+ require("../lib/cli/cli").main([], mochaArgs);
}
diff --git a/browser-entry.js b/browser-entry.js
index e8a848aa..3c40c5d7 100644
--- a/browser-entry.js
+++ b/browser-entry.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/* eslint no-unused-vars: off */
/* eslint-env commonjs */
@@ -7,11 +7,11 @@
* Shim process.stdout.
*/
-process.stdout = require('browser-stdout')({label: false});
+process.stdout = require("browser-stdout")({ label: false });
-var parseQuery = require('./lib/browser/parse-query');
-var highlightTags = require('./lib/browser/highlight-tags');
-var Mocha = require('./lib/mocha');
+var parseQuery = require("./lib/browser/parse-query");
+var highlightTags = require("./lib/browser/highlight-tags");
+var Mocha = require("./lib/mocha");
/**
* Create a Mocha instance.
@@ -19,7 +19,7 @@ var Mocha = require('./lib/mocha');
* @return {undefined}
*/
-var mocha = new Mocha({reporter: 'html'});
+var mocha = new Mocha({ reporter: "html" });
/**
* Save timer references to avoid Sinon interfering (see GH-237).
@@ -41,7 +41,7 @@ var originalOnerrorHandler = global.onerror;
*/
process.removeListener = function (e, fn) {
- if (e === 'uncaughtException') {
+ if (e === "uncaughtException") {
if (originalOnerrorHandler) {
global.onerror = originalOnerrorHandler;
} else {
@@ -59,7 +59,7 @@ process.removeListener = function (e, fn) {
*/
process.listenerCount = function (name) {
- if (name === 'uncaughtException') {
+ if (name === "uncaughtException") {
return uncaughtExceptionHandlers.length;
}
return 0;
@@ -70,9 +70,9 @@ process.listenerCount = function (name) {
*/
process.on = function (e, fn) {
- if (e === 'uncaughtException') {
+ if (e === "uncaughtException") {
global.onerror = function (msg, url, line, col, err) {
- fn(err || new Error(msg + ' (' + url + ':' + line + ':' + col + ')'));
+ fn(err || new Error(msg + " (" + url + ":" + line + ":" + col + ")"));
return !mocha.options.allowUncaught;
};
uncaughtExceptionHandlers.push(fn);
@@ -80,7 +80,7 @@ process.on = function (e, fn) {
};
process.listeners = function (err) {
- if (err === 'uncaughtException') {
+ if (err === "uncaughtException") {
return uncaughtExceptionHandlers;
}
return [];
@@ -89,7 +89,7 @@ process.listeners = function (err) {
// The BDD UI is registered by default, but no UI will be functional in the
// browser without an explicit call to the overridden `mocha.ui` (see below).
// Ensure that this default UI does not expose its methods to the global scope.
-mocha.suite.removeAllListeners('pre-require');
+mocha.suite.removeAllListeners("pre-require");
var immediateQueue = [];
var immediateTimeout;
@@ -136,7 +136,7 @@ mocha.throwError = function (err) {
mocha.ui = function (ui) {
Mocha.prototype.ui.call(this, ui);
- this.suite.emit('pre-require', global, null, this);
+ this.suite.emit("pre-require", global, null, this);
return this;
};
@@ -145,8 +145,8 @@ mocha.ui = function (ui) {
*/
mocha.setup = function (opts) {
- if (typeof opts === 'string') {
- opts = {ui: opts};
+ if (typeof opts === "string") {
+ opts = { ui: opts };
}
if (opts.delay === true) {
this.delay();
@@ -154,7 +154,7 @@ mocha.setup = function (opts) {
var self = this;
Object.keys(opts)
.filter(function (opt) {
- return opt !== 'delay';
+ return opt !== "delay";
})
.forEach(function (opt) {
if (Object.prototype.hasOwnProperty.call(opts, opt)) {
@@ -170,9 +170,9 @@ mocha.setup = function (opts) {
mocha.run = function (fn) {
var options = mocha.options;
- mocha.globals('location');
+ mocha.globals("location");
- var query = parseQuery(global.location.search || '');
+ var query = parseQuery(global.location.search || "");
if (query.grep) {
mocha.grep(query.grep);
}
@@ -188,10 +188,10 @@ mocha.run = function (fn) {
var document = global.document;
if (
document &&
- document.getElementById('mocha') &&
+ document.getElementById("mocha") &&
options.noHighlighting !== true
) {
- highlightTags('code');
+ highlightTags("code");
}
if (fn) {
fn(err);
diff --git a/docs-next/public/example/Array.js b/docs-next/public/example/Array.js
index 38cbe39f..cc9ab7da 100644
--- a/docs-next/public/example/Array.js
+++ b/docs-next/public/example/Array.js
@@ -1,75 +1,74 @@
"use strict";
-describe('Array', function () {
- describe('.push()', function () {
- it('should append a value', function () {
+describe("Array", function () {
+ describe(".push()", function () {
+ it("should append a value", function () {
var arr = [];
- arr.push('foo');
- arr.push('bar');
- expect(arr[0]).to.equal('foo');
- expect(arr[1]).to.equal('bar');
- })
+ arr.push("foo");
+ arr.push("bar");
+ expect(arr[0]).to.equal("foo");
+ expect(arr[1]).to.equal("bar");
+ });
- it('should return the length', function () {
+ it("should return the length", function () {
var arr = [];
- var n = arr.push('foo');
+ var n = arr.push("foo");
expect(n).to.equal(1);
- n = arr.push('bar');
+ n = arr.push("bar");
expect(n).to.equal(2);
- })
+ });
- describe('with many arguments', function () {
- it('should add the values', function () {
+ describe("with many arguments", function () {
+ it("should add the values", function () {
var arr = [];
- arr.push('foo', 'bar');
- expect(arr[0]).to.equal('foo');
- expect(arr[1]).to.equal('bar');
- })
- })
- })
+ arr.push("foo", "bar");
+ expect(arr[0]).to.equal("foo");
+ expect(arr[1]).to.equal("bar");
+ });
+ });
+ });
- describe('.unshift()', function () {
- it('should prepend a value', function () {
+ describe(".unshift()", function () {
+ it("should prepend a value", function () {
var arr = [1, 2, 3];
- arr.unshift('foo');
- expect(arr[0]).to.equal('foo');
+ arr.unshift("foo");
+ expect(arr[0]).to.equal("foo");
expect(arr[1]).to.equal(1);
- })
+ });
- it('should return the length', function () {
+ it("should return the length", function () {
var arr = [];
- var n = arr.unshift('foo');
+ var n = arr.unshift("foo");
expect(n).to.equal(1);
- n = arr.unshift('bar');
+ n = arr.unshift("bar");
expect(n).to.equal(2);
- })
+ });
- describe('with many arguments', function () {
- it('should add the values', function () {
+ describe("with many arguments", function () {
+ it("should add the values", function () {
var arr = [];
- arr.unshift('foo', 'bar');
- expect(arr[0]).to.equal('foo');
- expect(arr[1]).to.equal('bar');
- })
- })
- })
+ arr.unshift("foo", "bar");
+ expect(arr[0]).to.equal("foo");
+ expect(arr[1]).to.equal("bar");
+ });
+ });
+ });
- describe('.pop()', function () {
- it('should remove and return the last value', function () {
+ describe(".pop()", function () {
+ it("should remove and return the last value", function () {
var arr = [1, 2, 3];
expect(arr.pop()).to.equal(3);
expect(arr.pop()).to.equal(2);
expect(arr).to.have.length(1);
- })
- })
+ });
+ });
- describe('.shift()', function () {
- it('should remove and return the first value', function () {
+ describe(".shift()", function () {
+ it("should remove and return the first value", function () {
var arr = [1, 2, 3];
expect(arr.shift()).to.equal(1);
expect(arr.shift()).to.equal(2);
expect(arr).to.have.length(1);
- })
- })
-})
-
+ });
+ });
+});
diff --git a/docs-next/public/example/tests.html b/docs-next/public/example/tests.html
index d52f87c0..ae144b3f 100644
--- a/docs-next/public/example/tests.html
+++ b/docs-next/public/example/tests.html
@@ -1,17 +1,21 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
- <meta charset="utf-8">
+ <meta charset="utf-8" />
<title>Mocha</title>
- <link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css">
- <link rel="shortcut icon" href="../favicon.svg">
+ <link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
+ <link rel="shortcut icon" href="../favicon.svg" />
</head>
<body>
<div id="mocha"></div>
<script src="https://unpkg.com/mocha/mocha.js"></script>
<script src="https://unpkg.com/[email protected]/chai.js"></script>
- <script>mocha.setup('bdd')</script>
- <script>expect = chai.expect</script>
+ <script>
+ mocha.setup("bdd");
+ </script>
+ <script>
+ expect = chai.expect;
+ </script>
<script src="Array.js"></script>
<script>
mocha.run();
diff --git a/docs-next/src/content/docs/explainers/compilers-deprecation.mdx b/docs-next/src/content/docs/explainers/compilers-deprecation.mdx
index e846ca1a..8ec30b90 100644
--- a/docs-next/src/content/docs/explainers/compilers-deprecation.mdx
+++ b/docs-next/src/content/docs/explainers/compilers-deprecation.mdx
@@ -3,15 +3,15 @@ description: Compilers deprecation notice.
title: Compilers deprecation
---
-If you're here, you probably hit the deprecation notice. Sorry about that!
+If you're here, you probably hit the deprecation notice. Sorry about that!
## Will it break?
-This is a *soft* deprecation, which means you get nagged about it, but it won't break (yet).
+This is a _soft_ deprecation, which means you get nagged about it, but it won't break (yet).
## Make it go away
-To suppress this warning, execute `mocha` with the `--no-deprecation` flag (though you won't get notice of any *other* deprecations you may encounter either).
+To suppress this warning, execute `mocha` with the `--no-deprecation` flag (though you won't get notice of any _other_ deprecations you may encounter either).
## ... but why?
@@ -21,7 +21,7 @@ To suppress this warning, execute `mocha` with the `--no-deprecation` flag (thou
Let's say you want to compile using CoffeeScript. Ensure that you have the coffeescript package installed as a dev dependency:
-```npm install coffeescript --save-dev```
+`npm install coffeescript --save-dev`
Then update your package.json with the relevant require statement: `--require coffeescript/register`.
@@ -34,7 +34,7 @@ Here's a list of popular compilers/transpilers:
- LiveScript: `--compilers ls:livescript` becomes `--require livescript`
- (feel free to add more examples!)
-You'll have to handle file extensions as well. Mocha, by default, only loads `.js` files when given a directory (and the default directory is `test`). Therefore, to use a *different* file extension (such as `.coffee` or `.ts`), you will need to supply a *glob* instead of simply a directory. If this was how you ran Mocha pre-v4:
+You'll have to handle file extensions as well. Mocha, by default, only loads `.js` files when given a directory (and the default directory is `test`). Therefore, to use a _different_ file extension (such as `.coffee` or `.ts`), you will need to supply a _glob_ instead of simply a directory. If this was how you ran Mocha pre-v4:
```bash
$ mocha --compilers coffee:coffee-script/register --recursive ./test
@@ -47,9 +47,9 @@ $ mocha --require coffeescript/register "test/**/*.js"
```
When you wrap a glob in quotes, file discovery is handed to the [glob](https://npm.im/glob) package.
- It's *recommended* to wrap in double-quotes, because the result should be the same regardless of your shell or environment (Windows/Linux/macOS, etc.).
+It's _recommended_ to wrap in double-quotes, because the result should be the same regardless of your shell or environment (Windows/Linux/macOS, etc.).
-[glob](https://npm.im/glob) is powerful. For instance, if your `test` dir has tests written in *both* JS *and* CoffeeScript, you could do this:
+[glob](https://npm.im/glob) is powerful. For instance, if your `test` dir has tests written in _both_ JS _and_ CoffeeScript, you could do this:
```bash
$ mocha --require coffeescript/register "test/**/*.{js,coffee}"
@@ -62,4 +62,3 @@ When using `--watch`, you will also need to specify the extension(s) to watch vi
```js
$ mocha --require coffeescript/register --watch --watch-extensions js,coffee "test/**/*.{js,coffee}"
```
-
diff --git a/docs-next/src/content/docs/explainers/count-assertions.mdx b/docs-next/src/content/docs/explainers/count-assertions.mdx
index 638be4e6..8ceaa6d5 100644
--- a/docs-next/src/content/docs/explainers/count-assertions.mdx
+++ b/docs-next/src/content/docs/explainers/count-assertions.mdx
@@ -10,7 +10,7 @@ var expected = 0;
var actual = 0;
function assert(expr, msg) {
- if (!expr) throw new Error(msg || 'assertion failed');
+ if (!expr) throw new Error(msg || "assertion failed");
actual++;
}
@@ -25,23 +25,23 @@ function reset() {
function check() {
if (!expected || expected == actual) return;
- var err = new Error('expected ' + expected + ' assertions, got ' + actual);
- this.currentTest.emit('error', err);
+ var err = new Error("expected " + expected + " assertions, got " + actual);
+ this.currentTest.emit("error", err);
}
beforeEach(reset);
afterEach(check);
-describe('something', function () {
- it('should work', function (done) {
+describe("something", function () {
+ it("should work", function (done) {
expect(2);
setTimeout(function () {
- assert('wahoo');
+ assert("wahoo");
}, 50);
setTimeout(function () {
- assert('hey');
+ assert("hey");
}, 50);
setTimeout(function () {
diff --git a/docs-next/src/content/docs/explainers/find-global-leaks.mdx b/docs-next/src/content/docs/explainers/find-global-leaks.mdx
index b05f9596..87e5201b 100644
--- a/docs-next/src/content/docs/explainers/find-global-leaks.mdx
+++ b/docs-next/src/content/docs/explainers/find-global-leaks.mdx
@@ -6,10 +6,10 @@ title: Find global leaks
Detecting which module is causing a global leak can be tedious. Add these lines at the very beginning of your tests, or in a file which is included via `--require`:
```javascript
-Object.defineProperty(global, 'name_of_leaking_property', {
+Object.defineProperty(global, "name_of_leaking_property", {
set: function (value) {
- throw new Error('Found the leak!');
- }
+ throw new Error("Found the leak!");
+ },
});
```
diff --git a/docs-next/src/content/docs/explainers/shared-behaviours.mdx b/docs-next/src/content/docs/explainers/shared-behaviours.mdx
index fde18337..e95eaa79 100644
--- a/docs-next/src/content/docs/explainers/shared-behaviours.mdx
+++ b/docs-next/src/content/docs/explainers/shared-behaviours.mdx
@@ -8,49 +8,49 @@ Mocha currently has no concept of a "shared behaviour" however the "contexts" fa
shared.js:
```js
-exports.shouldBehaveLikeAUser = function() {
- it('should have .name.first', function() {
- this.user.name.first.should.equal('tobi');
- })
-
- it('should have .name.last', function() {
- this.user.name.last.should.equal('holowaychuk');
- })
-
- describe('.fullname()', function() {
- it('should return the full name', function() {
- this.user.fullname().should.equal('tobi holowaychuk');
- })
- })
+exports.shouldBehaveLikeAUser = function () {
+ it("should have .name.first", function () {
+ this.user.name.first.should.equal("tobi");
+ });
+
+ it("should have .name.last", function () {
+ this.user.name.last.should.equal("holowaychuk");
+ });
+
+ describe(".fullname()", function () {
+ it("should return the full name", function () {
+ this.user.fullname().should.equal("tobi holowaychuk");
+ });
+ });
};
```
test.js:
```js
-var User = require('./user').User
- , Admin = require('./user').Admin
- , shared = require('./shared');
+var User = require("./user").User,
+ Admin = require("./user").Admin,
+ shared = require("./shared");
-describe('User', function() {
- beforeEach(function() {
- this.user = new User('tobi', 'holowaychuk');
- })
+describe("User", function () {
+ beforeEach(function () {
+ this.user = new User("tobi", "holowaychuk");
+ });
shared.shouldBehaveLikeAUser();
-})
+});
-describe('Admin', function() {
- beforeEach(function() {
- this.user = new Admin('tobi', 'holowaychuk');
- })
+describe("Admin", function () {
+ beforeEach(function () {
+ this.user = new Admin("tobi", "holowaychuk");
+ });
shared.shouldBehaveLikeAUser();
- it('should be an .admin', function() {
+ it("should be an .admin", function () {
this.user.admin.should.be.true;
- })
-})
+ });
+});
```
user.js:
@@ -62,12 +62,12 @@ exports.Admin = Admin;
function User(first, last) {
this.name = {
first: first,
- last: last
+ last: last,
};
}
-User.prototype.fullname = function() {
- return this.name.first + ' ' + this.name.last;
+User.prototype.fullname = function () {
+ return this.name.first + " " + this.name.last;
};
function Admin(first, last) {
diff --git a/docs-next/src/content/docs/explainers/spies.mdx b/docs-next/src/content/docs/explainers/spies.mdx
index b455f440..13ec9717 100644
--- a/docs-next/src/content/docs/explainers/spies.mdx
+++ b/docs-next/src/content/docs/explainers/spies.mdx
@@ -6,55 +6,55 @@ 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;
+var sinon = require("sinon"),
+ EventEmitter = require("events").EventEmitter;
-describe('EventEmitter', function() {
- describe('#emit()', function() {
- it('should invoke the callback', function() {
+describe("EventEmitter", function () {
+ describe("#emit()", function () {
+ it("should invoke the callback", function () {
var spy = sinon.spy(),
- emitter = new EventEmitter();
+ emitter = new EventEmitter();
- emitter.on('foo', spy);
- emitter.emit('foo');
+ emitter.on("foo", spy);
+ emitter.emit("foo");
spy.called.should.equal.true;
- })
+ });
- it('should pass arguments to the callbacks', function() {
+ it("should pass arguments to the callbacks", function () {
var spy = sinon.spy(),
- emitter = new EventEmitter();
+ emitter = new EventEmitter();
- emitter.on('foo', spy);
- emitter.emit('foo', 'bar', 'baz');
+ emitter.on("foo", spy);
+ emitter.emit("foo", "bar", "baz");
sinon.assert.calledOnce(spy);
- sinon.assert.calledWith(spy, 'bar', 'baz');
- })
- })
-})
+ sinon.assert.calledWith(spy, "bar", "baz");
+ });
+ });
+});
```
The following is the same test, performed without any special spy library, utilizing the Mocha `done([err])` callback as a means to assert that the callback has occurred, otherwise resulting in a timeout. Note that Mocha only allows `done()` to be invoked once, and will otherwise error.
```javascript
-describe('EventEmitter', function() {
- describe('#emit()', function() {
- it('should invoke the callback', function(done) {
+describe("EventEmitter", function () {
+ describe("#emit()", function () {
+ it("should invoke the callback", function (done) {
var emitter = new EventEmitter();
- emitter.on('foo', done);
- emitter.emit('foo');
- })
+ emitter.on("foo", done);
+ emitter.emit("foo");
+ });
- it('should pass arguments to the callbacks', function(done) {
+ it("should pass arguments to the callbacks", function (done) {
var emitter = new EventEmitter();
- emitter.on('foo', function(a, b) {
- a.should.equal('bar');
- b.should.equal('baz');
+ emitter.on("foo", function (a, b) {
+ a.should.equal("bar");
+ b.should.equal("baz");
done();
});
- emitter.emit('foo', 'bar', 'baz');
- })
- })
-})
+ emitter.emit("foo", "bar", "baz");
+ });
+ });
+});
```
diff --git a/docs-next/src/content/docs/explainers/tagging.mdx b/docs-next/src/content/docs/explainers/tagging.mdx
index 12a545d9..558c9f03 100644
--- a/docs-next/src/content/docs/explainers/tagging.mdx
+++ b/docs-next/src/content/docs/explainers/tagging.mdx
@@ -8,15 +8,15 @@ Mocha's `--grep` feature may be used both on the client (via `?grep=`) and serve
A good example of this is if you wanted to run slow tests only before releasing, or periodically. You could use any sequence of characters you like, perhaps `#slow`, `@slow` to tag them as shown here:
```js
-describe('app', function () {
- describe('GET /login', function () {
- it('should respond with the login form @fast', function () {
+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 () {
+ describe("GET /download/:file", function () {
+ it("should respond with the file @slow", function () {
// ...
});
});
diff --git a/docs-next/src/content/docs/explainers/third-party-reporters.mdx b/docs-next/src/content/docs/explainers/third-party-reporters.mdx
index c7dd3175..7ecab677 100644
--- a/docs-next/src/content/docs/explainers/third-party-reporters.mdx
+++ b/docs-next/src/content/docs/explainers/third-party-reporters.mdx
@@ -9,7 +9,7 @@ Here is a minimalistic sample reporter, which you can use by executing: `mocha -
```js
// my-reporter.js
-var mocha = require('mocha');
+var mocha = require("mocha");
module.exports = MyReporter;
function MyReporter(runner) {
@@ -17,18 +17,18 @@ function MyReporter(runner) {
var passes = 0;
var failures = 0;
- runner.on('pass', function (test) {
+ runner.on("pass", function (test) {
passes++;
- console.log('pass: %s', test.fullTitle());
+ console.log("pass: %s", test.fullTitle());
});
- runner.on('fail', function (test, err) {
+ runner.on("fail", function (test, err) {
failures++;
- console.log('fail: %s -- error: %s', test.fullTitle(), err.message);
+ console.log("fail: %s -- error: %s", test.fullTitle(), err.message);
});
- runner.on('end', function () {
- console.log('end: %d/%d', passes, passes + failures);
+ runner.on("end", function () {
+ console.log("end: %d/%d", passes, passes + failures);
});
}
@@ -36,11 +36,12 @@ function MyReporter(runner) {
// mocha.utils.inherits(MyReporter, mocha.reporters.Spec);
```
-For details look at the implementations in [lib/reporters/*](https://github.com/mochajs/mocha/tree/main/lib/reporters).
+For details look at the implementations in [lib/reporters/\*](https://github.com/mochajs/mocha/tree/main/lib/reporters).
Another sample implementation can be found at [mocha-examples: third-party-reporter (GitHub)](https://github.com/mochajs/mocha-examples/tree/main/packages/third-party-reporter).
Mocha provides the following events:
+
- **start**: Execution started
- **waiting**: Execution of root `Suite` delayed
- **ready**: Execution of root `Suite` started
diff --git a/docs-next/src/content/docs/explainers/third-party-uis.mdx b/docs-next/src/content/docs/explainers/third-party-uis.mdx
index fa98c74d..9d2c1956 100644
--- a/docs-next/src/content/docs/explainers/third-party-uis.mdx
+++ b/docs-next/src/content/docs/explainers/third-party-uis.mdx
@@ -9,17 +9,16 @@ Creating a Third Party UI involves listening for the `pre-require` event emitted
In this first brief example, we'll create an interface with only a single function: `test`
-``` javascript
-var Mocha = require('mocha');
- Suite = require('mocha/lib/suite'),
- Test = require('mocha/lib/test');
+```javascript
+var Mocha = require("mocha");
+((Suite = require("mocha/lib/suite")), (Test = require("mocha/lib/test")));
/**
* A simple UI that only exposes a single function: test
*/
-module.exports = Mocha.interfaces['simple-ui'] = function(suite) {
- suite.on('pre-require', function(context, file, mocha) {
- var common = require('mocha/lib/interfaces/common')([suite], context);
+module.exports = Mocha.interfaces["simple-ui"] = function (suite) {
+ suite.on("pre-require", function (context, file, mocha) {
+ var common = require("mocha/lib/interfaces/common")([suite], context);
context.run = mocha.options.delay && common.runWithSuite(suite);
@@ -27,7 +26,7 @@ module.exports = Mocha.interfaces['simple-ui'] = function(suite) {
* Describes a specification or test-case with the given `title`
* and callback `fn` acting as a thunk.
*/
- context.test = function(title, fn) {
+ context.test = function (title, fn) {
var test = new Test(title, fn);
test.file = file;
suite.addTest(test);
@@ -38,13 +37,13 @@ module.exports = Mocha.interfaces['simple-ui'] = function(suite) {
};
```
-``` javascript
-test('pass', function() {
+```javascript
+test("pass", function () {
// pass
});
-test('fail', function() {
- throw new Error('oops!');
+test("fail", function () {
+ throw new Error("oops!");
});
```
@@ -68,22 +67,22 @@ $ mocha --require ./simple-ui.js --ui simple-ui test.js
In this next example, we'll be extending the [TDD interface](https://github.com/mochajs/mocha/blob/master/lib/interfaces/tdd.js) with a comment function that simply prints the passed text. That is, `comment('This is a comment');` would print the string.
-``` javascript
-var Mocha = require('mocha');
- Suite = require('mocha/lib/suite'),
- Test = require('mocha/lib/test'),
- escapeRe = require('escape-string-regexp');
+```javascript
+var Mocha = require("mocha");
+((Suite = require("mocha/lib/suite")),
+ (Test = require("mocha/lib/test")),
+ (escapeRe = require("escape-string-regexp")));
/**
* 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
*/
-module.exports = Mocha.interfaces['example-ui'] = function(suite) {
+module.exports = Mocha.interfaces["example-ui"] = function (suite) {
var suites = [suite];
- suite.on('pre-require', function(context, file, mocha) {
- var common = require('mocha/lib/interfaces/common')(suites, context);
+ suite.on("pre-require", function (context, file, mocha) {
+ var common = require("mocha/lib/interfaces/common")(suites, context);
/**
* Use all existing hook logic common to UIs. Common logic can be found in
@@ -102,7 +101,7 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
* a pending test. But any custom reporter could check for the isComment
* attribute on a test to modify its presentation.
*/
- context.comment = function(title) {
+ context.comment = function (title) {
var suite, comment;
suite = suites[0];
@@ -125,7 +124,7 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
* given title and callback, fn`, which may contain nested suites
* and/or tests.
*/
- context.suite = function(title, fn) {
+ context.suite = function (title, fn) {
var suite = Suite.create(suites[0], title);
suite.file = file;
@@ -139,7 +138,7 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
/**
* The default TDD pending suite functionality.
*/
- context.suite.skip = function(title, fn) {
+ context.suite.skip = function (title, fn) {
var suite = Suite.create(suites[0], title);
suite.pending = true;
@@ -151,7 +150,7 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
/**
* Default TDD exclusive test-case logic.
*/
- context.suite.only = function(title, fn) {
+ context.suite.only = function (title, fn) {
var suite = context.suite(title, fn);
mocha.grep(suite.fullTitle());
};
@@ -160,7 +159,7 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
* Default TDD test-case logic. Describes a specification or test-case
* with the given `title` and callback `fn` acting as a thunk.
*/
- context.test = function(title, fn) {
+ context.test = function (title, fn) {
var suite, test;
suite = suites[0];
@@ -175,11 +174,11 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
/**
* Exclusive test-case.
*/
- context.test.only = function(title, fn) {
+ context.test.only = function (title, fn) {
var test, reString;
test = context.test(title, fn);
- reString = '^' + escapeRe(test.fullTitle()) + '$';
+ reString = "^" + escapeRe(test.fullTitle()) + "$";
mocha.grep(new RegExp(reString));
};
@@ -191,16 +190,16 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
};
```
-``` javascript
-suite('Example', function() {
+```javascript
+suite("Example", function () {
comment("Here's the addition we made to the UI");
- test('passing test', function() {
+ test("passing test", function () {
// Pass
});
- test('failing test', function() {
- throw new Error('it failed!');
+ test("failing test", function () {
+ throw new Error("it failed!");
});
});
```
diff --git a/docs/_data/files.js b/docs/_data/files.js
index 0435ffce..dd27f794 100644
--- a/docs/_data/files.js
+++ b/docs/_data/files.js
@@ -1,28 +1,28 @@
-'use strict';
+"use strict";
-const {resolve, relative, dirname} = require('node:path');
-const {promises: fs} = require('node:fs');
+const { resolve, relative, dirname } = require("node:path");
+const { promises: fs } = require("node:fs");
-const PROJECT_ROOT_DIR = resolve(__dirname, '..', '..');
+const PROJECT_ROOT_DIR = resolve(__dirname, "..", "..");
const FILES = [
{
- slug: 'simplereporter',
- path: require.resolve('../../test/integration/fixtures/simple-reporter.js'),
- header: '// my-reporter.js'
- }
+ slug: "simplereporter",
+ path: require.resolve("../../test/integration/fixtures/simple-reporter.js"),
+ header: "// my-reporter.js",
+ },
];
-const loadFile = async (path, {header} = {}) => {
+const loadFile = async (path, { header } = {}) => {
const relativeDir = relative(dirname(path), PROJECT_ROOT_DIR);
- let content = await fs.readFile(path, 'utf-8');
+ let content = await fs.readFile(path, "utf-8");
// replace relative paths in `require()` to root with "mocha".
// might not work in the general case. not gonna parse an AST for this
// e.g. `require('../../lib/foo')` => `require('mocha/lib/foo')`
// also trim any trailing whitespace
content = content
.replace(
- new RegExp(`require\\(['"]${relativeDir}(.*?)['"]\\)`, 'g'),
- "require('mocha$1')"
+ new RegExp(`require\\(['"]${relativeDir}(.*?)['"]\\)`, "g"),
+ "require('mocha$1')",
)
.trim();
return `${header}\n\n${content}`;
@@ -34,15 +34,15 @@ const loadFile = async (path, {header} = {}) => {
*/
module.exports = async () => {
const files = [];
- for await (const {path, header, slug} of FILES) {
- const content = await loadFile(path, {header});
- files.push({slug, content});
+ for await (const { path, header, slug } of FILES) {
+ const content = await loadFile(path, { header });
+ files.push({ slug, content });
}
return files.reduce(
- (files, {slug, content}) => ({
+ (files, { slug, content }) => ({
...files,
- [slug]: content
+ [slug]: content,
}),
- {}
+ {},
);
};
diff --git a/docs/_data/supporters.js b/docs/_data/supporters.js
index 1d59fead..be4ce738 100755
--- a/docs/_data/supporters.js
+++ b/docs/_data/supporters.js
@@ -13,46 +13,47 @@
* @see https://docs.opencollective.com/help/contributing/development/api
*/
-'use strict';
+"use strict";
-const {writeFile, mkdir, rm} = require('node:fs').promises;
-const {resolve} = require('node:path');
-const debug = require('debug')('mocha:docs:data:supporters');
-const needle = require('needle');
-const blocklist = new Set(require('./blocklist.json'));
+const { writeFile, mkdir, rm } = require("node:fs").promises;
+const { resolve } = require("node:path");
+const debug = require("debug")("mocha:docs:data:supporters");
+const needle = require("needle");
+const blocklist = new Set(require("./blocklist.json"));
/**
* In addition to the blocklist, any account slug matching this regex will not
* be displayed on the website.
*/
-const BLOCKED_STRINGS = /(?:[ck]a[sz]ino|seo|slot|gambl(?:e|ing)|crypto|follow|buy|cheap|instagram|hacks|tiktok|likes|youtube|subscriber|boost|deposit|mushroom|bingo|broker|promotion|bathroom|landscaping|lawn care|groundskeeping|remediation|esports|links|coupon|review|refer|promocode|rabattkod|jämför|betting|reddit|hire|fortune|equity|download|marketing|comment|rank|scrapcar|lawyer|celeb|concrete|firestick|playground)/i;
+const BLOCKED_STRINGS =
+ /(?:[ck]a[sz]ino|seo|slot|gambl(?:e|ing)|crypto|follow|buy|cheap|instagram|hacks|tiktok|likes|youtube|subscriber|boost|deposit|mushroom|bingo|broker|promotion|bathroom|landscaping|lawn care|groundskeeping|remediation|esports|links|coupon|review|refer|promocode|rabattkod|jämför|betting|reddit|hire|fortune|equity|download|marketing|comment|rank|scrapcar|lawyer|celeb|concrete|firestick|playground)/i;
/**
* Add a few Categories exposed by Open Collective to help moderation
*/
const BLOCKED_CATEGORIES = [
- 'adult',
- 'casino',
- 'credit',
- 'gambling',
- 'seo',
- 'writer',
- 'review'
+ "adult",
+ "casino",
+ "credit",
+ "gambling",
+ "seo",
+ "writer",
+ "review",
];
/**
* The OC API endpoint
*/
-const API_ENDPOINT = 'https://api.opencollective.com/graphql/v2';
+const API_ENDPOINT = "https://api.opencollective.com/graphql/v2";
-const SPONSOR_TIER = 'sponsors';
-const BACKER_TIER = 'backers';
+const SPONSOR_TIER = "sponsors";
+const BACKER_TIER = "backers";
// if this percent of fetches completes, the build will pass
const PRODUCTION_SUCCESS_THRESHOLD = 0.9;
-const SUPPORTER_IMAGE_PATH = resolve(__dirname, '../images/supporters');
+const SUPPORTER_IMAGE_PATH = resolve(__dirname, "../images/supporters");
const SUPPORTER_QUERY = `query account($limit: Int, $offset: Int, $slug: String) {
account(slug: $slug) {
@@ -83,7 +84,7 @@ const GRAPHQL_PAGE_SIZE = 1000;
const invalidSupporters = [];
-const nodeToSupporter = node => ({
+const nodeToSupporter = (node) => ({
id: node.fromAccount.id,
name: node.fromAccount.name,
slug: node.fromAccount.slug,
@@ -94,32 +95,32 @@ const nodeToSupporter = node => ({
categories: node.fromAccount.categories,
tier: (node.tier && node.tier.slug) || BACKER_TIER,
totalDonations: node.totalDonations.value * 100,
- firstDonation: node.createdAt
+ firstDonation: node.createdAt,
});
const fetchImage = process.env.MOCHA_DOCS_SKIP_IMAGE_DOWNLOAD
- ? async supporter => {
+ ? async (supporter) => {
invalidSupporters.push(supporter);
}
- : async supporter => {
+ : async (supporter) => {
try {
- const {avatar: url} = supporter;
- const {body: imageBuf, headers} = await needle('get', url, {
- open_timeout: 30000
+ const { avatar: url } = supporter;
+ const { body: imageBuf, headers } = await needle("get", url, {
+ open_timeout: 30000,
});
- if (headers['content-type'].startsWith('text/html')) {
+ if (headers["content-type"].startsWith("text/html")) {
throw new TypeError(
- 'received html and expected a png; outage likely'
+ "received html and expected a png; outage likely",
);
}
- debug('fetched %s', url);
- const filePath = resolve(SUPPORTER_IMAGE_PATH, supporter.id + '.png');
+ debug("fetched %s", url);
+ const filePath = resolve(SUPPORTER_IMAGE_PATH, supporter.id + ".png");
await writeFile(filePath, imageBuf);
- debug('wrote %s', filePath);
+ debug("wrote %s", filePath);
} catch (err) {
console.error(
`failed to load ${supporter.avatar}; will discard ${supporter.tier} "${supporter.name} (${supporter.slug}). reason:\n`,
- err
+ err,
);
invalidSupporters.push(supporter);
}
@@ -132,42 +133,43 @@ const fetchImage = process.env.MOCHA_DOCS_SKIP_IMAGE_DOWNLOAD
* @param {string} slug - Collective slug to get donation data from
* @returns {Promise<Object[]>} Array of raw donation data
*/
-const getAllOrders = async (slug = 'mochajs') => {
+const getAllOrders = async (slug = "mochajs") => {
let allOrders = [];
- const variables = {limit: GRAPHQL_PAGE_SIZE, offset: 0, slug};
+ const variables = { limit: GRAPHQL_PAGE_SIZE, offset: 0, slug };
// Handling pagination if necessary (2 pages for ~1400 results in May 2019)
while (true) {
const result = await needle(
- 'post',
+ "post",
API_ENDPOINT,
- {query: SUPPORTER_QUERY, variables},
- {json: true}
+ { query: SUPPORTER_QUERY, variables },
+ { json: true },
);
const orders = result.body.data.account.orders.nodes;
allOrders = [...allOrders, ...orders];
variables.offset += GRAPHQL_PAGE_SIZE;
if (orders.length < GRAPHQL_PAGE_SIZE) {
- debug('retrieved %d orders', allOrders.length);
+ debug("retrieved %d orders", allOrders.length);
return allOrders;
} else {
debug(
- 'loading page %d of orders...',
- Math.floor(variables.offset / GRAPHQL_PAGE_SIZE)
+ "loading page %d of orders...",
+ Math.floor(variables.offset / GRAPHQL_PAGE_SIZE),
);
}
}
};
-const isAllowed = ({name, slug, website, categories}) => {
- const allowed = !blocklist.has(slug) &&
+const isAllowed = ({ name, slug, website, categories }) => {
+ const allowed =
+ !blocklist.has(slug) &&
!BLOCKED_STRINGS.test(name) &&
!BLOCKED_STRINGS.test(slug) &&
!BLOCKED_STRINGS.test(website) &&
- !categories.some(category => BLOCKED_CATEGORIES.includes(category));
+ !categories.some((category) => BLOCKED_CATEGORIES.includes(category));
if (!allowed) {
- debug('filtering %o', {categories, name, slug, website});
+ debug("filtering %o", { categories, name, slug, website });
} else {
// debug('keeping %o', {categories, name, slug, website}, BLOCKED_STRINGS.test(website));
}
@@ -201,13 +203,13 @@ const getSupporters = async () => {
.reduce(
(supporters, supporter) => {
if (supporter.tier === BACKER_TIER) {
- if (supporter.name !== 'anonymous') {
+ if (supporter.name !== "anonymous") {
supporters[BACKER_TIER] = [
...supporters[BACKER_TIER],
{
...supporter,
- avatar: encodeURI(supporter.imgUrlSmall)
- }
+ avatar: encodeURI(supporter.imgUrlSmall),
+ },
];
}
} else {
@@ -215,37 +217,37 @@ const getSupporters = async () => {
...supporters[SPONSOR_TIER],
{
...supporter,
- avatar: encodeURI(supporter.imgUrlMed)
- }
+ avatar: encodeURI(supporter.imgUrlMed),
+ },
];
}
return supporters;
},
{
[SPONSOR_TIER]: [],
- [BACKER_TIER]: []
- }
+ [BACKER_TIER]: [],
+ },
);
- await rm(SUPPORTER_IMAGE_PATH, {recursive: true, force: true});
- debug('blasted %s', SUPPORTER_IMAGE_PATH);
- await mkdir(SUPPORTER_IMAGE_PATH, {recursive: true});
- debug('created %s', SUPPORTER_IMAGE_PATH);
+ await rm(SUPPORTER_IMAGE_PATH, { recursive: true, force: true });
+ debug("blasted %s", SUPPORTER_IMAGE_PATH);
+ await mkdir(SUPPORTER_IMAGE_PATH, { recursive: true });
+ debug("created %s", SUPPORTER_IMAGE_PATH);
// Fetch images for sponsors and save their image dimensions
await Promise.all([
...supporters[SPONSOR_TIER].map(fetchImage),
- ...supporters[BACKER_TIER].map(fetchImage)
+ ...supporters[BACKER_TIER].map(fetchImage),
]);
- debug('fetched images');
+ debug("fetched images");
- invalidSupporters.forEach(supporter => {
+ invalidSupporters.forEach((supporter) => {
supporters[supporter.tier].splice(
supporters[supporter.tier].indexOf(supporter),
- 1
+ 1,
);
});
- debug('tossed out invalid supporters');
+ debug("tossed out invalid supporters");
const backerCount = supporters[BACKER_TIER].length;
const sponsorCount = supporters[SPONSOR_TIER].length;
@@ -253,22 +255,22 @@ const getSupporters = async () => {
const successRate = 1 - invalidSupporters.length / totalSupportersCount;
debug(
- 'found %d valid backers and %d valid sponsors (%d total; %d invalid; %d blocked)',
+ "found %d valid backers and %d valid sponsors (%d total; %d invalid; %d blocked)",
backerCount,
sponsorCount,
totalSupportersCount,
invalidSupporters.length,
- uniqueSupporters.size - totalSupportersCount
+ uniqueSupporters.size - totalSupportersCount,
);
if (successRate < PRODUCTION_SUCCESS_THRESHOLD) {
- if (process.env.NETLIFY && process.env.CONTEXT !== 'deploy-preview') {
+ if (process.env.NETLIFY && process.env.CONTEXT !== "deploy-preview") {
throw new Error(
`Failed to meet success threshold ${
PRODUCTION_SUCCESS_THRESHOLD * 100
}% (was ${
successRate * 100
- }%) for a production deployment; refusing to deploy`
+ }%) for a production deployment; refusing to deploy`,
);
} else {
console.warn(
@@ -276,18 +278,21 @@ const getSupporters = async () => {
successRate * 100
}% fails to meet production threshold of ${
PRODUCTION_SUCCESS_THRESHOLD * 100
- }%; would fail a production deployment!`
+ }%; would fail a production deployment!`,
);
}
}
- debug('supporter image pull completed');
+ debug("supporter image pull completed");
// TODO: For now, this supporters.js script is used both in the classic docs (docs/) and next (docs-next/).
// Eventually, we'll sunset the classic docs and only have docs-next.
// At that point we'll have supporters.js only used for writing files.
- if (process.argv.includes('--write-supporters-json')) {
+ if (process.argv.includes("--write-supporters-json")) {
await mkdir("src/content/data", { recursive: true });
- await writeFile('src/content/data/supporters.json', JSON.stringify(supporters, null, 4));
+ await writeFile(
+ "src/content/data/supporters.json",
+ JSON.stringify(supporters, null, 4),
+ );
}
return supporters;
};
@@ -295,8 +300,8 @@ const getSupporters = async () => {
module.exports = getSupporters;
if (require.main === module) {
- require('debug').enable('mocha:docs:data:supporters');
- process.on('unhandledRejection', err => {
+ require("debug").enable("mocha:docs:data:supporters");
+ process.on("unhandledRejection", (err) => {
throw err;
});
getSupporters();
diff --git a/docs/_data/toc.js b/docs/_data/toc.js
index 11763d16..0f852a7b 100644
--- a/docs/_data/toc.js
+++ b/docs/_data/toc.js
@@ -1,21 +1,21 @@
-'use strict';
+"use strict";
-const markdownToc = require('markdown-toc');
-const {readFileSync} = require('node:fs');
-const {resolve} = require('node:path');
+const markdownToc = require("markdown-toc");
+const { readFileSync } = require("node:fs");
+const { resolve } = require("node:path");
const IGNORED_HEADINGS_REGEXP = /Features|Table of Contents|Backers|Sponsors/i;
-const DOCUMENT_PATH = resolve(__dirname, '..', 'index.md');
+const DOCUMENT_PATH = resolve(__dirname, "..", "index.md");
module.exports = () => {
- const doc = readFileSync(DOCUMENT_PATH, 'utf-8');
+ const doc = readFileSync(DOCUMENT_PATH, "utf-8");
return markdownToc(doc, {
- slugify: require('uslug'),
+ slugify: require("uslug"),
firsth1: false,
- bullets: '-',
+ bullets: "-",
maxdepth: 2,
// if filter is supplied, maxdepth is apparently ignored,
// so we have to do it ourselves.
- filter: (str, ele) => ele.lvl < 2 && !IGNORED_HEADINGS_REGEXP.test(str)
+ filter: (str, ele) => ele.lvl < 2 && !IGNORED_HEADINGS_REGEXP.test(str),
}).content;
};
diff --git a/docs/_data/usage.js b/docs/_data/usage.js
index 84bcbb85..685f2da7 100644
--- a/docs/_data/usage.js
+++ b/docs/_data/usage.js
@@ -1,11 +1,11 @@
-'use strict';
+"use strict";
-const {stripVTControlCharacters} = require('node:util');
-const {resolve} = require('node:path');
-const {execSync} = require('node:child_process');
+const { stripVTControlCharacters } = require("node:util");
+const { resolve } = require("node:path");
+const { execSync } = require("node:child_process");
-const executable = require.resolve('../../bin/mocha');
-const flag = '--help';
+const executable = require.resolve("../../bin/mocha");
+const flag = "--help";
/**
* Return the output of `mocha --help` for display
@@ -14,8 +14,8 @@ module.exports = () => {
return stripVTControlCharacters(
String(
execSync(`"${process.execPath}" ${executable} ${flag}`, {
- cwd: resolve(__dirname, '..')
- })
- ).trim()
+ cwd: resolve(__dirname, ".."),
+ }),
+ ).trim(),
);
};
diff --git a/docs/api-tutorials/count-assertions.md b/docs/api-tutorials/count-assertions.md
index 78851cf4..17a1e0d2 100644
--- a/docs/api-tutorials/count-assertions.md
+++ b/docs/api-tutorials/count-assertions.md
@@ -5,7 +5,7 @@ var expected = 0;
var actual = 0;
function assert(expr, msg) {
- if (!expr) throw new Error(msg || 'assertion failed');
+ if (!expr) throw new Error(msg || "assertion failed");
actual++;
}
@@ -20,23 +20,23 @@ function reset() {
function check() {
if (!expected || expected == actual) return;
- var err = new Error('expected ' + expected + ' assertions, got ' + actual);
- this.currentTest.emit('error', err);
+ var err = new Error("expected " + expected + " assertions, got " + actual);
+ this.currentTest.emit("error", err);
}
beforeEach(reset);
afterEach(check);
-describe('something', function () {
- it('should work', function (done) {
+describe("something", function () {
+ it("should work", function (done) {
expect(2);
setTimeout(function () {
- assert('wahoo');
+ assert("wahoo");
}, 50);
setTimeout(function () {
- assert('hey');
+ assert("hey");
}, 50);
setTimeout(function () {
diff --git a/docs/api-tutorials/find-global-leaks.md b/docs/api-tutorials/find-global-leaks.md
index ae2e6dff..d8881227 100644
--- a/docs/api-tutorials/find-global-leaks.md
+++ b/docs/api-tutorials/find-global-leaks.md
@@ -1,10 +1,10 @@
Detecting which module is causing a global leak can be tedious. Add these lines at the very beginning of your tests, or in a file which is included via `--require`:
```javascript
-Object.defineProperty(global, 'name_of_leaking_property', {
+Object.defineProperty(global, "name_of_leaking_property", {
set: function (value) {
- throw new Error('Found the leak!');
- }
+ throw new Error("Found the leak!");
+ },
});
```
diff --git a/docs/api-tutorials/shared-behaviours.md b/docs/api-tutorials/shared-behaviours.md
index f2788bb5..2d63b259 100644
--- a/docs/api-tutorials/shared-behaviours.md
+++ b/docs/api-tutorials/shared-behaviours.md
@@ -3,49 +3,49 @@ Mocha currently has no concept of a "shared behaviour" however the "contexts" fa
shared.js:
```js
-exports.shouldBehaveLikeAUser = function() {
- it('should have .name.first', function() {
- this.user.name.first.should.equal('tobi');
- })
-
- it('should have .name.last', function() {
- this.user.name.last.should.equal('holowaychuk');
- })
-
- describe('.fullname()', function() {
- it('should return the full name', function() {
- this.user.fullname().should.equal('tobi holowaychuk');
- })
- })
+exports.shouldBehaveLikeAUser = function () {
+ it("should have .name.first", function () {
+ this.user.name.first.should.equal("tobi");
+ });
+
+ it("should have .name.last", function () {
+ this.user.name.last.should.equal("holowaychuk");
+ });
+
+ describe(".fullname()", function () {
+ it("should return the full name", function () {
+ this.user.fullname().should.equal("tobi holowaychuk");
+ });
+ });
};
```
test.js:
```js
-var User = require('./user').User
- , Admin = require('./user').Admin
- , shared = require('./shared');
+var User = require("./user").User,
+ Admin = require("./user").Admin,
+ shared = require("./shared");
-describe('User', function() {
- beforeEach(function() {
- this.user = new User('tobi', 'holowaychuk');
- })
+describe("User", function () {
+ beforeEach(function () {
+ this.user = new User("tobi", "holowaychuk");
+ });
shared.shouldBehaveLikeAUser();
-})
+});
-describe('Admin', function() {
- beforeEach(function() {
- this.user = new Admin('tobi', 'holowaychuk');
- })
+describe("Admin", function () {
+ beforeEach(function () {
+ this.user = new Admin("tobi", "holowaychuk");
+ });
shared.shouldBehaveLikeAUser();
- it('should be an .admin', function() {
+ it("should be an .admin", function () {
this.user.admin.should.be.true;
- })
-})
+ });
+});
```
user.js:
@@ -57,12 +57,12 @@ exports.Admin = Admin;
function User(first, last) {
this.name = {
first: first,
- last: last
+ last: last,
};
}
-User.prototype.fullname = function() {
- return this.name.first + ' ' + this.name.last;
+User.prototype.fullname = function () {
+ return this.name.first + " " + this.name.last;
};
function Admin(first, last) {
diff --git a/docs/api-tutorials/spies.md b/docs/api-tutorials/spies.md
index abcd0c8a..1802dd07 100644
--- a/docs/api-tutorials/spies.md
+++ b/docs/api-tutorials/spies.md
@@ -1,55 +1,55 @@
Mocha does not come equipped with spies, though libraries like [Sinon](https://github.com/cjohansen/sinon.js) 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;
+var sinon = require("sinon"),
+ EventEmitter = require("events").EventEmitter;
-describe('EventEmitter', function() {
- describe('#emit()', function() {
- it('should invoke the callback', function() {
+describe("EventEmitter", function () {
+ describe("#emit()", function () {
+ it("should invoke the callback", function () {
var spy = sinon.spy(),
- emitter = new EventEmitter();
+ emitter = new EventEmitter();
- emitter.on('foo', spy);
- emitter.emit('foo');
+ emitter.on("foo", spy);
+ emitter.emit("foo");
spy.called.should.equal.true;
- })
+ });
- it('should pass arguments to the callbacks', function() {
+ it("should pass arguments to the callbacks", function () {
var spy = sinon.spy(),
- emitter = new EventEmitter();
+ emitter = new EventEmitter();
- emitter.on('foo', spy);
- emitter.emit('foo', 'bar', 'baz');
+ emitter.on("foo", spy);
+ emitter.emit("foo", "bar", "baz");
sinon.assert.calledOnce(spy);
- sinon.assert.calledWith(spy, 'bar', 'baz');
- })
- })
-})
+ sinon.assert.calledWith(spy, "bar", "baz");
+ });
+ });
+});
```
The following is the same test, performed without any special spy library, utilizing the Mocha `done([err])` callback as a means to assert that the callback has occurred, otherwise resulting in a timeout. Note that Mocha only allows `done()` to be invoked once, and will otherwise error.
```javascript
-describe('EventEmitter', function() {
- describe('#emit()', function() {
- it('should invoke the callback', function(done) {
+describe("EventEmitter", function () {
+ describe("#emit()", function () {
+ it("should invoke the callback", function (done) {
var emitter = new EventEmitter();
- emitter.on('foo', done);
- emitter.emit('foo');
- })
+ emitter.on("foo", done);
+ emitter.emit("foo");
+ });
- it('should pass arguments to the callbacks', function(done) {
+ it("should pass arguments to the callbacks", function (done) {
var emitter = new EventEmitter();
- emitter.on('foo', function(a, b) {
- a.should.equal('bar');
- b.should.equal('baz');
+ emitter.on("foo", function (a, b) {
+ a.should.equal("bar");
+ b.should.equal("baz");
done();
});
- emitter.emit('foo', 'bar', 'baz');
- })
- })
-})
+ emitter.emit("foo", "bar", "baz");
+ });
+ });
+});
```
diff --git a/docs/api-tutorials/tagging.md b/docs/api-tutorials/tagging.md
index 69c14f13..bc940fc6 100644
--- a/docs/api-tutorials/tagging.md
+++ b/docs/api-tutorials/tagging.md
@@ -3,15 +3,15 @@ Mocha's `--grep` feature may be used both on the client (via `?grep=`) and serve
A good example of this is if you wanted to run slow tests only before releasing, or periodically. You could use any sequence of characters you like, perhaps `#slow`, `@slow` to tag them as shown here:
```js
-describe('app', function () {
- describe('GET /login', function () {
- it('should respond with the login form @fast', function () {
+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 () {
+ describe("GET /download/:file", function () {
+ it("should respond with the file @slow", function () {
// ...
});
});
diff --git a/docs/api-tutorials/third-party-reporters.md b/docs/api-tutorials/third-party-reporters.md
index bef513c6..c8f48a66 100644
--- a/docs/api-tutorials/third-party-reporters.md
+++ b/docs/api-tutorials/third-party-reporters.md
@@ -4,7 +4,7 @@ Here is a minimalistic sample reporter, which you can use by executing: `mocha -
```js
// my-reporter.js
-var mocha = require('mocha');
+var mocha = require("mocha");
module.exports = MyReporter;
function MyReporter(runner) {
@@ -12,18 +12,18 @@ function MyReporter(runner) {
var passes = 0;
var failures = 0;
- runner.on('pass', function (test) {
+ runner.on("pass", function (test) {
passes++;
- console.log('pass: %s', test.fullTitle());
+ console.log("pass: %s", test.fullTitle());
});
- runner.on('fail', function (test, err) {
+ runner.on("fail", function (test, err) {
failures++;
- console.log('fail: %s -- error: %s', test.fullTitle(), err.message);
+ console.log("fail: %s -- error: %s", test.fullTitle(), err.message);
});
- runner.on('end', function () {
- console.log('end: %d/%d', passes, passes + failures);
+ runner.on("end", function () {
+ console.log("end: %d/%d", passes, passes + failures);
});
}
diff --git a/docs/api-tutorials/third-party-uis.md b/docs/api-tutorials/third-party-uis.md
index b617153e..985760d5 100644
--- a/docs/api-tutorials/third-party-uis.md
+++ b/docs/api-tutorials/third-party-uis.md
@@ -4,17 +4,16 @@ Creating a Third Party UI involves listening for the `pre-require` event emitted
In this first brief example, we'll create an interface with only a single function: `test`
-``` javascript
-var Mocha = require('mocha');
- Suite = require('mocha/lib/suite'),
- Test = require('mocha/lib/test');
+```javascript
+var Mocha = require("mocha");
+((Suite = require("mocha/lib/suite")), (Test = require("mocha/lib/test")));
/**
* A simple UI that only exposes a single function: test
*/
-module.exports = Mocha.interfaces['simple-ui'] = function(suite) {
- suite.on('pre-require', function(context, file, mocha) {
- var common = require('mocha/lib/interfaces/common')([suite], context);
+module.exports = Mocha.interfaces["simple-ui"] = function (suite) {
+ suite.on("pre-require", function (context, file, mocha) {
+ var common = require("mocha/lib/interfaces/common")([suite], context);
context.run = mocha.options.delay && common.runWithSuite(suite);
@@ -22,7 +21,7 @@ module.exports = Mocha.interfaces['simple-ui'] = function(suite) {
* Describes a specification or test-case with the given `title`
* and callback `fn` acting as a thunk.
*/
- context.test = function(title, fn) {
+ context.test = function (title, fn) {
var test = new Test(title, fn);
test.file = file;
suite.addTest(test);
@@ -33,13 +32,13 @@ module.exports = Mocha.interfaces['simple-ui'] = function(suite) {
};
```
-``` javascript
-test('pass', function() {
+```javascript
+test("pass", function () {
// pass
});
-test('fail', function() {
- throw new Error('oops!');
+test("fail", function () {
+ throw new Error("oops!");
});
```
@@ -63,22 +62,22 @@ $ mocha --require ./simple-ui.js --ui simple-ui test.js
In this next example, we'll be extending the [TDD interface](https://github.com/mochajs/mocha/blob/master/lib/interfaces/tdd.js) with a comment function that simply prints the passed text. That is, `comment('This is a comment');` would print the string.
-``` javascript
-var Mocha = require('mocha');
- Suite = require('mocha/lib/suite'),
- Test = require('mocha/lib/test'),
- escapeRe = require('escape-string-regexp');
+```javascript
+var Mocha = require("mocha");
+((Suite = require("mocha/lib/suite")),
+ (Test = require("mocha/lib/test")),
+ (escapeRe = require("escape-string-regexp")));
/**
* 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
*/
-module.exports = Mocha.interfaces['example-ui'] = function(suite) {
+module.exports = Mocha.interfaces["example-ui"] = function (suite) {
var suites = [suite];
- suite.on('pre-require', function(context, file, mocha) {
- var common = require('mocha/lib/interfaces/common')(suites, context);
+ suite.on("pre-require", function (context, file, mocha) {
+ var common = require("mocha/lib/interfaces/common")(suites, context);
/**
* Use all existing hook logic common to UIs. Common logic can be found in
@@ -97,7 +96,7 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
* a pending test. But any custom reporter could check for the isComment
* attribute on a test to modify its presentation.
*/
- context.comment = function(title) {
+ context.comment = function (title) {
var suite, comment;
suite = suites[0];
@@ -120,7 +119,7 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
* given title and callback, fn`, which may contain nested suites
* and/or tests.
*/
- context.suite = function(title, fn) {
+ context.suite = function (title, fn) {
var suite = Suite.create(suites[0], title);
suite.file = file;
@@ -134,7 +133,7 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
/**
* The default TDD pending suite functionality.
*/
- context.suite.skip = function(title, fn) {
+ context.suite.skip = function (title, fn) {
var suite = Suite.create(suites[0], title);
suite.pending = true;
@@ -146,7 +145,7 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
/**
* Default TDD exclusive test-case logic.
*/
- context.suite.only = function(title, fn) {
+ context.suite.only = function (title, fn) {
var suite = context.suite(title, fn);
mocha.grep(suite.fullTitle());
};
@@ -155,7 +154,7 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
* Default TDD test-case logic. Describes a specification or test-case
* with the given `title` and callback `fn` acting as a thunk.
*/
- context.test = function(title, fn) {
+ context.test = function (title, fn) {
var suite, test;
suite = suites[0];
@@ -170,11 +169,11 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
/**
* Exclusive test-case.
*/
- context.test.only = function(title, fn) {
+ context.test.only = function (title, fn) {
var test, reString;
test = context.test(title, fn);
- reString = '^' + escapeRe(test.fullTitle()) + '$';
+ reString = "^" + escapeRe(test.fullTitle()) + "$";
mocha.grep(new RegExp(reString));
};
@@ -186,16 +185,16 @@ module.exports = Mocha.interfaces['example-ui'] = function(suite) {
};
```
-``` javascript
-suite('Example', function() {
+```javascript
+suite("Example", function () {
comment("Here's the addition we made to the UI");
- test('passing test', function() {
+ test("passing test", function () {
// Pass
});
- test('failing test', function() {
- throw new Error('it failed!');
+ test("failing test", function () {
+ throw new Error("it failed!");
});
});
```
diff --git a/docs/css/style.css b/docs/css/style.css
index 52cc35aa..ff81491b 100644
--- a/docs/css/style.css
+++ b/docs/css/style.css
@@ -1,5 +1,9 @@
html {
- font: 16px/1.6 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ font:
+ 16px/1.6 "Helvetica Neue",
+ Helvetica,
+ Arial,
+ sans-serif;
}
body {
@@ -56,7 +60,9 @@ header {
}
#tag {
- animation: fadein 1s forwards, slideright 1s forwards;
+ animation:
+ fadein 1s forwards,
+ slideright 1s forwards;
color: #c29d7f;
font-size: 30px;
font-weight: 100;
@@ -215,7 +221,9 @@ ul.single-column li > ul > li {
}
code {
- font: 14px monaco, monospace;
+ font:
+ 14px monaco,
+ monospace;
line-height: 1.8;
}
@@ -238,7 +246,9 @@ pre {
img.screenshot {
border-radius: 3px;
- box-shadow: 0 3px 10px #dedede, 0 1px 5px #888;
+ box-shadow:
+ 0 3px 10px #dedede,
+ 0 1px 5px #888;
display: block;
margin: 30px auto;
max-width: 100%;
@@ -283,7 +293,7 @@ footer {
/* displays each list item with a "|" between */
#openjsf-links li + li:before {
- content: ' | ';
+ content: " | ";
}
.openjsf-logo {
@@ -325,11 +335,11 @@ footer {
}
.dl-inline dt:after {
- content: ': ';
+ content: ": ";
}
.dl-inline dd + dt:before {
- content: '';
+ content: "";
display: block;
}
@@ -391,6 +401,6 @@ table td {
}
}
-#mocha-fixture-wizard text[font-weight=bold]:hover {
+#mocha-fixture-wizard text[font-weight="bold"]:hover {
text-decoration: underline;
}
diff --git a/docs/example/Array.js b/docs/example/Array.js
index 9be8287b..c3820c6a 100644
--- a/docs/example/Array.js
+++ b/docs/example/Array.js
@@ -1,74 +1,72 @@
-
-describe('Array', function(){
- describe('.push()', function(){
- it('should append a value', function(){
+describe("Array", function () {
+ describe(".push()", function () {
+ it("should append a value", function () {
var arr = [];
- arr.push('foo');
- arr.push('bar');
- expect(arr[0]).to.equal('foo');
- expect(arr[1]).to.equal('bar');
- })
+ arr.push("foo");
+ arr.push("bar");
+ expect(arr[0]).to.equal("foo");
+ expect(arr[1]).to.equal("bar");
+ });
- it('should return the length', function(){
+ it("should return the length", function () {
var arr = [];
- var n = arr.push('foo');
+ var n = arr.push("foo");
expect(n).to.equal(1);
- n = arr.push('bar');
+ n = arr.push("bar");
expect(n).to.equal(2);
- })
+ });
- describe('with many arguments', function(){
- it('should add the values', function(){
+ describe("with many arguments", function () {
+ it("should add the values", function () {
var arr = [];
- arr.push('foo', 'bar');
- expect(arr[0]).to.equal('foo');
- expect(arr[1]).to.equal('bar');
- })
- })
- })
+ arr.push("foo", "bar");
+ expect(arr[0]).to.equal("foo");
+ expect(arr[1]).to.equal("bar");
+ });
+ });
+ });
- describe('.unshift()', function(){
- it('should prepend a value', function(){
- var arr = [1,2,3];
- arr.unshift('foo');
- expect(arr[0]).to.equal('foo');
+ describe(".unshift()", function () {
+ it("should prepend a value", function () {
+ var arr = [1, 2, 3];
+ arr.unshift("foo");
+ expect(arr[0]).to.equal("foo");
expect(arr[1]).to.equal(1);
- })
+ });
- it('should return the length', function(){
+ it("should return the length", function () {
var arr = [];
- var n = arr.unshift('foo');
+ var n = arr.unshift("foo");
expect(n).to.equal(1);
- n = arr.unshift('bar');
+ n = arr.unshift("bar");
expect(n).to.equal(2);
- })
+ });
- describe('with many arguments', function(){
- it('should add the values', function(){
+ describe("with many arguments", function () {
+ it("should add the values", function () {
var arr = [];
- arr.unshift('foo', 'bar');
- expect(arr[0]).to.equal('foo');
- expect(arr[1]).to.equal('bar');
- })
- })
- })
+ arr.unshift("foo", "bar");
+ expect(arr[0]).to.equal("foo");
+ expect(arr[1]).to.equal("bar");
+ });
+ });
+ });
- describe('.pop()', function(){
- it('should remove and return the last value', function(){
- var arr = [1,2,3];
+ describe(".pop()", function () {
+ it("should remove and return the last value", function () {
+ var arr = [1, 2, 3];
expect(arr.pop()).to.equal(3);
expect(arr.pop()).to.equal(2);
expect(arr).to.have.length(1);
- })
- })
+ });
+ });
- describe('.shift()', function(){
- it('should remove and return the first value', function(){
- var arr = [1,2,3];
+ describe(".shift()", function () {
+ it("should remove and return the first value", function () {
+ var arr = [1, 2, 3];
expect(arr.shift()).to.equal(1);
expect(arr.shift()).to.equal(2);
expect(arr).to.have.length(1);
- })
- })
-})
-
+ });
+ });
+});
diff --git a/docs/example/async-dump.js b/docs/example/async-dump.js
index c1c15058..3544dcf4 100644
--- a/docs/example/async-dump.js
+++ b/docs/example/async-dump.js
@@ -1,7 +1,7 @@
-'use strict';
+"use strict";
-const {createHook} = require('async_hooks');
-const {stackTraceFilter} = require('mocha/lib/utils');
+const { createHook } = require("async_hooks");
+const { stackTraceFilter } = require("mocha/lib/utils");
const allResources = new Map();
const resourceActivity = new Set();
@@ -9,7 +9,11 @@ const filterStack = stackTraceFilter();
const hook = createHook({
init(asyncId, type, triggerAsyncId) {
- allResources.set(asyncId, {type, triggerAsyncId, stack: (new Error()).stack});
+ allResources.set(asyncId, {
+ type,
+ triggerAsyncId,
+ stack: new Error().stack,
+ });
},
before(asyncId) {
resourceActivity.add(asyncId);
@@ -19,15 +23,15 @@ const hook = createHook({
},
destroy(asyncId) {
allResources.delete(asyncId);
- }
+ },
}).enable();
global.asyncDump = module.exports = () => {
hook.disable();
- console.error('STUFF STILL IN THE EVENT LOOP:')
- allResources.forEach(value=> {
+ console.error("STUFF STILL IN THE EVENT LOOP:");
+ allResources.forEach((value) => {
console.error(`Type: ${value.type}`);
console.error(filterStack(value.stack));
- console.error('\n');
+ console.error("\n");
});
};
diff --git a/docs/example/debug-hanging-mocha.js b/docs/example/debug-hanging-mocha.js
index 92772ca0..594a9c17 100644
--- a/docs/example/debug-hanging-mocha.js
+++ b/docs/example/debug-hanging-mocha.js
@@ -1,9 +1,9 @@
-'use strict';
+"use strict";
-const net = require('net');
-const assert = require('assert');
+const net = require("net");
+const assert = require("assert");
-describe('how to debug Mocha when it hangs', function () {
+describe("how to debug Mocha when it hangs", function () {
before(function (done) {
const server = net.createServer();
server.listen(10101, done);
@@ -13,10 +13,10 @@ describe('how to debug Mocha when it hangs', function () {
global.asyncDump();
});
- it('should complete, but Mocha should not exit', function(done) {
+ it("should complete, but Mocha should not exit", function (done) {
const sock = net.createConnection(10101, () => {
- assert.deepStrictEqual(sock.address().family, 'IPv4');
+ assert.deepStrictEqual(sock.address().family, "IPv4");
done();
});
});
-});
\ No newline at end of file
+});
diff --git a/docs/example/tests.html b/docs/example/tests.html
index 24c1f8d6..53da8152 100644
--- a/docs/example/tests.html
+++ b/docs/example/tests.html
@@ -1,17 +1,21 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
- <meta charset="utf-8">
+ <meta charset="utf-8" />
<title>Mocha</title>
- <link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css">
- <link rel="shortcut icon" href="../favicon.ico">
+ <link rel="stylesheet" href="https://unpkg.com/mocha/mocha.css" />
+ <link rel="shortcut icon" href="../favicon.ico" />
</head>
<body>
<div id="mocha"></div>
<script src="https://unpkg.com/mocha/mocha.js"></script>
<script src="https://unpkg.com/[email protected]/chai.js"></script>
- <script>mocha.setup('bdd')</script>
- <script>expect = chai.expect</script>
+ <script>
+ mocha.setup("bdd");
+ </script>
+ <script>
+ expect = chai.expect;
+ </script>
<script src="Array.js"></script>
<script>
mocha.run();
diff --git a/docs/index.md b/docs/index.md
index 5d527b60..955327aa 100644
--- a/docs/index.md
+++ b/docs/index.md
@@ -1,7 +1,7 @@
---
layout: default
-title: 'Mocha - the fun, simple, flexible JavaScript test framework'
-description: 'Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun.'
+title: "Mocha - the fun, simple, flexible JavaScript test framework"
+description: "Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing simple and fun."
---
<div class="admonition">This site has a new look, try it out at <a href="next">mochajs.org/next</a>!</div>
@@ -80,10 +80,10 @@ $ $EDITOR test/test.js # or open with your favorite editor
In your editor:
```js
-var assert = require('assert');
-describe('Array', function () {
- describe('#indexOf()', function () {
- it('should return -1 when the value is not present', function () {
+var assert = require("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);
});
});
@@ -177,7 +177,7 @@ In a browser, test files are loaded by `<script>` tags, and calling `mocha.run()
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.
```javascript
-it('double done', function (done) {
+it("double done", function (done) {
// Calling `done()` twice is an error
setImmediate(done);
setImmediate(done);
@@ -220,10 +220,10 @@ Mocha allows you to use any assertion library you wish. In the above example, we
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).
```js
-describe('User', function () {
- describe('#save()', function () {
- it('should save without error', function (done) {
- var user = new User('Luna');
+describe("User", function () {
+ describe("#save()", function () {
+ it("should save without error", function (done) {
+ var user = new User("Luna");
user.save(function (err) {
if (err) done(err);
else done();
@@ -236,10 +236,10 @@ describe('User', function () {
Alternatively, use the `done()` callback directly (which will handle an error argument, if it exists):
```js
-describe('User', function () {
- describe('#save()', function () {
- it('should save without error', function (done) {
- var user = new User('Luna');
+describe("User", function () {
+ describe("#save()", function () {
+ it("should save without error", function (done) {
+ var user = new User("Luna");
user.save(done);
});
});
@@ -257,9 +257,9 @@ beforeEach(function () {
});
});
-describe('#find()', function () {
- it('respond with matching records', function () {
- return db.find({type: 'User'}).should.eventually.have.length(3);
+describe("#find()", function () {
+ it("respond with matching records", function () {
+ return db.find({ type: "User" }).should.eventually.have.length(3);
});
});
```
@@ -269,10 +269,10 @@ describe('#find()', function () {
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');
+const assert = require("assert");
// antipattern
-it('should complete this test', function (done) {
+it("should complete this test", function (done) {
return new Promise(function (resolve) {
assert.ok(true);
resolve();
@@ -292,9 +292,9 @@ beforeEach(async function () {
await db.save([tobi, loki, jane]);
});
-describe('#find()', function () {
- it('responds with matching records', async function () {
- const users = await db.find({type: 'User'});
+describe("#find()", function () {
+ it("responds with matching records", async function () {
+ const users = await db.find({ type: "User" });
users.should.have.length(3);
});
});
@@ -310,9 +310,9 @@ See [#5046](https://github.com/mochajs/mocha/pull/5046) for more information.
When testing synchronous code, omit the callback and Mocha will automatically continue on to the next test.
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
- it('should return -1 when the value is not present', function () {
+describe("Array", function () {
+ describe("#indexOf()", function () {
+ it("should return -1 when the value is not present", function () {
[1, 2, 3].indexOf(5).should.equal(-1);
[1, 2, 3].indexOf(0).should.equal(-1);
});
@@ -325,8 +325,8 @@ describe('Array', function () {
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:
```js
-describe('my suite', () => {
- it('my test', () => {
+describe("my suite", () => {
+ it("my test", () => {
// should set the timeout of this test to 1000 ms; instead will fail
this.timeout(1000);
assert.ok(true);
@@ -339,9 +339,9 @@ _If you do not need to use_ Mocha's context, lambdas should work. Be aware that
Alternatively, you can override certain context variables, such as test timeouts, by chain-calling methods of the created tests and/or hooks:
```js
-describe('my suite', () => {
+describe("my suite", () => {
beforeEach(() => {}).timeout(1000);
- it('my test', () => {
+ it("my test", () => {
assert.ok(true);
}).timeout(1000);
}).timeout(1000);
@@ -352,7 +352,7 @@ describe('my suite', () => {
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.
```js
-describe('hooks', function () {
+describe("hooks", function () {
before(function () {
// runs once before the first test in this block
});
@@ -388,7 +388,7 @@ beforeEach(function namedFun() {
// beforeEach:namedFun
});
-beforeEach('some description', function () {
+beforeEach("some description", function () {
// beforeEach:some description
});
```
@@ -398,11 +398,11 @@ beforeEach('some description', function () {
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:
```js
-describe('Connection', function () {
+describe("Connection", function () {
var db = new Connection(),
- tobi = new User('tobi'),
- loki = new User('loki'),
- jane = new User('jane');
+ tobi = new User("tobi"),
+ loki = new User("loki"),
+ jane = new User("jane");
beforeEach(function (done) {
db.clear(function (err) {
@@ -411,9 +411,9 @@ describe('Connection', function () {
});
});
- describe('#find()', function () {
- it('respond with matching records', function (done) {
- db.find({type: 'User'}, function (err, res) {
+ describe("#find()", function () {
+ it("respond with matching records", function (done) {
+ db.find({ type: "User" }, function (err, res) {
if (err) return done(err);
res.should.have.length(3);
done();
@@ -436,10 +436,10 @@ As of v8.0.0, [Root Hook Plugins] are the preferred mechanism for setting root h
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:
```js
-const assert = require('assert');
+const assert = require("assert");
-const fn = async x => {
- return new Promise(resolve => {
+const fn = async (x) => {
+ return new Promise((resolve) => {
setTimeout(resolve, 3000, 2 * x);
});
};
@@ -448,7 +448,7 @@ const fn = async x => {
(async function () {
const z = await fn(3);
- describe('my suite', function () {
+ describe("my suite", function () {
it(`expected value ${z}`, function () {
assert.strictEqual(z, 6);
});
@@ -463,10 +463,10 @@ const fn = async x => {
"Pending" — as in "someone should write these test cases eventually" — test-cases are those _without_ a callback:
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
+describe("Array", function () {
+ describe("#indexOf()", function () {
// pending test below
- it('should return -1 when the value is not present');
+ it("should return -1 when the value is not present");
});
});
```
@@ -483,8 +483,8 @@ The exclusivity feature allows you to run _only_ the specified suite or test-cas
by appending `.only()` to the function. Here's an example of executing only a particular suite:
```js
-describe('Array', function () {
- describe.only('#indexOf()', function () {
+describe("Array", function () {
+ describe.only("#indexOf()", function () {
// ...
});
});
@@ -495,13 +495,13 @@ _Note_: All nested suites will still be executed.
Here's an example of executing an individual test case:
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
- it.only('should return -1 unless present', function () {
+describe("Array", function () {
+ describe("#indexOf()", function () {
+ it.only("should return -1 unless present", function () {
// ...
});
- it('should return the index when present', function () {
+ it("should return the index when present", function () {
// ...
});
});
@@ -511,17 +511,17 @@ describe('Array', function () {
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:
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
- it.only('should return -1 unless present', function () {
+describe("Array", function () {
+ describe("#indexOf()", function () {
+ it.only("should return -1 unless present", function () {
// this test will be run
});
- it.only('should return the index when present', function () {
+ it.only("should return the index when present", function () {
// this test will also be run
});
- it('should return -1 if called with a non-Array context', function () {
+ it("should return -1 if called with a non-Array context", function () {
// this test will not be run
});
});
@@ -531,25 +531,25 @@ describe('Array', function () {
You may also choose multiple suites:
```js
-describe('Array', function () {
- describe.only('#indexOf()', function () {
- it('should return -1 unless present', function () {
+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 () {
+ 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 () {
+ 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 () {
+ describe("#slice()", function () {
+ it("should return a new Array", function () {
// this test will not be run
});
});
@@ -559,13 +559,13 @@ describe('Array', function () {
But _tests will have precedence_:
```js
-describe('Array', function () {
- describe.only('#indexOf()', function () {
- it.only('should return -1 unless present', function () {
+describe("Array", function () {
+ describe.only("#indexOf()", function () {
+ it.only("should return -1 unless present", function () {
// this test will be run
});
- it('should return the index when present', function () {
+ it("should return the index when present", function () {
// this test will not be run
});
});
@@ -581,13 +581,13 @@ _Note_: Hooks, if present, will still be executed.
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:
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
- it.skip('should return -1 unless present', function () {
+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 () {
+ it("should return the index when present", function () {
// this test will be run
});
});
@@ -597,9 +597,9 @@ describe('Array', function () {
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.
```js
-describe('Array', function () {
- describe.skip('#indexOf()', function () {
- it('should return -1 unless present', function () {
+describe("Array", function () {
+ describe.skip("#indexOf()", function () {
+ it("should return -1 unless present", function () {
// this test will not be run
});
});
@@ -657,7 +657,7 @@ before(function() {
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()`.
```js
-describe('outer', function () {
+describe("outer", function () {
before(function () {
this.skip();
});
@@ -666,7 +666,7 @@ describe('outer', function () {
// will be executed
});
- describe('inner', function () {
+ describe("inner", function () {
before(function () {
// will be skipped
});
@@ -691,18 +691,18 @@ This feature does re-run a failed test and its corresponding `beforeEach/afterEa
**NOTE**: Example below was written using Selenium webdriver (which [overwrites global Mocha hooks][selenium-webdriver-testing] for `Promise` chain).
```js
-describe('retries', function () {
+describe("retries", function () {
// Retry all tests in this suite up to 4 times
this.retries(4);
beforeEach(function () {
- browser.get('http://www.yahoo.com');
+ browser.get("http://www.yahoo.com");
});
- it('should succeed on the 3rd try', function () {
+ it("should succeed on the 3rd try", function () {
// Specify this test to only retry up to 2 times
this.retries(2);
- expect($('.foo').isDisplayed()).to.eventually.be.true;
+ expect($(".foo").isDisplayed()).to.eventually.be.true;
});
});
```
@@ -714,20 +714,20 @@ Given Mocha's use of function expressions to define suites and test cases, it's
Take the following example:
```js
-const assert = require('assert');
+const assert = require("assert");
function add(args) {
return args.reduce((prev, curr) => prev + curr, 0);
}
-describe('add()', function () {
+describe("add()", function () {
const tests = [
- {args: [1, 2], expected: 3},
- {args: [1, 2, 3], expected: 6},
- {args: [1, 2, 3, 4], expected: 10}
+ { args: [1, 2], expected: 3 },
+ { args: [1, 2, 3], expected: 6 },
+ { args: [1, 2, 3, 4], expected: 10 },
];
- tests.forEach(({args, expected}) => {
+ tests.forEach(({ args, expected }) => {
it(`correctly adds ${args.length} args`, function () {
const res = add(args);
assert.strictEqual(res, expected);
@@ -751,16 +751,16 @@ Tests added inside a `.forEach` handler often don't play well with editor plugin
Another way to parameterize tests is to generate them with a closure. This following example is equivalent to the one above:
```js
-describe('add()', function () {
- const testAdd = ({args, expected}) =>
+describe("add()", function () {
+ const testAdd = ({ args, expected }) =>
function () {
const res = add(args);
assert.strictEqual(res, expected);
};
- it('correctly adds 2 args', testAdd({args: [1, 2], expected: 3}));
- it('correctly adds 3 args', testAdd({args: [1, 2, 3], expected: 6}));
- it('correctly adds 4 args', testAdd({args: [1, 2, 3, 4], expected: 10}));
+ it("correctly adds 2 args", testAdd({ args: [1, 2], expected: 3 }));
+ it("correctly adds 3 args", testAdd({ args: [1, 2, 3], expected: 6 }));
+ it("correctly adds 4 args", testAdd({ args: [1, 2, 3, 4], expected: 10 }));
});
```
@@ -770,20 +770,20 @@ See also [`--delay`](#delayed-root-suite) for CommonJS modules without `top-leve
```js
// testfile.mjs
-import assert from 'assert';
+import assert from "assert";
// top-level await: Node >= v14.8.0 with ESM test file
-const tests = await new Promise(resolve => {
+const tests = await new Promise((resolve) => {
setTimeout(resolve, 5000, [
- {args: [1, 2], expected: 3},
- {args: [1, 2, 3], expected: 6},
- {args: [1, 2, 3, 4], expected: 10}
+ { args: [1, 2], expected: 3 },
+ { args: [1, 2, 3], expected: 6 },
+ { args: [1, 2, 3, 4], expected: 10 },
]);
});
// in suites ASYNCHRONOUS callbacks are NOT supported
-describe('add()', function () {
- tests.forEach(({args, expected}) => {
+describe("add()", function () {
+ tests.forEach(({ args, expected }) => {
it(`correctly adds ${args.length} args`, function () {
const res = args.reduce((sum, curr) => sum + curr, 0);
assert.strictEqual(res, expected);
@@ -809,10 +809,10 @@ There are three levels of test duration (depicted in the following image):
To tweak what's considered "slow", you can use the `slow()` method:
```js
-describe('something slow', function () {
+describe("something slow", function () {
this.slow(300000); // five minutes
- it('should take long enough for me to go make a sandwich', function () {
+ it("should take long enough for me to go make a sandwich", function () {
// ...
});
});
@@ -825,14 +825,14 @@ describe('something slow', function () {
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.
```js
-describe('a suite of tests', function () {
+describe("a suite of tests", function () {
this.timeout(500);
- it('should take less than 500ms', function (done) {
+ it("should take less than 500ms", function (done) {
setTimeout(done, 300);
});
- it('should take less than 500ms as well', function (done) {
+ it("should take less than 500ms as well", function (done) {
setTimeout(done, 250);
});
});
@@ -843,7 +843,7 @@ describe('a suite of tests', function () {
Test-specific timeouts may also be applied, or the use of `this.timeout(0)` to disable timeouts all together:
```js
-it('should take less than 500ms', function (done) {
+it("should take less than 500ms", function (done) {
this.timeout(500);
setTimeout(done, 300);
});
@@ -854,7 +854,7 @@ it('should take less than 500ms', function (done) {
Hook-level timeouts may also be applied:
```js
-describe('a suite of tests', function () {
+describe("a suite of tests", function () {
beforeEach(function (done) {
this.timeout(3000); // A very long environment setup.
setTimeout(done, 2500);
@@ -1202,17 +1202,17 @@ And another option with double quotes: `--grep "groupA|groupB"`.
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.
```js
-describe('api', function () {
- describe('GET /api/users groupA', function () {
- it('respond with an array of users', function () {
+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 () {
+describe("app", function () {
+ describe("GET /users groupB", function () {
+ it("respond with an array of users", function () {
// ...
});
});
@@ -1458,7 +1458,7 @@ exports.mochaHooks = {
beforeEach(done) {
// do something before every test
done();
- }
+ },
};
```
@@ -1475,7 +1475,7 @@ export const mochaHooks = {
beforeEach(done) {
// do something before every test
done();
- }
+ },
};
```
@@ -1510,10 +1510,10 @@ As with other hooks, `this` refers to the current context object:
export const mochaHooks = {
beforeAll() {
// skip all tests for bob
- if (require('os').userInfo().username === 'bob') {
+ if (require("os").userInfo().username === "bob") {
return this.skip();
}
- }
+ },
};
```
@@ -1532,8 +1532,8 @@ export const mochaHooks = {
},
async function () {
// async or Promise-returning functions allowed
- }
- ]
+ },
+ ],
};
```
@@ -1554,15 +1554,15 @@ export const mochaHooks = () => {
},
function () {
// some other CI-specific beforeEach
- }
- ]
+ },
+ ],
};
}
// root hooks object
return {
beforeEach() {
// regular beforeEach
- }
+ },
};
};
```
@@ -1580,7 +1580,7 @@ export const mochaHooks = async () => {
return {
beforeEach() {
// something
- }
+ },
};
}
};
@@ -1613,8 +1613,8 @@ after(function () {
// one-time final cleanup
});
-describe('my test suite', function () {
- it('should have run my global setup', function () {
+describe("my test suite", function () {
+ it("should have run my global setup", function () {
// make assertion
});
});
@@ -1631,7 +1631,7 @@ exports.mochaHooks = {
},
afterAll: function () {
// one-time final cleanup
- }
+ },
};
```
@@ -1642,8 +1642,8 @@ Your original `test/test.spec.js` should now contain:
```js
// test/test.spec.js
-describe('my test suite', function () {
- it('should have run my global setup', function () {
+describe("my test suite", function () {
+ it("should have run my global setup", function () {
// make assertion
});
});
@@ -1680,7 +1680,7 @@ To create a global setup fixture, export `mochaGlobalSetup` from a script, e.g.,
// can be async or not
exports.mochaGlobalSetup = async function () {
- this.server = await startSomeServer({port: process.env.TEST_PORT});
+ this.server = await startSomeServer({ port: process.env.TEST_PORT });
console.log(`server running on port ${this.server.port}`);
};
```
@@ -1692,7 +1692,7 @@ exports.mochaGlobalSetup = async function () {
// can be async or not
export async function mochaGlobalSetup() {
- this.server = await startSomeServer({port: process.env.TEST_PORT});
+ this.server = await startSomeServer({ port: process.env.TEST_PORT });
console.log(`server running on port ${this.server.port}`);
}
```
@@ -1713,7 +1713,7 @@ Just like a [global setup fixture](#global-setup-fixtures), a _global teardown f
// can be async or not
exports.mochaGlobalTeardown = async function () {
await this.server.stop();
- console.log('server stopped!');
+ console.log("server stopped!");
};
```
@@ -1725,7 +1725,7 @@ exports.mochaGlobalTeardown = async function () {
// can be async or not
export async function mochaGlobalTeardown() {
await this.server.stop();
- console.log('server stopped!');
+ console.log("server stopped!");
}
```
@@ -1755,13 +1755,13 @@ First, use a global fixture to start and stop a test server:
let server;
export const mochaGlobalSetup = async () => {
- server = await startSomeServer({port: process.env.TEST_PORT});
+ 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!');
+ console.log("server stopped!");
};
```
@@ -1770,16 +1770,16 @@ Then, connect to the server in your tests:
```js
// test.spec.mjs
-import {connect} from 'my-server-connector-thingy';
+import { connect } from "my-server-connector-thingy";
-describe('my API', function () {
+describe("my API", function () {
let connection;
before(async function () {
- connection = await connect({port: process.env.TEST_PORT});
+ connection = await connect({ port: process.env.TEST_PORT });
});
- it('should be a nice API', function () {
+ it("should be a nice API", function () {
// assertions here
});
@@ -1811,24 +1811,24 @@ The **BDD** interface provides `describe()`, `context()`, `it()`, `specify()`, `
> All of the previous examples were written using the **BDD** interface.
```js
-describe('Array', function () {
+describe("Array", function () {
before(function () {
// ...
});
- describe('#indexOf()', function () {
- context('when not present', function () {
- it('should not throw an error', 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 () {
+ 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 () {
+ 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);
});
});
@@ -1841,13 +1841,13 @@ describe('Array', function () {
The **TDD** interface provides `suite()`, `test()`, `suiteSetup()`, `suiteTeardown()`, `setup()`, and `teardown()`:
```js
-suite('Array', function () {
+suite("Array", function () {
setup(function () {
// ...
});
- suite('#indexOf()', function () {
- test('should return -1 when not present', function () {
+ suite("#indexOf()", function () {
+ test("should return -1 when not present", function () {
assert.equal(-1, [1, 2, 3].indexOf(4));
});
});
@@ -1869,12 +1869,12 @@ module.exports = {
},
Array: {
- '#indexOf()': {
- 'should return -1 when not present': function () {
+ "#indexOf()": {
+ "should return -1 when not present": function () {
[1, 2, 3].indexOf(4).should.equal(-1);
- }
- }
- }
+ },
+ },
+ },
};
```
@@ -1887,24 +1887,24 @@ function ok(expr, msg) {
if (!expr) throw new Error(msg);
}
-suite('Array');
+suite("Array");
-test('#length', function () {
+test("#length", function () {
var arr = [1, 2, 3];
ok(arr.length == 3);
});
-test('#indexOf()', function () {
+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');
+suite("String");
-test('#length', function () {
- ok('foo'.length == 3);
+test("#length", function () {
+ ok("foo".length == 3);
});
```
@@ -1915,18 +1915,18 @@ The `require` interface allows you to require the `describe` and friend words di
_Note_: The `require` interface cannot be run via the `node` executable, and must be run via `mocha`.
```js
-var testCase = require('mocha').describe;
-var pre = require('mocha').before;
-var assertions = require('mocha').it;
-var assert = require('chai').assert;
+var testCase = require("mocha").describe;
+var pre = require("mocha").before;
+var assertions = require("mocha").it;
+var assert = require("chai").assert;
-testCase('Array', function () {
+testCase("Array", function () {
pre(function () {
// ...
});
- testCase('#indexOf()', function () {
- assertions('should return -1 when not present', function () {
+ testCase("#indexOf()", function () {
+ assertions("should return -1 when not present", function () {
assert.equal([1, 2, 3].indexOf(4), -1);
});
});
@@ -2032,9 +2032,9 @@ The Doc reporter outputs a hierarchical HTML body representation of your tests.
For example, suppose you have the following JavaScript:
```js
-describe('Array', function () {
- describe('#indexOf()', function () {
- it('should return -1 when the value is not present', function () {
+describe("Array", function () {
+ describe("#indexOf()", function () {
+ it("should return -1 when the value is not present", function () {
[1, 2, 3].indexOf(5).should.equal(-1);
[1, 2, 3].indexOf(0).should.equal(-1);
});
@@ -2114,10 +2114,10 @@ Mocha supports writing your tests as ES modules, and not just using CommonJS. Fo
```js
// test.mjs
-import {add} from './add.mjs';
-import assert from 'assert';
+import { add } from "./add.mjs";
+import assert from "assert";
-it('should add to numbers from an es module', () => {
+it("should add to numbers from an es module", () => {
assert.equal(add(3, 5), 8);
});
```
@@ -2161,7 +2161,7 @@ A typical setup might look something like the following, where we call `mocha.se
<script src="https://unpkg.com/mocha/mocha.js"></script>
<script class="mocha-init">
- mocha.setup('bdd');
+ mocha.setup("bdd");
mocha.checkLeaks();
</script>
<script src="test.array.js"></script>
@@ -2425,7 +2425,7 @@ spies, mocking, and shared behaviours be sure to check out the [Mocha Wiki][moch
For a running example of Mocha, view [example/tests.html](example/tests.html). For the JavaScript API, view the [API documentation](api/)
or the [source](https://github.com/mochajs/mocha/blob/main/lib/mocha.js).
-[//]: # 'Cross reference section'
+[//]: # "Cross reference section"
[bash-globbing]: https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html
[better-assert]: https://github.com/visionmedia/better-assert
[caniuse-notifications]: https://caniuse.com/#feat=notifications
diff --git a/eslint.config.js b/eslint.config.js
index 93aec09a..10d4ad13 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -1,177 +1,181 @@
"use strict";
-const js = require('@eslint/js');
-const n = require('eslint-plugin-n');
-const globals = require('globals');
+const js = require("@eslint/js");
+const n = require("eslint-plugin-n");
+const globals = require("globals");
const messages = {
- gh237: 'See https://github.com/mochajs/mocha/issues/237',
- gh3604: 'See https://github.com/mochajs/mocha/issues/3604'
+ gh237: "See https://github.com/mochajs/mocha/issues/237",
+ gh3604: "See https://github.com/mochajs/mocha/issues/3604",
};
module.exports = [
- n.configs['flat/recommended-script'],
+ n.configs["flat/recommended-script"],
{
...js.configs.recommended,
languageOptions: {
ecmaVersion: 2020,
globals: {
...globals.browser,
- ...globals.node
+ ...globals.node,
},
- sourceType: 'script'
+ sourceType: "script",
},
rules: {
- 'n/prefer-node-protocol': 'error',
- 'no-unused-vars': 'error',
- strict: ['error', 'global'],
+ "n/prefer-node-protocol": "error",
+ "no-unused-vars": "error",
+ strict: ["error", "global"],
- 'no-var': 'off',
- 'n/no-process-exit': 'off',
- 'n/no-unpublished-require': 'off',
- 'n/no-unsupported-features/node-builtins': 'off',
- }
+ "no-var": "off",
+ "n/no-process-exit": "off",
+ "n/no-unpublished-require": "off",
+ "n/no-unsupported-features/node-builtins": "off",
+ },
},
{
- files: ['docs/js/**/*.js'],
+ files: ["docs/js/**/*.js"],
languageOptions: {
- globals: globals.browser
- }
+ globals: globals.browser,
+ },
},
{
files: [
- '.eleventy.js',
- '.wallaby.js',
- 'package-scripts.js',
- 'karma.conf.js',
- 'bin/*',
- 'docs/_data/**/*.js',
- 'lib/cli/**/*.js',
- 'lib/nodejs/**/*.js',
- 'scripts/**/*.{js,mjs}',
- 'test/**/*.{js,mjs}',
- 'test/node-unit/**/*.js'
+ ".eleventy.js",
+ ".wallaby.js",
+ "package-scripts.js",
+ "karma.conf.js",
+ "bin/*",
+ "docs/_data/**/*.js",
+ "lib/cli/**/*.js",
+ "lib/nodejs/**/*.js",
+ "scripts/**/*.{js,mjs}",
+ "test/**/*.{js,mjs}",
+ "test/node-unit/**/*.js",
],
languageOptions: {
globals: globals.node,
ecmaVersion: 2020,
- }
+ },
},
{
files: [
- 'lib/nodejs/esm-utils.js',
- 'rollup.config.js',
- 'scripts/*.mjs',
- 'scripts/pick-from-package-json.js',
- 'test/compiler-cjs/test.js'
+ "lib/nodejs/esm-utils.js",
+ "rollup.config.js",
+ "scripts/*.mjs",
+ "scripts/pick-from-package-json.js",
+ "test/compiler-cjs/test.js",
],
languageOptions: {
- sourceType: 'module'
- }
+ sourceType: "module",
+ },
},
{
- files: [
- 'test/compiler-esm/*.{js,mjs}'
- ],
+ files: ["test/compiler-esm/*.{js,mjs}"],
languageOptions: {
- sourceType: 'module',
+ sourceType: "module",
// For top-level await support.
ecmaVersion: 2022,
- }
+ },
},
{
- files: ['test/**/*.{js,mjs}'],
+ files: ["test/**/*.{js,mjs}"],
languageOptions: {
globals: {
...globals.browser,
...globals.mocha,
...globals.node,
- expect: 'readonly'
- }
- }
+ expect: "readonly",
+ },
+ },
},
{
- files: ['test/**/*.mjs'],
+ files: ["test/**/*.mjs"],
languageOptions: {
- sourceType: "module"
+ sourceType: "module",
},
},
{
- files: ['bin/*', 'lib/**/*.js'],
+ files: ["bin/*", "lib/**/*.js"],
rules: {
- 'no-restricted-globals': [
- 'error',
+ "no-restricted-globals": [
+ "error",
{
message: messages.gh237,
- name: 'setTimeout'
+ name: "setTimeout",
},
{
message: messages.gh237,
- name: 'clearTimeout'
+ name: "clearTimeout",
},
{
message: messages.gh237,
- name: 'setInterval'
+ name: "setInterval",
},
{
message: messages.gh237,
- name: 'clearInterval'
+ name: "clearInterval",
},
{
message: messages.gh237,
- name: 'setImmediate'
+ name: "setImmediate",
},
{
message: messages.gh237,
- name: 'clearImmediate'
+ name: "clearImmediate",
},
{
message: messages.gh237,
- name: 'Date'
- }
+ name: "Date",
+ },
],
- 'no-restricted-modules': ['error', 'timers'],
- "no-restricted-syntax": ['error',
+ "no-restricted-modules": ["error", "timers"],
+ "no-restricted-syntax": [
+ "error",
// disallow `global.setTimeout()`, `global.setInterval()`, etc.
{
message: messages.gh237,
- selector: 'CallExpression[callee.object.name=global][callee.property.name=/(set|clear)(Timeout|Immediate|Interval)/]'
+ selector:
+ "CallExpression[callee.object.name=global][callee.property.name=/(set|clear)(Timeout|Immediate|Interval)/]",
},
// disallow `new global.Date()`
{
message: messages.gh237,
- selector: 'NewExpression[callee.object.name=global][callee.property.name=Date]'
+ selector:
+ "NewExpression[callee.object.name=global][callee.property.name=Date]",
},
// disallow property access of `global.<timer>.*`
{
message: messages.gh237,
- selector: '*[object.object.name=global][object.property.name=/(Date|(set|clear)(Timeout|Immediate|Interval))/]:expression'
- }
- ]
- }
+ selector:
+ "*[object.object.name=global][object.property.name=/(Date|(set|clear)(Timeout|Immediate|Interval))/]:expression",
+ },
+ ],
+ },
},
{
- files: ['lib/reporters/*.js'],
+ files: ["lib/reporters/*.js"],
rules: {
- 'no-restricted-syntax': ['error',
+ "no-restricted-syntax": [
+ "error",
// disallow Reporters using `console.log()`
{
message: messages.gh3604,
- selector: 'CallExpression[callee.object.name=console][callee.property.name=log]'
- }
- ]
- }
+ selector:
+ "CallExpression[callee.object.name=console][callee.property.name=log]",
+ },
+ ],
+ },
},
{
ignores: [
- '**/*.{fixture,min}.{js,mjs}',
- 'coverage/**',
- 'docs/{_dist,_site,api,example}/**',
- 'docs-next/dist/**',
- 'out/**',
- 'test/integration/fixtures/**',
- '.karma/**',
- 'mocha.js'
+ "**/*.{fixture,min}.{js,mjs}",
+ "coverage/**",
+ "docs/{_dist,_site,api,example}/**",
+ "docs-next/dist/**",
+ "out/**",
+ "test/integration/fixtures/**",
+ ".karma/**",
+ "mocha.js",
],
- }
+ },
];
diff --git a/example/config/.mocharc.js b/example/config/.mocharc.js
index e40bea1b..a97a793e 100644
--- a/example/config/.mocharc.js
+++ b/example/config/.mocharc.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
// This is a JavaScript-based config file containing every Mocha option plus others.
// If you need conditional logic, you might want to use this type of config,
@@ -6,45 +6,45 @@
// Otherwise, JSON or YAML is recommended.
module.exports = {
- 'allow-uncaught': false,
- 'async-only': false,
+ "allow-uncaught": false,
+ "async-only": false,
bail: false,
- 'check-leaks': false,
+ "check-leaks": false,
color: true,
delay: false,
diff: true,
exit: false, // could be expressed as "'no-exit': true"
- extension: ['js', 'cjs', 'mjs'],
- 'fail-zero': true,
- fgrep: 'something', // fgrep and grep are mutually exclusive
- file: ['/path/to/some/file', '/path/to/some/other/file'],
- 'forbid-only': false,
- 'forbid-pending': false,
- 'full-trace': false,
- global: ['jQuery', '$'],
+ extension: ["js", "cjs", "mjs"],
+ "fail-zero": true,
+ fgrep: "something", // fgrep and grep are mutually exclusive
+ file: ["/path/to/some/file", "/path/to/some/other/file"],
+ "forbid-only": false,
+ "forbid-pending": false,
+ "full-trace": false,
+ global: ["jQuery", "$"],
grep: /something/i, // also 'something', fgrep and grep are mutually exclusive
growl: false,
- ignore: ['/path/to/some/ignored/file'],
- 'inline-diffs': false,
+ ignore: ["/path/to/some/ignored/file"],
+ "inline-diffs": false,
// invert: false, // needs to be used with grep or fgrep
jobs: 1,
- 'node-option': ['unhandled-rejections=strict'], // without leading "--", also V8 flags
- package: './package.json',
+ "node-option": ["unhandled-rejections=strict"], // without leading "--", also V8 flags
+ package: "./package.json",
parallel: false,
recursive: false,
- reporter: 'spec',
- 'reporter-option': ['foo=bar', 'baz=quux'], // array, not object
- require: '@babel/register',
+ reporter: "spec",
+ "reporter-option": ["foo=bar", "baz=quux"], // array, not object
+ require: "@babel/register",
retries: 1,
- slow: '75',
+ slow: "75",
sort: false,
- spec: ['test/**/*.spec.js'], // the positional arguments!
- timeout: '2000', // same as "timeout: '2s'"
+ spec: ["test/**/*.spec.js"], // the positional arguments!
+ timeout: "2000", // same as "timeout: '2s'"
// timeout: false, // same as "timeout: 0"
- 'trace-warnings': true, // node flags ok
- ui: 'bdd',
- 'v8-stack-trace-limit': 100, // V8 flags are prepended with "v8-"
+ "trace-warnings": true, // node flags ok
+ ui: "bdd",
+ "v8-stack-trace-limit": 100, // V8 flags are prepended with "v8-"
watch: false,
- 'watch-files': ['lib/**/*.js', 'test/**/*.js'],
- 'watch-ignore': ['lib/vendor']
+ "watch-files": ["lib/**/*.js", "test/**/*.js"],
+ "watch-ignore": ["lib/vendor"],
};
diff --git a/example/config/.mocharc.jsonc b/example/config/.mocharc.jsonc
index 362aee2e..ff23db17 100644
--- a/example/config/.mocharc.jsonc
+++ b/example/config/.mocharc.jsonc
@@ -4,12 +4,12 @@
// project's `package.json`.
{
"diff": true,
- "extension": ["js","cjs","mjs"],
+ "extension": ["js", "cjs", "mjs"],
"package": /* 📦 */ "./package.json",
"reporter": /* 📋 */ "spec",
"slow": "75",
"timeout": "2000",
"ui": "bdd",
"watch-files": ["lib/**/*.js", "test/**/*.js"],
- "watch-ignore": ["lib/vendor"]
+ "watch-ignore": ["lib/vendor"],
}
diff --git a/example/config/.mocharc.yml b/example/config/.mocharc.yml
index e132b7a9..16709814 100644
--- a/example/config/.mocharc.yml
+++ b/example/config/.mocharc.yml
@@ -7,51 +7,51 @@ color: true
delay: false
diff: true
exit: false # could be expressed as "no-exit: true"
-extension: ['js', 'cjs', 'mjs']
+extension: ["js", "cjs", "mjs"]
fail-zero: true
# fgrep and grep are mutually exclusive
-fgrep: 'something'
+fgrep: "something"
file:
- - '/path/to/some/file'
- - '/path/to/some/other/file'
+ - "/path/to/some/file"
+ - "/path/to/some/other/file"
forbid-only: false
forbid-pending: false
full-trace: false
global:
- - 'jQuery'
- - '$'
+ - "jQuery"
+ - "$"
# fgrep and grep are mutually exclusive
-grep: '/something/i' # also 'something'
+grep: "/something/i" # also 'something'
growl: false
ignore:
- - '/path/to/some/ignored/file'
+ - "/path/to/some/ignored/file"
inline-diffs: false
# needs to be used with grep or fgrep
# invert: false
jobs: 1
node-option:
- - 'unhandled-rejections=strict' # without leading "--", also V8 flags
-package: './package.json'
+ - "unhandled-rejections=strict" # without leading "--", also V8 flags
+package: "./package.json"
parallel: false
recursive: false
-reporter: 'spec'
+reporter: "spec"
reporter-option: # array, not object
- - 'foo=bar'
- - 'baz=quux'
-require: '@babel/register'
+ - "foo=bar"
+ - "baz=quux"
+require: "@babel/register"
retries: 1
-slow: '75'
+slow: "75"
sort: false
spec:
- - 'test/**/*.spec.js' # the positional arguments!
-timeout: '2000' # same as "timeout: '2s'"
+ - "test/**/*.spec.js" # the positional arguments!
+timeout: "2000" # same as "timeout: '2s'"
# timeout: false # same as "timeout: 0"
trace-warnings: true # node flags ok
-ui: 'bdd'
+ui: "bdd"
v8-stack-trace-limit: 100 # V8 flags are prepended with "v8-"
watch: false
watch-files:
- - 'lib/**/*.js'
- - 'test/**/*.js'
+ - "lib/**/*.js"
+ - "test/**/*.js"
watch-ignore:
- - 'lib/vendor'
+ - "lib/vendor"
diff --git a/index.js b/index.js
index d2b7d196..6c972d99 100644
--- a/index.js
+++ b/index.js
@@ -1,3 +1,3 @@
-'use strict';
+"use strict";
-module.exports = require('./lib/mocha');
+module.exports = require("./lib/mocha");
diff --git a/karma.conf.js b/karma.conf.js
index 93704e04..fd7414f6 100644
--- a/karma.conf.js
+++ b/karma.conf.js
@@ -20,64 +20,64 @@
* configuration we've built.
*/
-'use strict';
-const fs = require('node:fs');
-const path = require('node:path');
-const os = require('node:os');
-const rollupPlugin = require('./scripts/karma-rollup-plugin');
-const BASE_BUNDLE_DIR_PATH = path.join(__dirname, '.karma');
+"use strict";
+const fs = require("node:fs");
+const path = require("node:path");
+const os = require("node:os");
+const rollupPlugin = require("./scripts/karma-rollup-plugin");
+const BASE_BUNDLE_DIR_PATH = path.join(__dirname, ".karma");
const env = process.env;
const hostname = os.hostname();
const BROWSER = env.BROWSER;
const SAUCE_BROWSER_PLATFORM_MAP = {
- 'chrome@latest': 'Windows 10',
- 'MicrosoftEdge@latest': 'Windows 10',
- 'firefox@latest': 'Windows 10',
- 'safari@latest': 'macOS 10.15'
+ "chrome@latest": "Windows 10",
+ "MicrosoftEdge@latest": "Windows 10",
+ "firefox@latest": "Windows 10",
+ "safari@latest": "macOS 10.15",
};
const baseConfig = {
- frameworks: ['rollup', 'mocha'],
+ frameworks: ["rollup", "mocha"],
files: [
// we use the BDD interface for all of the tests that
// aren't interface-specific.
- 'test/unit/*.spec.js'
+ "test/unit/*.spec.js",
],
plugins: [
- 'karma-mocha',
- 'karma-mocha-reporter',
- 'karma-sauce-launcher',
- 'karma-chrome-launcher',
- rollupPlugin
+ "karma-mocha",
+ "karma-mocha-reporter",
+ "karma-sauce-launcher",
+ "karma-chrome-launcher",
+ rollupPlugin,
],
rollup: {
- configFile: 'rollup.config.js',
- include: ['test/**']
+ configFile: "rollup.config.js",
+ include: ["test/**"],
},
- reporters: ['mocha'],
+ reporters: ["mocha"],
colors: true,
- browsers: ['ChromeHeadless'],
+ browsers: ["ChromeHeadless"],
client: {
mocha: {
// this helps debug
- reporter: 'html'
- }
+ reporter: "html",
+ },
},
mochaReporter: {
- showDiff: true
+ showDiff: true,
},
customLaunchers: {
ChromeDebug: {
- base: 'Chrome',
- flags: ['--remote-debugging-port=9333']
- }
- }
+ base: "Chrome",
+ flags: ["--remote-debugging-port=9333"],
+ },
+ },
};
-module.exports = config => {
+module.exports = (config) => {
let bundleDirPath = path.join(BASE_BUNDLE_DIR_PATH, hostname);
- let cfg = {...baseConfig};
+ let cfg = { ...baseConfig };
// TO RUN AGAINST SAUCELABS LOCALLY, execute:
// `CI=1 SAUCE_USERNAME=<user> SAUCE_ACCESS_KEY=<key> npm run test-browser`
@@ -85,13 +85,13 @@ module.exports = config => {
// configuration for CI mode
if (env.CI) {
- console.error('CI mode enabled');
+ console.error("CI mode enabled");
if (env.GITHUB_RUN_ID) {
- console.error('Github Actions detected');
+ console.error("Github Actions detected");
const buildId = `github-${env.GITHUB_RUN_ID}_${env.GITHUB_RUN_NUMBER}`;
bundleDirPath = path.join(BASE_BUNDLE_DIR_PATH, buildId);
sauceConfig = {
- build: buildId
+ build: buildId,
};
} else {
console.error(`Local environment (${hostname}) detected`);
@@ -100,12 +100,12 @@ module.exports = config => {
const id = `${hostname} (${Date.now()})`;
sauceConfig = {
build: id,
- tunnelIdentifier: id
+ tunnelIdentifier: id,
};
- console.error('Configured SauceLabs');
+ console.error("Configured SauceLabs");
} else {
console.error(
- 'No SauceLabs credentials present; set SAUCE_USERNAME and SAUCE_ACCESS_KEY env vars'
+ "No SauceLabs credentials present; set SAUCE_USERNAME and SAUCE_ACCESS_KEY env vars",
);
}
}
@@ -118,13 +118,13 @@ module.exports = config => {
// include sourcemap
cfg = {
...cfg,
- files: [...cfg.files, {pattern: './mocha.js.map', included: false}]
+ files: [...cfg.files, { pattern: "./mocha.js.map", included: false }],
};
if (BROWSER) {
cfg = {
...cfg,
- browsers: [BROWSER]
+ browsers: [BROWSER],
};
}
@@ -143,21 +143,21 @@ module.exports = config => {
const createBundleDir = (cfg, bundleDirPath) => {
if (bundleDirPath) {
try {
- fs.mkdirSync(bundleDirPath, {recursive: true});
+ fs.mkdirSync(bundleDirPath, { recursive: true });
cfg = {
...cfg,
rollup: {
...cfg.rollup,
- bundleDirPath
- }
+ bundleDirPath,
+ },
};
} catch (ignored) {
console.error(
- `Failed to create ${bundleDirPath}; using temp directory instead`
+ `Failed to create ${bundleDirPath}; using temp directory instead`,
);
}
}
- return {...cfg};
+ return { ...cfg };
};
/**
@@ -178,40 +178,40 @@ const addSauceTests = (cfg, sauceLabs) => {
// creates Karma `customLauncher` configs from `SAUCE_BROWSER_PLATFORM_MAP`
const customLaunchers = sauceBrowsers.reduce((acc, sauceBrowser) => {
const platformName = SAUCE_BROWSER_PLATFORM_MAP[sauceBrowser];
- const [browserName, browserVersion] = sauceBrowser.split('@');
+ const [browserName, browserVersion] = sauceBrowser.split("@");
const result = {
...acc,
[sauceBrowser]: {
- base: 'SauceLabs',
+ base: "SauceLabs",
browserName,
browserVersion,
platformName,
- 'sauce:options': sauceLabs
- }
+ "sauce:options": sauceLabs,
+ },
};
- if (browserName === 'firefox') {
- result[sauceBrowser]['sauce:options']['moz:debuggerAddress'] = true;
+ if (browserName === "firefox") {
+ result[sauceBrowser]["sauce:options"]["moz:debuggerAddress"] = true;
}
return result;
}, {});
const result = {
...cfg,
- reporters: [...cfg.reporters, 'saucelabs'],
+ reporters: [...cfg.reporters, "saucelabs"],
browsers: [...cfg.browsers, ...sauceBrowsers],
customLaunchers: {
...cfg.customLaunchers,
- ...customLaunchers
+ ...customLaunchers,
},
sauceLabs,
concurrency: Infinity,
retryLimit: 1,
captureTimeout: 120000,
- browserNoActivityTimeout: 20000
+ browserNoActivityTimeout: 20000,
};
return result;
}
- return {...cfg};
+ return { ...cfg };
};
/**
@@ -221,35 +221,35 @@ const addSauceTests = (cfg, sauceLabs) => {
* @param {object} cfg - Karma config
* @returns {object} New Karma config
*/
-const addStandardDependencies = cfg => ({
+const addStandardDependencies = (cfg) => ({
...cfg,
files: [
- require.resolve('sinon/pkg/sinon.js'),
- require.resolve('unexpected/unexpected'),
+ require.resolve("sinon/pkg/sinon.js"),
+ require.resolve("unexpected/unexpected"),
{
- pattern: require.resolve('unexpected/unexpected.js.map'),
- included: false
+ pattern: require.resolve("unexpected/unexpected.js.map"),
+ included: false,
},
- require.resolve('unexpected-sinon'),
- require.resolve('unexpected-eventemitter/dist/unexpected-eventemitter.js'),
- require.resolve('./test/browser-specific/setup'),
- ...cfg.files
+ require.resolve("unexpected-sinon"),
+ require.resolve("unexpected-eventemitter/dist/unexpected-eventemitter.js"),
+ require.resolve("./test/browser-specific/setup"),
+ ...cfg.files,
],
rollup: {
...cfg.rollup,
external: [
- 'sinon',
- 'unexpected',
- 'unexpected-eventemitter',
- 'unexpected-sinon'
+ "sinon",
+ "unexpected",
+ "unexpected-eventemitter",
+ "unexpected-sinon",
],
globals: {
- sinon: 'sinon',
- unexpected: 'weknowhow.expect',
- 'unexpected-sinon': 'weknowhow.unexpectedSinon',
- 'unexpected-eventemitter': 'unexpectedEventEmitter'
- }
- }
+ sinon: "sinon",
+ unexpected: "weknowhow.expect",
+ "unexpected-sinon": "weknowhow.unexpectedSinon",
+ "unexpected-eventemitter": "unexpectedEventEmitter",
+ },
+ },
});
/**
@@ -269,10 +269,10 @@ const addSauceLabsTestName = (testName, cfg) =>
...cfg,
sauceLabs: {
...cfg.sauceLabs,
- testName
- }
+ testName,
+ },
}
- : {...cfg};
+ : { ...cfg };
/**
* Returns a new Karma config to run with specific configuration (which cannot
@@ -291,9 +291,9 @@ const addSauceLabsTestName = (testName, cfg) =>
*/
const chooseTestSuite = (cfg, value) => {
switch (value) {
- case 'bdd':
- case 'tdd':
- case 'qunit':
+ case "bdd":
+ case "tdd":
+ case "qunit":
return addStandardDependencies({
...cfg,
...addSauceLabsTestName(`Interface "${value}" Integration Tests`, cfg),
@@ -302,27 +302,27 @@ const chooseTestSuite = (cfg, value) => {
...cfg.client,
mocha: {
...cfg.client.mocha,
- ui: value
- }
- }
+ ui: value,
+ },
+ },
});
- case 'esm':
+ case "esm":
return addStandardDependencies({
- ...addSauceLabsTestName('ESM Integration Tests', cfg),
+ ...addSauceLabsTestName("ESM Integration Tests", cfg),
files: [
{
- pattern: 'test/browser-specific/fixtures/esm.fixture.mjs',
- type: 'module'
+ pattern: "test/browser-specific/fixtures/esm.fixture.mjs",
+ type: "module",
},
{
- pattern: 'test/browser-specific/esm.spec.mjs',
- type: 'module'
- }
- ]
+ pattern: "test/browser-specific/esm.spec.mjs",
+ type: "module",
+ },
+ ],
});
default:
return addStandardDependencies({
- ...addSauceLabsTestName('Unit Tests', cfg)
+ ...addSauceLabsTestName("Unit Tests", cfg),
});
}
};
diff --git a/lib/browser/highlight-tags.js b/lib/browser/highlight-tags.js
index d98896e7..3f2dca46 100644
--- a/lib/browser/highlight-tags.js
+++ b/lib/browser/highlight-tags.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Highlight the given string of `js`.
@@ -9,19 +9,19 @@
*/
function highlight(js) {
return js
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
+ .replace(/</g, "&lt;")
+ .replace(/>/g, "&gt;")
.replace(/\/\/(.*)/gm, '<span class="comment">//$1</span>')
.replace(/('.*?')/gm, '<span class="string">$1</span>')
.replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>')
.replace(/(\d+)/gm, '<span class="number">$1</span>')
.replace(
/\bnew[ \t]+(\w+)/gm,
- '<span class="keyword">new</span> <span class="init">$1</span>'
+ '<span class="keyword">new</span> <span class="init">$1</span>',
)
.replace(
/\b(function|new|throw|return|var|if|else)\b/gm,
- '<span class="keyword">$1</span>'
+ '<span class="keyword">$1</span>',
);
}
@@ -32,7 +32,7 @@ function highlight(js) {
* @param {string} name
*/
module.exports = function highlightTags(name) {
- var code = document.getElementById('mocha').getElementsByTagName(name);
+ var code = document.getElementById("mocha").getElementsByTagName(name);
for (var i = 0, len = code.length; i < len; ++i) {
code[i].innerHTML = highlight(code[i].innerHTML);
}
diff --git a/lib/browser/parse-query.js b/lib/browser/parse-query.js
index 3a7ac1ab..7841a437 100644
--- a/lib/browser/parse-query.js
+++ b/lib/browser/parse-query.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Parse the given `qs`.
@@ -9,15 +9,15 @@
*/
module.exports = function parseQuery(qs) {
return qs
- .replace('?', '')
- .split('&')
+ .replace("?", "")
+ .split("&")
.reduce(function (obj, pair) {
- var i = pair.indexOf('=');
+ var i = pair.indexOf("=");
var key = pair.slice(0, i);
var val = pair.slice(++i);
// Due to how the URLSearchParams API treats spaces
- obj[key] = decodeURIComponent(val.replace(/\+/g, '%20'));
+ obj[key] = decodeURIComponent(val.replace(/\+/g, "%20"));
return obj;
}, {});
diff --git a/lib/browser/template.html b/lib/browser/template.html
index 4ebd4af4..10f15241 100644
--- a/lib/browser/template.html
+++ b/lib/browser/template.html
@@ -1,4 +1,4 @@
-<!DOCTYPE html>
+<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
@@ -10,7 +10,7 @@
<div id="mocha"></div>
<script src="mocha.js"></script>
<script>
- mocha.setup('bdd');
+ mocha.setup("bdd");
</script>
<script src="tests.spec.js"></script>
<script>
diff --git a/lib/cli/cli.js b/lib/cli/cli.js
index 6229335d..81475a42 100755
--- a/lib/cli/cli.js
+++ b/lib/cli/cli.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Contains CLI entry point and public API for programmatic usage in Node.js.
@@ -8,21 +8,26 @@
* @module lib/cli
*/
-const debug = require('debug')('mocha:cli:cli');
-const symbols = require('log-symbols');
-const yargs = require('yargs');
-const path = require('node:path');
+const debug = require("debug")("mocha:cli:cli");
+const symbols = require("log-symbols");
+const yargs = require("yargs");
+const path = require("node:path");
const {
loadRc,
loadPkgRc,
loadOptions,
- YARGS_PARSER_CONFIG
-} = require('./options');
-const lookupFiles = require('./lookup-files');
-const commands = require('./commands');
-const pc = require('picocolors');
-const {repository, homepage, version, discord} = require('../../package.json');
-const {cwd} = require('../utils');
+ YARGS_PARSER_CONFIG,
+} = require("./options");
+const lookupFiles = require("./lookup-files");
+const commands = require("./commands");
+const pc = require("picocolors");
+const {
+ repository,
+ homepage,
+ version,
+ discord,
+} = require("../../package.json");
+const { cwd } = require("../utils");
/**
* - Accepts an `Array` of arguments
@@ -34,46 +39,46 @@ const {cwd} = require('../utils');
* @param {object} [mochaArgs] - Object of already parsed Mocha arguments (by bin/mocha)
*/
exports.main = (argv = process.argv.slice(2), mochaArgs) => {
- debug('entered main with raw args', argv);
+ debug("entered main with raw args", argv);
// ensure we can require() from current working directory
- if (typeof module.paths !== 'undefined') {
- module.paths.push(cwd(), path.resolve('node_modules'));
+ if (typeof module.paths !== "undefined") {
+ module.paths.push(cwd(), path.resolve("node_modules"));
}
try {
Error.stackTraceLimit = Infinity; // configurable via --stack-trace-limit?
} catch (err) {
- debug('unable to set Error.stackTraceLimit = Infinity', err);
+ debug("unable to set Error.stackTraceLimit = Infinity", err);
}
var args = mochaArgs || loadOptions(argv);
yargs()
- .scriptName('mocha')
+ .scriptName("mocha")
.command(commands.run)
.command(commands.init)
.updateStrings({
- 'Positionals:': 'Positional Arguments',
- 'Options:': 'Other Options',
- 'Commands:': 'Commands'
+ "Positionals:": "Positional Arguments",
+ "Options:": "Other Options",
+ "Commands:": "Commands",
})
.fail((msg, err, yargs) => {
- debug('caught error sometime before command handler: %O', err);
+ debug("caught error sometime before command handler: %O", err);
yargs.showHelp();
- console.error(`\n${symbols.error} ${pc.red('ERROR:')} ${msg}`);
+ console.error(`\n${symbols.error} ${pc.red("ERROR:")} ${msg}`);
process.exit(1);
})
- .help('help', 'Show usage information & exit')
- .alias('help', 'h')
- .version('version', 'Show version number & exit', version)
- .alias('version', 'V')
+ .help("help", "Show usage information & exit")
+ .alias("help", "h")
+ .version("version", "Show version number & exit", version)
+ .alias("version", "V")
.wrap(process.stdout.columns ? Math.min(process.stdout.columns, 80) : 80)
.epilog(
`${pc.reset("Mocha Resources")}
Chat: ${pc.magenta(discord)}
GitHub: ${pc.blue(repository.url)}
Docs: ${pc.yellow(homepage)}
- `
+ `,
)
.parserConfiguration(YARGS_PARSER_CONFIG)
.config(args)
diff --git a/lib/cli/collect-files.js b/lib/cli/collect-files.js
index 6821dd37..020e86e6 100644
--- a/lib/cli/collect-files.js
+++ b/lib/cli/collect-files.js
@@ -1,12 +1,12 @@
-'use strict';
+"use strict";
-const path = require('node:path');
-const pc = require('picocolors');
-const debug = require('debug')('mocha:cli:run:helpers');
-const { minimatch } = require('minimatch');
-const {NO_FILES_MATCH_PATTERN} = require('../error-constants').constants;
-const lookupFiles = require('./lookup-files');
-const {castArray} = require('../utils');
+const path = require("node:path");
+const pc = require("picocolors");
+const debug = require("debug")("mocha:cli:run:helpers");
+const { minimatch } = require("minimatch");
+const { NO_FILES_MATCH_PATTERN } = require("../error-constants").constants;
+const lookupFiles = require("./lookup-files");
+const { castArray } = require("../utils");
/**
* Exports a function that collects test files from CLI parameters.
@@ -33,23 +33,23 @@ module.exports = ({
file: fileArgs,
recursive,
sort,
- spec
+ spec,
} = {}) => {
const unmatchedSpecFiles = [];
const specFiles = spec.reduce((specFiles, arg) => {
try {
const moreSpecFiles = castArray(lookupFiles(arg, extension, recursive))
- .filter(filename =>
+ .filter((filename) =>
ignore.every(
- pattern =>
- !minimatch(filename, pattern, {windowsPathsNoEscape: true})
- )
+ (pattern) =>
+ !minimatch(filename, pattern, { windowsPathsNoEscape: true }),
+ ),
)
- .map(filename => path.resolve(filename));
+ .map((filename) => path.resolve(filename));
return [...specFiles, ...moreSpecFiles];
} catch (err) {
if (err.code === NO_FILES_MATCH_PATTERN) {
- unmatchedSpecFiles.push({message: err.message, pattern: err.pattern});
+ unmatchedSpecFiles.push({ message: err.message, pattern: err.pattern });
return specFiles;
}
@@ -60,16 +60,16 @@ module.exports = ({
// check that each file passed in to --file exists
const unmatchedFiles = [];
- fileArgs.forEach(file => {
+ fileArgs.forEach((file) => {
const fileAbsolutePath = path.resolve(file);
try {
// Used instead of fs.existsSync to ensure that file-ending less files are still resolved correctly
require.resolve(fileAbsolutePath);
} catch (err) {
- if (err.code === 'MODULE_NOT_FOUND') {
+ if (err.code === "MODULE_NOT_FOUND") {
unmatchedFiles.push({
pattern: file,
- absolutePath: fileAbsolutePath
+ absolutePath: fileAbsolutePath,
});
return;
}
@@ -85,30 +85,30 @@ module.exports = ({
// add files given through --file to be ran first
const files = [
- ...fileArgs.map(filepath => path.resolve(filepath)),
- ...specFiles
+ ...fileArgs.map((filepath) => path.resolve(filepath)),
+ ...specFiles,
];
- debug('test files (in order): ', files);
+ debug("test files (in order): ", files);
if (!files.length) {
// give full message details when only 1 file is missing
const noneFoundMsg =
unmatchedSpecFiles.length === 1
? `Error: No test files found: ${JSON.stringify(
- unmatchedSpecFiles[0].pattern
+ unmatchedSpecFiles[0].pattern,
)}` // stringify to print escaped characters raw
- : 'Error: No test files found';
+ : "Error: No test files found";
console.error(pc.red(noneFoundMsg));
process.exit(1);
} else {
// print messages as a warning
- unmatchedSpecFiles.forEach(warning => {
+ unmatchedSpecFiles.forEach((warning) => {
console.warn(pc.yellow(`Warning: ${warning.message}`));
});
}
return {
files,
- unmatchedFiles
+ unmatchedFiles,
};
};
diff --git a/lib/cli/commands.js b/lib/cli/commands.js
index e3238f70..b3383d1e 100644
--- a/lib/cli/commands.js
+++ b/lib/cli/commands.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Exports Yargs commands
@@ -8,7 +8,7 @@
*/
module.exports = {
- init: require('./init'),
+ init: require("./init"),
// default command
- run: require('./run'),
-}
+ run: require("./run"),
+};
diff --git a/lib/cli/config.js b/lib/cli/config.js
index 9f9dfdbb..20682811 100644
--- a/lib/cli/config.js
+++ b/lib/cli/config.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Responsible for loading / finding Mocha's "rc" files.
@@ -7,12 +7,12 @@
* @module
*/
-const fs = require('node:fs');
-const path = require('node:path');
-const debug = require('debug')('mocha:cli:config');
-const findUp = require('find-up');
-const {createUnparsableFileError} = require('../errors');
-const utils = require('../utils');
+const fs = require("node:fs");
+const path = require("node:path");
+const debug = require("debug")("mocha:cli:config");
+const findUp = require("find-up");
+const { createUnparsableFileError } = require("../errors");
+const utils = require("../utils");
/**
* These are the valid config files, in order of precedence;
@@ -22,12 +22,12 @@ const utils = require('../utils');
* @private
*/
exports.CONFIG_FILES = [
- '.mocharc.cjs',
- '.mocharc.js',
- '.mocharc.yaml',
- '.mocharc.yml',
- '.mocharc.jsonc',
- '.mocharc.json'
+ ".mocharc.cjs",
+ ".mocharc.js",
+ ".mocharc.yaml",
+ ".mocharc.yml",
+ ".mocharc.jsonc",
+ ".mocharc.json",
];
/**
@@ -35,8 +35,9 @@ exports.CONFIG_FILES = [
* returns an object (but could throw)
*/
const parsers = (exports.parsers = {
- yaml: filepath => require('js-yaml').load(fs.readFileSync(filepath, 'utf8')),
- js: filepath => {
+ yaml: (filepath) =>
+ require("js-yaml").load(fs.readFileSync(filepath, "utf8")),
+ js: (filepath) => {
let cwdFilepath;
try {
debug('parsers: load cwd-relative path: "%s"', path.resolve(filepath));
@@ -49,10 +50,10 @@ const parsers = (exports.parsers = {
return require(filepath);
}
},
- json: filepath =>
+ json: (filepath) =>
JSON.parse(
- require('strip-json-comments')(fs.readFileSync(filepath, 'utf8'))
- )
+ require("strip-json-comments")(fs.readFileSync(filepath, "utf8")),
+ ),
});
/**
@@ -63,15 +64,15 @@ const parsers = (exports.parsers = {
* @param {string} filepath - Config file path to load
* @returns {Object} Parsed config object
*/
-exports.loadConfig = filepath => {
+exports.loadConfig = (filepath) => {
let config = {};
- debug('loadConfig: trying to parse config at %s', filepath);
+ debug("loadConfig: trying to parse config at %s", filepath);
const ext = path.extname(filepath);
try {
- if (ext === '.yml' || ext === '.yaml') {
+ if (ext === ".yml" || ext === ".yaml") {
config = parsers.yaml(filepath);
- } else if (ext === '.js' || ext === '.cjs') {
+ } else if (ext === ".js" || ext === ".cjs") {
config = parsers.js(filepath);
} else {
config = parsers.json(filepath);
@@ -79,7 +80,7 @@ exports.loadConfig = filepath => {
} catch (err) {
throw createUnparsableFileError(
`Unable to read/parse ${filepath}: ${err}`,
- filepath
+ filepath,
);
}
return config;
@@ -92,9 +93,9 @@ exports.loadConfig = filepath => {
* @returns {string|null} Filepath to config, if found
*/
exports.findConfig = (cwd = utils.cwd()) => {
- const filepath = findUp.sync(exports.CONFIG_FILES, {cwd});
+ const filepath = findUp.sync(exports.CONFIG_FILES, { cwd });
if (filepath) {
- debug('findConfig: found config file %s', filepath);
+ debug("findConfig: found config file %s", filepath);
}
return filepath;
};
diff --git a/lib/cli/index.js b/lib/cli/index.js
index f20314ea..95fcfe5a 100644
--- a/lib/cli/index.js
+++ b/lib/cli/index.js
@@ -1,3 +1,3 @@
-'use strict';
+"use strict";
-module.exports = require('./cli');
+module.exports = require("./cli");
diff --git a/lib/cli/init.js b/lib/cli/init.js
index c892d308..8b5fafee 100644
--- a/lib/cli/init.js
+++ b/lib/cli/init.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Command module for "init" command
@@ -7,30 +7,30 @@
* @module
*/
-const fs = require('node:fs');
-const path = require('node:path');
+const fs = require("node:fs");
+const path = require("node:path");
-exports.command = 'init <path>';
+exports.command = "init <path>";
-exports.description = 'create a client-side Mocha setup at <path>';
+exports.description = "create a client-side Mocha setup at <path>";
-exports.builder = yargs =>
- yargs.positional('path', {
- type: 'string',
- normalize: true
+exports.builder = (yargs) =>
+ yargs.positional("path", {
+ type: "string",
+ normalize: true,
});
-exports.handler = argv => {
+exports.handler = (argv) => {
const destdir = argv.path;
- const srcdir = path.join(__dirname, '..', '..');
- fs.mkdirSync(destdir, {recursive: true});
- const css = fs.readFileSync(path.join(srcdir, 'mocha.css'));
- const js = fs.readFileSync(path.join(srcdir, 'mocha.js'));
+ const srcdir = path.join(__dirname, "..", "..");
+ fs.mkdirSync(destdir, { recursive: true });
+ const css = fs.readFileSync(path.join(srcdir, "mocha.css"));
+ const js = fs.readFileSync(path.join(srcdir, "mocha.js"));
const tmpl = fs.readFileSync(
- path.join(srcdir, 'lib', 'browser', 'template.html')
+ path.join(srcdir, "lib", "browser", "template.html"),
);
- fs.writeFileSync(path.join(destdir, 'mocha.css'), css);
- fs.writeFileSync(path.join(destdir, 'mocha.js'), js);
- fs.writeFileSync(path.join(destdir, 'tests.spec.js'), '');
- fs.writeFileSync(path.join(destdir, 'index.html'), tmpl);
+ fs.writeFileSync(path.join(destdir, "mocha.css"), css);
+ fs.writeFileSync(path.join(destdir, "mocha.js"), js);
+ fs.writeFileSync(path.join(destdir, "tests.spec.js"), "");
+ fs.writeFileSync(path.join(destdir, "index.html"), tmpl);
};
diff --git a/lib/cli/lookup-files.js b/lib/cli/lookup-files.js
index f5ad0ca8..878b4993 100644
--- a/lib/cli/lookup-files.js
+++ b/lib/cli/lookup-files.js
@@ -1,17 +1,17 @@
-'use strict';
+"use strict";
/**
* Contains `lookupFiles`, which takes some globs/dirs/options and returns a list of files.
* @module
* @private
*/
-var fs = require('node:fs');
-var path = require('node:path');
-var glob = require('glob');
-var errors = require('../errors');
+var fs = require("node:fs");
+var path = require("node:path");
+var glob = require("glob");
+var errors = require("../errors");
var createNoFilesMatchPatternError = errors.createNoFilesMatchPatternError;
var createMissingArgumentError = errors.createMissingArgumentError;
-const debug = require('debug')('mocha:cli:lookup-files');
+const debug = require("debug")("mocha:cli:lookup-files");
/**
* Determines if pathname would be a "hidden" file (or directory) on UN*X.
@@ -28,7 +28,7 @@ const debug = require('debug')('mocha:cli:lookup-files');
* @example
* isHiddenOnUnix('.profile'); // => true
*/
-const isHiddenOnUnix = pathname => path.basename(pathname).startsWith('.');
+const isHiddenOnUnix = (pathname) => path.basename(pathname).startsWith(".");
/**
* Determines if pathname has a matching file extension.
@@ -46,8 +46,8 @@ const isHiddenOnUnix = pathname => path.basename(pathname).startsWith('.');
*/
const hasMatchingExtname = (pathname, exts = []) =>
exts
- .map(ext => (ext.startsWith('.') ? ext : `.${ext}`))
- .some(ext => pathname.endsWith(ext));
+ .map((ext) => (ext.startsWith(".") ? ext : `.${ext}`))
+ .some((ext) => pathname.endsWith(ext));
/**
* Lookup file names at the given `path`.
@@ -68,39 +68,39 @@ const hasMatchingExtname = (pathname, exts = []) =>
module.exports = function lookupFiles(
filepath,
extensions = [],
- recursive = false
+ recursive = false,
) {
const files = [];
let stat;
if (!fs.existsSync(filepath)) {
let pattern;
- if (glob.hasMagic(filepath, {windowsPathsNoEscape: true})) {
+ if (glob.hasMagic(filepath, { windowsPathsNoEscape: true })) {
// Handle glob as is without extensions
pattern = filepath;
} else {
// glob pattern e.g. 'filepath+(.js|.ts)'
const strExtensions = extensions
- .map(ext => (ext.startsWith('.') ? ext : `.${ext}`))
- .join('|');
+ .map((ext) => (ext.startsWith(".") ? ext : `.${ext}`))
+ .join("|");
pattern = `${filepath}+(${strExtensions})`;
- debug('looking for files using glob pattern: %s', pattern);
+ debug("looking for files using glob pattern: %s", pattern);
}
files.push(
...glob
.sync(pattern, {
nodir: true,
- windowsPathsNoEscape: true
+ windowsPathsNoEscape: true,
})
// glob@8 and earlier sorted results in en; glob@9 depends on OS sorting.
// This preserves the older glob behavior.
// https://github.com/mochajs/mocha/pull/5250/files#r1840469747
- .sort((a, b) => a.localeCompare(b, 'en'))
+ .sort((a, b) => a.localeCompare(b, "en")),
);
if (!files.length) {
throw createNoFilesMatchPatternError(
`Cannot find any files matching pattern "${filepath}"`,
- filepath
+ filepath,
);
}
return files;
@@ -118,7 +118,7 @@ module.exports = function lookupFiles(
}
// Handle directory
- fs.readdirSync(filepath).forEach(dirent => {
+ fs.readdirSync(filepath).forEach((dirent) => {
const pathname = path.join(filepath, dirent);
let stat;
@@ -136,8 +136,8 @@ module.exports = function lookupFiles(
if (!extensions.length) {
throw createMissingArgumentError(
`Argument '${extensions}' required when argument '${filepath}' is a directory`,
- 'extensions',
- 'array'
+ "extensions",
+ "array",
);
}
diff --git a/lib/cli/node-flags.js b/lib/cli/node-flags.js
index 25ca2669..8b8ffe02 100644
--- a/lib/cli/node-flags.js
+++ b/lib/cli/node-flags.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Some settings and code related to Mocha's handling of Node.js/V8 flags.
@@ -7,15 +7,15 @@
*/
const nodeFlags = process.allowedNodeEnvironmentFlags;
-const {isMochaFlag} = require('./run-option-metadata');
-const unparse = require('yargs-unparser');
+const { isMochaFlag } = require("./run-option-metadata");
+const unparse = require("yargs-unparser");
/**
* These flags are considered "debug" flags.
* @see {@link impliesNoTimeouts}
* @private
*/
-const debugFlags = new Set(['inspect', 'inspect-brk']);
+const debugFlags = new Set(["inspect", "inspect-brk"]);
/**
* Mocha has historical support for various `node` and V8 flags which might not
@@ -41,7 +41,7 @@ exports.isNodeFlag = (flag, bareword = true) => {
return false;
}
// strip the leading dashes to match against subsequent checks
- flag = flag.replace(/^--?/, '');
+ flag = flag.replace(/^--?/, "");
}
return (
// check actual node flags from `process.allowedNodeEnvironmentFlags`,
@@ -50,7 +50,7 @@ exports.isNodeFlag = (flag, bareword = true) => {
(!isMochaFlag(flag) && nodeFlags && nodeFlags.has(flag)) ||
debugFlags.has(flag) ||
/(?:preserve-symlinks(?:-main)?|harmony(?:[_-]|$)|(?:trace[_-].+$)|gc[_-]global$|es[_-]staging$|use[_-]strict$|v8[_-](?!options).+?$)/.test(
- flag
+ flag,
)
);
};
@@ -62,7 +62,7 @@ exports.isNodeFlag = (flag, bareword = true) => {
* @returns {boolean}
* @private
*/
-exports.impliesNoTimeouts = flag => debugFlags.has(flag);
+exports.impliesNoTimeouts = (flag) => debugFlags.has(flag);
/**
* All non-strictly-boolean arguments to node--those with values--must specify those values using `=`, e.g., `--inspect=0.0.0.0`.
@@ -72,14 +72,14 @@ exports.impliesNoTimeouts = flag => debugFlags.has(flag);
* @returns {string[]} Unparsed arguments using `=` to specify values
* @private
*/
-exports.unparseNodeFlags = opts => {
+exports.unparseNodeFlags = (opts) => {
var args = unparse(opts);
return args.length
? args
- .join(' ')
+ .join(" ")
.split(/\b/)
- .map(arg => (arg === ' ' ? '=' : arg))
- .join('')
- .split(' ')
+ .map((arg) => (arg === " " ? "=" : arg))
+ .join("")
+ .split(" ")
: [];
};
diff --git a/lib/cli/one-and-dones.js b/lib/cli/one-and-dones.js
index 21bad6fd..dc3a738f 100644
--- a/lib/cli/one-and-dones.js
+++ b/lib/cli/one-and-dones.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Contains "command" code for "one-and-dones"--options passed
@@ -8,7 +8,7 @@
* @private
*/
-const Mocha = require('../mocha');
+const Mocha = require("../mocha");
/**
* Dumps a sorted list of the enumerable, lower-case keys of some object
@@ -17,21 +17,22 @@ const Mocha = require('../mocha');
* @ignore
* @private
*/
-const showKeys = obj => {
+const showKeys = (obj) => {
console.log();
const keys = Object.keys(obj);
const maxKeyLength = keys.reduce((max, key) => Math.max(max, key.length), 0);
keys
.filter(
- key => /^[a-z]/.test(key) && !obj[key].browserOnly && !obj[key].abstract
+ (key) =>
+ /^[a-z]/.test(key) && !obj[key].browserOnly && !obj[key].abstract,
)
.sort()
- .forEach(key => {
+ .forEach((key) => {
const description = obj[key].description;
console.log(
` ${key.padEnd(maxKeyLength + 1)}${
- description ? `- ${description}` : ''
- }`
+ description ? `- ${description}` : ""
+ }`,
);
});
console.log();
@@ -47,16 +48,16 @@ exports.ONE_AND_DONES = {
* Dump list of built-in interfaces
* @private
*/
- 'list-interfaces': () => {
+ "list-interfaces": () => {
showKeys(Mocha.interfaces);
},
/**
* Dump list of built-in reporters
* @private
*/
- 'list-reporters': () => {
+ "list-reporters": () => {
showKeys(Mocha.reporters);
- }
+ },
};
/**
@@ -65,5 +66,5 @@ exports.ONE_AND_DONES = {
* @private
*/
exports.ONE_AND_DONE_ARGS = new Set(
- ['help', 'h', 'version', 'V'].concat(Object.keys(exports.ONE_AND_DONES))
+ ["help", "h", "version", "V"].concat(Object.keys(exports.ONE_AND_DONES)),
);
diff --git a/lib/cli/options.js b/lib/cli/options.js
index 167c78de..007f8943 100644
--- a/lib/cli/options.js
+++ b/lib/cli/options.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Main entry point for handling filesystem-based configuration,
@@ -7,28 +7,28 @@
* @private
*/
-const fs = require('node:fs');
-const pc = require('picocolors');
-const yargsParser = require('yargs-parser');
+const fs = require("node:fs");
+const pc = require("picocolors");
+const yargsParser = require("yargs-parser");
const {
types,
aliases,
isMochaFlag,
- expectedTypeForFlag
-} = require('./run-option-metadata');
-const {ONE_AND_DONE_ARGS} = require('./one-and-dones');
-const mocharc = require('../mocharc.json');
-const {list} = require('./run-helpers');
-const {loadConfig, findConfig} = require('./config');
-const findUp = require('find-up');
-const debug = require('debug')('mocha:cli:options');
-const {isNodeFlag} = require('./node-flags');
+ expectedTypeForFlag,
+} = require("./run-option-metadata");
+const { ONE_AND_DONE_ARGS } = require("./one-and-dones");
+const mocharc = require("../mocharc.json");
+const { list } = require("./run-helpers");
+const { loadConfig, findConfig } = require("./config");
+const findUp = require("find-up");
+const debug = require("debug")("mocha:cli:options");
+const { isNodeFlag } = require("./node-flags");
const {
createUnparsableFileError,
createInvalidArgumentTypeError,
- createUnsupportedError
-} = require('../errors');
-const {isNumeric} = require('../utils');
+ createUnsupportedError,
+} = require("../errors");
+const { isNumeric } = require("../utils");
/**
* The `yargs-parser` namespace
@@ -47,10 +47,10 @@ const {isNumeric} = require('../utils');
* @private
*/
const YARGS_PARSER_CONFIG = {
- 'combine-arrays': true,
- 'short-option-groups': false,
- 'dot-notation': false,
- 'strip-aliased': true
+ "combine-arrays": true,
+ "short-option-groups": false,
+ "dot-notation": false,
+ "strip-aliased": true,
};
/**
@@ -62,7 +62,7 @@ const YARGS_PARSER_CONFIG = {
* @ignore
*/
const configuration = Object.assign({}, YARGS_PARSER_CONFIG, {
- 'camel-case-expansion': false
+ "camel-case-expansion": false,
});
/**
@@ -73,22 +73,23 @@ const configuration = Object.assign({}, YARGS_PARSER_CONFIG, {
* @private
* @ignore
*/
-const globOptions = ['spec', 'ignore'];
+const globOptions = ["spec", "ignore"];
const coerceOpts = Object.assign(
types.array.reduce(
(acc, arg) =>
Object.assign(acc, {
- [arg]: v => Array.from(new Set(globOptions.includes(arg) ? v : list(v)))
+ [arg]: (v) =>
+ Array.from(new Set(globOptions.includes(arg) ? v : list(v))),
}),
- {}
+ {},
),
types.boolean
.concat(types.string, types.number)
.reduce(
(acc, arg) =>
- Object.assign(acc, {[arg]: v => (Array.isArray(v) ? v.pop() : v)}),
- {}
- )
+ Object.assign(acc, { [arg]: (v) => (Array.isArray(v) ? v.pop() : v) }),
+ {},
+ ),
);
/**
@@ -101,7 +102,7 @@ const coerceOpts = Object.assign(
*/
const nargOpts = types.array
.concat(types.string, types.number)
- .reduce((acc, arg) => Object.assign(acc, {[arg]: 1}), {});
+ .reduce((acc, arg) => Object.assign(acc, { [arg]: 1 }), {});
/**
* Throws either "UNSUPPORTED" error or "INVALID_ARG_TYPE" error for numeric positional arguments.
@@ -114,13 +115,13 @@ const nargOpts = types.array
const createErrorForNumericPositionalArg = (
numericArg,
allArgs,
- parsedResult
+ parsedResult,
) => {
// A flag for `numericArg` exists if:
// 1. A mocha flag immediately preceeded the numericArg in `allArgs` array and
// 2. `numericArg` value could not be assigned to this flag by `yargs-parser` because of incompatible datatype.
const flag = allArgs.find((arg, index) => {
- const normalizedArg = arg.replace(/^--?/, '');
+ const normalizedArg = arg.replace(/^--?/, "");
return (
isMochaFlag(arg) &&
allArgs[index + 1] === String(numericArg) &&
@@ -132,11 +133,11 @@ const createErrorForNumericPositionalArg = (
throw createInvalidArgumentTypeError(
`Mocha flag '${flag}' given invalid option: '${numericArg}'`,
numericArg,
- expectedTypeForFlag(flag)
+ expectedTypeForFlag(flag),
);
} else {
throw createUnsupportedError(
- `Option ${numericArg} is unsupported by the mocha cli`
+ `Option ${numericArg} is unsupported by the mocha cli`,
);
}
};
@@ -156,13 +157,13 @@ const parse = (args = [], defaultValues = {}, ...configObjects) => {
// 3. to avoid explicitly defining the set of them, we tell yargs-parser they
// are ALL boolean flags.
// 4. we can then reapply the values after yargs-parser is done.
- const allArgs = Array.isArray(args) ? args : args.split(' ');
+ const allArgs = Array.isArray(args) ? args : args.split(" ");
const nodeArgs = allArgs.reduce((acc, arg) => {
- const pair = arg.split('=');
+ const pair = arg.split("=");
let flag = pair[0];
if (isNodeFlag(flag, false)) {
- flag = flag.replace(/^--?/, '');
- return acc.concat([[flag, arg.includes('=') ? pair[1] : true]]);
+ flag = flag.replace(/^--?/, "");
+ return acc.concat([[flag, arg.includes("=") ? pair[1] : true]]);
}
return acc;
}, []);
@@ -177,19 +178,19 @@ const parse = (args = [], defaultValues = {}, ...configObjects) => {
string: types.string,
array: types.array,
number: types.number,
- boolean: types.boolean.concat(nodeArgs.map(pair => pair[0]))
+ boolean: types.boolean.concat(nodeArgs.map((pair) => pair[0])),
});
if (result.error) {
console.error(pc.red(`Error: ${result.error.message}`));
process.exit(1);
}
- const numericPositionalArg = result.argv._.find(arg => isNumeric(arg));
+ const numericPositionalArg = result.argv._.find((arg) => isNumeric(arg));
if (numericPositionalArg) {
createErrorForNumericPositionalArg(
numericPositionalArg,
allArgs,
- result.argv
+ result.argv,
);
}
@@ -236,33 +237,32 @@ const loadPkgRc = (args = {}) => {
if (filepath) {
let configData;
try {
- configData = fs.readFileSync(filepath, 'utf8');
+ configData = fs.readFileSync(filepath, "utf8");
} catch (err) {
// If `args.package` was explicitly specified, throw an error
if (filepath == args.package) {
throw createUnparsableFileError(
`Unable to read ${filepath}: ${err}`,
- filepath
+ filepath,
);
} else {
- debug('failed to read default package.json at %s; ignoring',
- filepath);
+ debug("failed to read default package.json at %s; ignoring", filepath);
return result;
}
}
try {
const pkg = JSON.parse(configData);
if (pkg.mocha) {
- debug('`mocha` prop of package.json parsed: %O', pkg.mocha);
+ debug("`mocha` prop of package.json parsed: %O", pkg.mocha);
result = pkg.mocha;
} else {
- debug('no config found in %s', filepath);
+ debug("no config found in %s", filepath);
}
} catch (err) {
// If JSON failed to parse, throw an error.
throw createUnparsableFileError(
`Unable to parse ${filepath}: ${err}`,
- filepath
+ filepath,
);
}
}
@@ -293,13 +293,13 @@ const loadOptions = (argv = []) => {
if (
Array.from(ONE_AND_DONE_ARGS).reduce(
(acc, arg) => acc || arg in args,
- false
+ false,
)
) {
return args;
}
- const envConfig = parse(process.env.MOCHA_OPTIONS || '');
+ const envConfig = parse(process.env.MOCHA_OPTIONS || "");
const rcConfig = loadRc(args);
const pkgConfig = loadPkgRc(args);
@@ -318,7 +318,7 @@ const loadOptions = (argv = []) => {
args,
envConfig,
rcConfig || {},
- pkgConfig || {}
+ pkgConfig || {},
);
// recombine positional arguments and "spec"
diff --git a/lib/cli/run-helpers.js b/lib/cli/run-helpers.js
index 607d67b6..d83b76f1 100644
--- a/lib/cli/run-helpers.js
+++ b/lib/cli/run-helpers.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Helper scripts for the `run` command
@@ -14,16 +14,16 @@
* @typedef {import('../runner.js')} Runner
*/
-const fs = require('node:fs');
-const path = require('node:path');
-const pc = require('picocolors');
-const debug = require('debug')('mocha:cli:run:helpers');
-const {watchRun, watchParallelRun} = require('./watch-run');
-const collectFiles = require('./collect-files');
-const {format} = require('node:util');
-const {createInvalidLegacyPluginError} = require('../errors');
-const {requireOrImport} = require('../nodejs/esm-utils');
-const PluginLoader = require('../plugin-loader');
+const fs = require("node:fs");
+const path = require("node:path");
+const pc = require("picocolors");
+const debug = require("debug")("mocha:cli:run:helpers");
+const { watchRun, watchParallelRun } = require("./watch-run");
+const collectFiles = require("./collect-files");
+const { format } = require("node:util");
+const { createInvalidLegacyPluginError } = require("../errors");
+const { requireOrImport } = require("../nodejs/esm-utils");
+const PluginLoader = require("../plugin-loader");
/**
* Exits Mocha when tests + code under test has finished execution (default)
@@ -31,9 +31,12 @@ const PluginLoader = require('../plugin-loader');
* @ignore
* @private
*/
-const exitMochaLater = clampedCode => {
- process.on('exit', () => {
- process.exitCode = Math.min(clampedCode, process.argv.includes('--posix-exit-codes') ? 1 : 255);
+const exitMochaLater = (clampedCode) => {
+ process.on("exit", () => {
+ process.exitCode = Math.min(
+ clampedCode,
+ process.argv.includes("--posix-exit-codes") ? 1 : 255,
+ );
});
};
@@ -44,8 +47,8 @@ const exitMochaLater = clampedCode => {
* @ignore
* @private
*/
-const exitMocha = clampedCode => {
- const usePosixExitCodes = process.argv.includes('--posix-exit-codes');
+const exitMocha = (clampedCode) => {
+ const usePosixExitCodes = process.argv.includes("--posix-exit-codes");
clampedCode = Math.min(clampedCode, usePosixExitCodes ? 1 : 255);
let draining = 0;
@@ -64,10 +67,10 @@ const exitMocha = clampedCode => {
const streams = [process.stdout, process.stderr];
- streams.forEach(stream => {
+ streams.forEach((stream) => {
// submit empty write request and wait for completion
draining += 1;
- stream.write('', done);
+ stream.write("", done);
});
done();
@@ -80,8 +83,8 @@ const exitMocha = clampedCode => {
* @returns {string[]} Array of strings
* @private
*/
-exports.list = str =>
- Array.isArray(str) ? exports.list(str.join(',')) : str.split(/ *, */);
+exports.list = (str) =>
+ Array.isArray(str) ? exports.list(str.join(",")) : str.split(/ *, */);
/**
* `require()` the modules as required by `--require <require>`.
@@ -91,26 +94,29 @@ exports.list = str =>
* @returns {Promise<object>} Plugin implementations
* @private
*/
-exports.handleRequires = async (requires = [], {ignoredPlugins = []} = {}) => {
- const pluginLoader = PluginLoader.create({ignore: ignoredPlugins});
+exports.handleRequires = async (
+ requires = [],
+ { ignoredPlugins = [] } = {},
+) => {
+ const pluginLoader = PluginLoader.create({ ignore: ignoredPlugins });
for await (const mod of requires) {
let modpath = mod;
// this is relative to cwd
if (fs.existsSync(mod) || fs.existsSync(`${mod}.js`)) {
modpath = path.resolve(mod);
- debug('resolved required file %s to %s', mod, modpath);
+ debug("resolved required file %s to %s", mod, modpath);
}
const requiredModule = await requireOrImport(modpath);
- if (requiredModule && typeof requiredModule === 'object') {
+ if (requiredModule && typeof requiredModule === "object") {
if (pluginLoader.load(requiredModule)) {
- debug('found one or more plugin implementations in %s', modpath);
+ debug("found one or more plugin implementations in %s", modpath);
}
}
debug('loaded required module "%s"', mod);
}
const plugins = await pluginLoader.finalize();
if (Object.keys(plugins).length) {
- debug('finalized plugin implementations: %O', plugins);
+ debug("finalized plugin implementations: %O", plugins);
}
return plugins;
};
@@ -127,15 +133,15 @@ const handleUnmatchedFiles = (mocha, unmatchedFiles) => {
return;
}
- unmatchedFiles.forEach(({pattern, absolutePath}) => {
+ unmatchedFiles.forEach(({ pattern, absolutePath }) => {
console.error(
pc.yellow(
- `Warning: Cannot find any files matching pattern "${pattern}" at the absolute path "${absolutePath}"`
- )
+ `Warning: Cannot find any files matching pattern "${pattern}" at the absolute path "${absolutePath}"`,
+ ),
);
});
console.log(
- 'No test file(s) found with the given pattern, exiting with code 1'
+ "No test file(s) found with the given pattern, exiting with code 1",
);
return mocha.run(exitMocha(1));
@@ -152,8 +158,8 @@ const handleUnmatchedFiles = (mocha, unmatchedFiles) => {
*/
const singleRun = async (
mocha,
- {exit, passOnFailingTestSuite},
- fileCollectParams
+ { exit, passOnFailingTestSuite },
+ fileCollectParams,
) => {
const fileCollectionObj = collectFiles(fileCollectParams);
@@ -161,14 +167,12 @@ const singleRun = async (
return handleUnmatchedFiles(mocha, fileCollectionObj.unmatchedFiles);
}
- debug('single run with %d file(s)', fileCollectionObj.files.length);
+ debug("single run with %d file(s)", fileCollectionObj.files.length);
mocha.files = fileCollectionObj.files;
// handles ESM modules
await mocha.loadFilesAsync();
- return mocha.run(
- createExitHandler({exit, passOnFailingTestSuite})
- );
+ return mocha.run(createExitHandler({ exit, passOnFailingTestSuite }));
};
/**
@@ -192,15 +196,13 @@ const parallelRun = async (mocha, options, fileCollectParams) => {
}
debug(
- 'executing %d test file(s) in parallel mode',
- fileCollectionObj.files.length
+ "executing %d test file(s) in parallel mode",
+ fileCollectionObj.files.length,
);
mocha.files = fileCollectionObj.files;
// note that we DO NOT load any files here; this is handled by the worker
- return mocha.run(
- createExitHandler(options)
- );
+ return mocha.run(createExitHandler(options));
};
/**
@@ -223,7 +225,7 @@ exports.runMocha = async (mocha, options) => {
parallel = false,
recursive = false,
sort = false,
- spec = []
+ spec = [],
} = options;
const fileCollectParams = {
@@ -232,7 +234,7 @@ exports.runMocha = async (mocha, options) => {
file,
recursive,
sort,
- spec
+ spec,
};
let run;
@@ -267,15 +269,15 @@ exports.validateLegacyPlugin = (opts, pluginType, map = {}) => {
if (Array.isArray(pluginId)) {
throw createInvalidLegacyPluginError(
`"--${pluginType}" can only be specified once`,
- pluginType
+ pluginType,
);
}
- const createUnknownError = err =>
+ const createUnknownError = (err) =>
createInvalidLegacyPluginError(
format('Could not load %s "%s":\n\n %O', pluginType, pluginId, err),
pluginType,
- pluginId
+ pluginId,
);
// if this exists, then it's already loaded, so nothing more to do.
@@ -298,13 +300,9 @@ exports.validateLegacyPlugin = (opts, pluginType, map = {}) => {
};
const createExitHandler = ({ exit, passOnFailingTestSuite }) => {
- return code => {
- const clampedCode = passOnFailingTestSuite
- ? 0
- : Math.min(code, 255);
-
- return exit
- ? exitMocha(clampedCode)
- : exitMochaLater(clampedCode);
+ return (code) => {
+ const clampedCode = passOnFailingTestSuite ? 0 : Math.min(code, 255);
+
+ return exit ? exitMocha(clampedCode) : exitMochaLater(clampedCode);
};
};
diff --git a/lib/cli/run-option-metadata.js b/lib/cli/run-option-metadata.js
index b0f86436..a4353108 100644
--- a/lib/cli/run-option-metadata.js
+++ b/lib/cli/run-option-metadata.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Metadata about various options of the `run` command
@@ -14,54 +14,54 @@
*/
const TYPES = (exports.types = {
array: [
- 'extension',
- 'file',
- 'global',
- 'ignore',
- 'node-option',
- 'reporter-option',
- 'require',
- 'spec',
- 'watch-files',
- 'watch-ignore'
+ "extension",
+ "file",
+ "global",
+ "ignore",
+ "node-option",
+ "reporter-option",
+ "require",
+ "spec",
+ "watch-files",
+ "watch-ignore",
],
boolean: [
- 'allow-uncaught',
- 'async-only',
- 'bail',
- 'check-leaks',
- 'color',
- 'delay',
- 'diff',
- 'dry-run',
- 'exit',
- 'pass-on-failing-test-suite',
- 'fail-zero',
- 'forbid-only',
- 'forbid-pending',
- 'full-trace',
- 'inline-diffs',
- 'invert',
- 'list-interfaces',
- 'list-reporters',
- 'no-colors',
- 'parallel',
- 'posix-exit-codes',
- 'recursive',
- 'sort',
- 'watch'
+ "allow-uncaught",
+ "async-only",
+ "bail",
+ "check-leaks",
+ "color",
+ "delay",
+ "diff",
+ "dry-run",
+ "exit",
+ "pass-on-failing-test-suite",
+ "fail-zero",
+ "forbid-only",
+ "forbid-pending",
+ "full-trace",
+ "inline-diffs",
+ "invert",
+ "list-interfaces",
+ "list-reporters",
+ "no-colors",
+ "parallel",
+ "posix-exit-codes",
+ "recursive",
+ "sort",
+ "watch",
],
- number: ['retries', 'jobs'],
+ number: ["retries", "jobs"],
string: [
- 'config',
- 'fgrep',
- 'grep',
- 'package',
- 'reporter',
- 'ui',
- 'slow',
- 'timeout'
- ]
+ "config",
+ "fgrep",
+ "grep",
+ "package",
+ "reporter",
+ "ui",
+ "slow",
+ "timeout",
+ ],
});
/**
@@ -71,35 +71,35 @@ const TYPES = (exports.types = {
* @private
*/
exports.aliases = {
- 'async-only': ['A'],
- bail: ['b'],
- color: ['c', 'colors'],
- fgrep: ['f'],
- global: ['globals'],
- grep: ['g'],
- ignore: ['exclude'],
- invert: ['i'],
- jobs: ['j'],
- 'no-colors': ['C'],
- 'node-option': ['n'],
- parallel: ['p'],
- reporter: ['R'],
- 'reporter-option': ['reporter-options', 'O'],
- require: ['r'],
- slow: ['s'],
- sort: ['S'],
- timeout: ['t', 'timeouts'],
- ui: ['u'],
- watch: ['w']
+ "async-only": ["A"],
+ bail: ["b"],
+ color: ["c", "colors"],
+ fgrep: ["f"],
+ global: ["globals"],
+ grep: ["g"],
+ ignore: ["exclude"],
+ invert: ["i"],
+ jobs: ["j"],
+ "no-colors": ["C"],
+ "node-option": ["n"],
+ parallel: ["p"],
+ reporter: ["R"],
+ "reporter-option": ["reporter-options", "O"],
+ require: ["r"],
+ slow: ["s"],
+ sort: ["S"],
+ timeout: ["t", "timeouts"],
+ ui: ["u"],
+ watch: ["w"],
};
const ALL_MOCHA_FLAGS = Object.keys(TYPES).reduce((acc, key) => {
// gets all flags from each of the fields in `types`, adds those,
// then adds aliases of each flag (if any)
- TYPES[key].forEach(flag => {
+ TYPES[key].forEach((flag) => {
acc.add(flag);
const aliases = exports.aliases[flag] || [];
- aliases.forEach(alias => {
+ aliases.forEach((alias) => {
acc.add(alias);
});
});
@@ -112,8 +112,8 @@ const ALL_MOCHA_FLAGS = Object.keys(TYPES).reduce((acc, key) => {
* @returns {boolean} If `true`, this is a Mocha flag
* @private
*/
-exports.isMochaFlag = flag => {
- return ALL_MOCHA_FLAGS.has(flag.replace(/^--?/, ''));
+exports.isMochaFlag = (flag) => {
+ return ALL_MOCHA_FLAGS.has(flag.replace(/^--?/, ""));
};
/**
@@ -122,17 +122,17 @@ exports.isMochaFlag = flag => {
* @returns {string | undefined} - If flag is a valid mocha flag, the expected type of argument for this flag is returned, otherwise undefined is returned.
* @private
*/
-exports.expectedTypeForFlag = flag => {
- const normalizedName = flag.replace(/^--?/, '');
+exports.expectedTypeForFlag = (flag) => {
+ const normalizedName = flag.replace(/^--?/, "");
// If flag is an alias, get it's full name.
const aliases = exports.aliases;
const fullFlagName =
- Object.keys(aliases).find(flagName =>
- aliases[flagName].includes(normalizedName)
+ Object.keys(aliases).find((flagName) =>
+ aliases[flagName].includes(normalizedName),
) || normalizedName;
- return Object.keys(TYPES).find(flagType =>
- TYPES[flagType].includes(fullFlagName)
+ return Object.keys(TYPES).find((flagType) =>
+ TYPES[flagType].includes(fullFlagName),
);
};
diff --git a/lib/cli/run.js b/lib/cli/run.js
index 73a98325..384528fd 100644
--- a/lib/cli/run.js
+++ b/lib/cli/run.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Definition for Mocha's default ("run tests") command
@@ -7,290 +7,290 @@
* @private
*/
-const symbols = require('log-symbols');
-const pc = require('picocolors');
-const Mocha = require('../mocha');
+const symbols = require("log-symbols");
+const pc = require("picocolors");
+const Mocha = require("../mocha");
const {
createUnsupportedError,
createInvalidArgumentValueError,
- createMissingArgumentError
-} = require('../errors');
+ createMissingArgumentError,
+} = require("../errors");
const {
list,
handleRequires,
validateLegacyPlugin,
- runMocha
-} = require('./run-helpers');
-const {ONE_AND_DONES, ONE_AND_DONE_ARGS} = require('./one-and-dones');
-const debug = require('debug')('mocha:cli:run');
-const defaults = require('../mocharc.json');
-const {types, aliases} = require('./run-option-metadata');
+ runMocha,
+} = require("./run-helpers");
+const { ONE_AND_DONES, ONE_AND_DONE_ARGS } = require("./one-and-dones");
+const debug = require("debug")("mocha:cli:run");
+const defaults = require("../mocharc.json");
+const { types, aliases } = require("./run-option-metadata");
/**
* Logical option groups
* @constant
*/
const GROUPS = {
- FILES: 'File Handling',
- FILTERS: 'Test Filters',
- NODEJS: 'Node.js & V8',
- OUTPUT: 'Reporting & Output',
- RULES: 'Rules & Behavior',
- CONFIG: 'Configuration'
+ FILES: "File Handling",
+ FILTERS: "Test Filters",
+ NODEJS: "Node.js & V8",
+ OUTPUT: "Reporting & Output",
+ RULES: "Rules & Behavior",
+ CONFIG: "Configuration",
};
-exports.command = ['$0 [spec..]', 'inspect'];
+exports.command = ["$0 [spec..]", "inspect"];
-exports.describe = 'Run tests with Mocha';
+exports.describe = "Run tests with Mocha";
-exports.builder = yargs =>
+exports.builder = (yargs) =>
yargs
.options({
- 'allow-uncaught': {
- description: 'Allow uncaught errors to propagate',
- group: GROUPS.RULES
+ "allow-uncaught": {
+ description: "Allow uncaught errors to propagate",
+ group: GROUPS.RULES,
},
- 'async-only': {
+ "async-only": {
description:
- 'Require all tests to use a callback (async) or return a Promise',
- group: GROUPS.RULES
+ "Require all tests to use a callback (async) or return a Promise",
+ group: GROUPS.RULES,
},
bail: {
description: 'Abort ("bail") after first test failure',
- group: GROUPS.RULES
+ group: GROUPS.RULES,
},
- 'check-leaks': {
- description: 'Check for global variable leaks',
- group: GROUPS.RULES
+ "check-leaks": {
+ description: "Check for global variable leaks",
+ group: GROUPS.RULES,
},
color: {
- description: 'Force-enable color output',
- group: GROUPS.OUTPUT
+ description: "Force-enable color output",
+ group: GROUPS.OUTPUT,
},
config: {
config: true,
- defaultDescription: '(nearest rc file)',
- description: 'Path to config file',
- group: GROUPS.CONFIG
+ defaultDescription: "(nearest rc file)",
+ description: "Path to config file",
+ group: GROUPS.CONFIG,
},
delay: {
- description: 'Delay initial execution of root suite',
- group: GROUPS.RULES
+ description: "Delay initial execution of root suite",
+ group: GROUPS.RULES,
},
diff: {
default: true,
- description: 'Show diff on failure',
- group: GROUPS.OUTPUT
+ description: "Show diff on failure",
+ group: GROUPS.OUTPUT,
},
- 'dry-run': {
- description: 'Report tests without executing them',
- group: GROUPS.RULES
+ "dry-run": {
+ description: "Report tests without executing them",
+ group: GROUPS.RULES,
},
exit: {
- description: 'Force Mocha to quit after tests complete',
- group: GROUPS.RULES
+ description: "Force Mocha to quit after tests complete",
+ group: GROUPS.RULES,
},
extension: {
default: defaults.extension,
- description: 'File extension(s) to load',
+ description: "File extension(s) to load",
group: GROUPS.FILES,
requiresArg: true,
- coerce: list
+ coerce: list,
},
- 'pass-on-failing-test-suite': {
+ "pass-on-failing-test-suite": {
default: false,
- description: 'Not fail test run if tests were failed',
- group: GROUPS.RULES
+ description: "Not fail test run if tests were failed",
+ group: GROUPS.RULES,
},
- 'fail-zero': {
- description: 'Fail test run if no test(s) encountered',
- group: GROUPS.RULES
+ "fail-zero": {
+ description: "Fail test run if no test(s) encountered",
+ group: GROUPS.RULES,
},
fgrep: {
- conflicts: 'grep',
- description: 'Only run tests containing this string',
+ conflicts: "grep",
+ description: "Only run tests containing this string",
group: GROUPS.FILTERS,
- requiresArg: true
+ requiresArg: true,
},
file: {
- defaultDescription: '(none)',
+ defaultDescription: "(none)",
description:
- 'Specify file(s) to be loaded prior to root suite execution',
+ "Specify file(s) to be loaded prior to root suite execution",
group: GROUPS.FILES,
normalize: true,
- requiresArg: true
+ requiresArg: true,
},
- 'forbid-only': {
- description: 'Fail if exclusive test(s) encountered',
- group: GROUPS.RULES
+ "forbid-only": {
+ description: "Fail if exclusive test(s) encountered",
+ group: GROUPS.RULES,
},
- 'forbid-pending': {
- description: 'Fail if pending test(s) encountered',
- group: GROUPS.RULES
+ "forbid-pending": {
+ description: "Fail if pending test(s) encountered",
+ group: GROUPS.RULES,
},
- 'full-trace': {
- description: 'Display full stack traces',
- group: GROUPS.OUTPUT
+ "full-trace": {
+ description: "Display full stack traces",
+ group: GROUPS.OUTPUT,
},
global: {
coerce: list,
- description: 'List of allowed global variables',
+ description: "List of allowed global variables",
group: GROUPS.RULES,
- requiresArg: true
+ requiresArg: true,
},
grep: {
- coerce: value => (!value ? null : value),
- conflicts: 'fgrep',
- description: 'Only run tests matching this string or regexp',
+ coerce: (value) => (!value ? null : value),
+ conflicts: "fgrep",
+ description: "Only run tests matching this string or regexp",
group: GROUPS.FILTERS,
- requiresArg: true
+ requiresArg: true,
},
ignore: {
- defaultDescription: '(none)',
- description: 'Ignore file(s) or glob pattern(s)',
+ defaultDescription: "(none)",
+ description: "Ignore file(s) or glob pattern(s)",
group: GROUPS.FILES,
- requiresArg: true
+ requiresArg: true,
},
- 'inline-diffs': {
+ "inline-diffs": {
description:
- 'Display actual/expected differences inline within each string',
- group: GROUPS.OUTPUT
+ "Display actual/expected differences inline within each string",
+ group: GROUPS.OUTPUT,
},
invert: {
- description: 'Inverts --grep and --fgrep matches',
- group: GROUPS.FILTERS
+ description: "Inverts --grep and --fgrep matches",
+ group: GROUPS.FILTERS,
},
jobs: {
description:
- 'Number of concurrent jobs for --parallel; use 1 to run in serial',
- defaultDescription: '(number of CPU cores - 1)',
+ "Number of concurrent jobs for --parallel; use 1 to run in serial",
+ defaultDescription: "(number of CPU cores - 1)",
requiresArg: true,
- group: GROUPS.RULES
+ group: GROUPS.RULES,
},
- 'list-interfaces': {
+ "list-interfaces": {
conflicts: Array.from(ONE_AND_DONE_ARGS).filter(
- arg => arg !== 'list-interfaces'
+ (arg) => arg !== "list-interfaces",
),
- description: 'List built-in user interfaces & exit'
+ description: "List built-in user interfaces & exit",
},
- 'list-reporters': {
+ "list-reporters": {
conflicts: Array.from(ONE_AND_DONE_ARGS).filter(
- arg => arg !== 'list-reporters'
+ (arg) => arg !== "list-reporters",
),
- description: 'List built-in reporters & exit'
+ description: "List built-in reporters & exit",
},
- 'no-colors': {
- description: 'Force-disable color output',
+ "no-colors": {
+ description: "Force-disable color output",
group: GROUPS.OUTPUT,
- hidden: true
+ hidden: true,
},
- 'node-option': {
+ "node-option": {
description: 'Node or V8 option (no leading "--")',
- group: GROUPS.CONFIG
+ group: GROUPS.CONFIG,
},
package: {
- description: 'Path to package.json for config',
+ description: "Path to package.json for config",
group: GROUPS.CONFIG,
normalize: true,
- requiresArg: true
+ requiresArg: true,
},
parallel: {
- description: 'Run tests in parallel',
- group: GROUPS.RULES
+ description: "Run tests in parallel",
+ group: GROUPS.RULES,
},
- 'posix-exit-codes': {
+ "posix-exit-codes": {
description:
"Use POSIX and UNIX shell exit codes as Mocha's return value",
- group: GROUPS.RULES
+ group: GROUPS.RULES,
},
recursive: {
- description: 'Look for tests in subdirectories',
- group: GROUPS.FILES
+ description: "Look for tests in subdirectories",
+ group: GROUPS.FILES,
},
reporter: {
default: defaults.reporter,
- description: 'Specify reporter to use',
+ description: "Specify reporter to use",
group: GROUPS.OUTPUT,
- requiresArg: true
+ requiresArg: true,
},
- 'reporter-option': {
- coerce: opts =>
+ "reporter-option": {
+ coerce: (opts) =>
list(opts).reduce((acc, opt) => {
- const pair = opt.split('=');
+ const pair = opt.split("=");
if (pair.length > 2 || !pair.length) {
throw createInvalidArgumentValueError(
`invalid reporter option '${opt}'`,
- '--reporter-option',
+ "--reporter-option",
opt,
- 'expected "key=value" format'
+ 'expected "key=value" format',
);
}
acc[pair[0]] = pair.length === 2 ? pair[1] : true;
return acc;
}, {}),
- description: 'Reporter-specific options (<k=v,[k1=v1,..]>)',
+ description: "Reporter-specific options (<k=v,[k1=v1,..]>)",
group: GROUPS.OUTPUT,
- requiresArg: true
+ requiresArg: true,
},
require: {
- defaultDescription: '(none)',
- description: 'Require module',
+ defaultDescription: "(none)",
+ description: "Require module",
group: GROUPS.FILES,
- requiresArg: true
+ requiresArg: true,
},
retries: {
- description: 'Retry failed tests this many times',
- group: GROUPS.RULES
+ description: "Retry failed tests this many times",
+ group: GROUPS.RULES,
},
slow: {
default: defaults.slow,
description: 'Specify "slow" test threshold (in milliseconds)',
- group: GROUPS.RULES
+ group: GROUPS.RULES,
},
sort: {
- description: 'Sort test files',
- group: GROUPS.FILES
+ description: "Sort test files",
+ group: GROUPS.FILES,
},
timeout: {
default: defaults.timeout,
- description: 'Specify test timeout threshold (in milliseconds)',
- group: GROUPS.RULES
+ description: "Specify test timeout threshold (in milliseconds)",
+ group: GROUPS.RULES,
},
ui: {
default: defaults.ui,
- description: 'Specify user interface',
+ description: "Specify user interface",
group: GROUPS.RULES,
- requiresArg: true
+ requiresArg: true,
},
watch: {
- description: 'Watch files in the current working directory for changes',
- group: GROUPS.FILES
+ description: "Watch files in the current working directory for changes",
+ group: GROUPS.FILES,
},
- 'watch-files': {
- description: 'List of paths or globs to watch',
+ "watch-files": {
+ description: "List of paths or globs to watch",
group: GROUPS.FILES,
requiresArg: true,
- coerce: list
+ coerce: list,
},
- 'watch-ignore': {
- description: 'List of paths or globs to exclude from watching',
+ "watch-ignore": {
+ description: "List of paths or globs to exclude from watching",
group: GROUPS.FILES,
requiresArg: true,
coerce: list,
- default: defaults['watch-ignore']
- }
+ default: defaults["watch-ignore"],
+ },
})
- .positional('spec', {
- default: ['test'],
- description: 'One or more files, directories, or globs to test',
- type: 'array'
+ .positional("spec", {
+ default: ["test"],
+ description: "One or more files, directories, or globs to test",
+ type: "array",
})
- .check(argv => {
+ .check((argv) => {
// "one-and-dones"; let yargs handle help and version
- Object.keys(ONE_AND_DONES).forEach(opt => {
+ Object.keys(ONE_AND_DONES).forEach((opt) => {
if (argv[opt]) {
ONE_AND_DONES[opt].call(null, yargs);
process.exit();
@@ -298,11 +298,11 @@ exports.builder = yargs =>
});
// yargs.implies() isn't flexible enough to handle this
- if (argv.invert && !('fgrep' in argv || 'grep' in argv)) {
+ if (argv.invert && !("fgrep" in argv || "grep" in argv)) {
throw createMissingArgumentError(
'"--invert" requires one of "--fgrep <str>" or "--grep <regexp>"',
- '--fgrep|--grep',
- 'string|regexp'
+ "--fgrep|--grep",
+ "string|regexp",
);
}
@@ -310,32 +310,32 @@ exports.builder = yargs =>
// yargs.conflicts() can't deal with `--file foo.js --no-parallel`, either
if (argv.file) {
throw createUnsupportedError(
- '--parallel runs test files in a non-deterministic order, and is mutually exclusive with --file'
+ "--parallel runs test files in a non-deterministic order, and is mutually exclusive with --file",
);
}
// or this
if (argv.sort) {
throw createUnsupportedError(
- '--parallel runs test files in a non-deterministic order, and is mutually exclusive with --sort'
+ "--parallel runs test files in a non-deterministic order, and is mutually exclusive with --sort",
);
}
- if (argv.reporter === 'progress') {
+ if (argv.reporter === "progress") {
throw createUnsupportedError(
- '--reporter=progress is mutually exclusive with --parallel'
+ "--reporter=progress is mutually exclusive with --parallel",
);
}
- if (argv.reporter === 'markdown') {
+ if (argv.reporter === "markdown") {
throw createUnsupportedError(
- '--reporter=markdown is mutually exclusive with --parallel'
+ "--reporter=markdown is mutually exclusive with --parallel",
);
}
- if (argv.reporter === 'json-stream') {
+ if (argv.reporter === "json-stream") {
throw createUnsupportedError(
- '--reporter=json-stream is mutually exclusive with --parallel'
+ "--reporter=json-stream is mutually exclusive with --parallel",
);
}
}
@@ -343,7 +343,7 @@ exports.builder = yargs =>
if (argv.compilers) {
throw createUnsupportedError(
`--compilers is DEPRECATED and no longer supported.
- See https://github.com/mochajs/mocha/wiki/compilers-deprecation for migration information.`
+ See https://github.com/mochajs/mocha/wiki/compilers-deprecation for migration information.`,
);
}
@@ -354,12 +354,12 @@ exports.builder = yargs =>
try {
// load requires first, because it can impact "plugin" validation
const plugins = await handleRequires(argv.require);
- validateLegacyPlugin(argv, 'reporter', Mocha.reporters);
- validateLegacyPlugin(argv, 'ui', Mocha.interfaces);
+ validateLegacyPlugin(argv, "reporter", Mocha.reporters);
+ validateLegacyPlugin(argv, "ui", Mocha.interfaces);
Object.assign(argv, plugins);
} catch (err) {
// this could be a bad --require, bad reporter, ui, etc.
- console.error(`\n${symbols.error} ${pc.red('ERROR:')}`, err);
+ console.error(`\n${symbols.error} ${pc.red("ERROR:")}`, err);
yargs.exit(1);
}
})
@@ -370,13 +370,13 @@ exports.builder = yargs =>
.alias(aliases);
exports.handler = async function (argv) {
- debug('post-yargs config', argv);
+ debug("post-yargs config", argv);
const mocha = new Mocha(argv);
try {
await runMocha(mocha, argv);
} catch (err) {
- console.error('\n Exception during run:', err);
+ console.error("\n Exception during run:", err);
process.exit(1);
}
};
diff --git a/lib/cli/watch-run.js b/lib/cli/watch-run.js
index 5fc1f7d6..72f161a8 100644
--- a/lib/cli/watch-run.js
+++ b/lib/cli/watch-run.js
@@ -1,14 +1,14 @@
-'use strict';
-
-const logSymbols = require('log-symbols');
-const debug = require('debug')('mocha:cli:watch');
-const path = require('node:path');
-const chokidar = require('chokidar');
-const glob = require('glob');
-const isPathInside = require('is-path-inside');
-const {minimatch} = require('minimatch');
-const Context = require('../context');
-const collectFiles = require('./collect-files');
+"use strict";
+
+const logSymbols = require("log-symbols");
+const debug = require("debug")("mocha:cli:watch");
+const path = require("node:path");
+const chokidar = require("chokidar");
+const glob = require("glob");
+const isPathInside = require("is-path-inside");
+const { minimatch } = require("minimatch");
+const Context = require("../context");
+const collectFiles = require("./collect-files");
/**
* @typedef {import('chokidar').FSWatcher} FSWatcher
@@ -46,15 +46,15 @@ const collectFiles = require('./collect-files');
*/
exports.watchParallelRun = (
mocha,
- {watchFiles, watchIgnore},
- fileCollectParams
+ { watchFiles, watchIgnore },
+ fileCollectParams,
) => {
- debug('creating parallel watcher');
+ debug("creating parallel watcher");
return createWatcher(mocha, {
watchFiles,
watchIgnore,
- beforeRun({mocha}) {
+ beforeRun({ mocha }) {
// I don't know why we're cloning the root suite.
const rootSuite = mocha.suite.clone();
@@ -64,7 +64,7 @@ exports.watchParallelRun = (
// this `require` is needed because the require cache has been cleared. the dynamic
// exports set via the below call to `mocha.ui()` won't work properly if a
// test depends on this module.
- const Mocha = require('../mocha');
+ const Mocha = require("../mocha");
// ... and now that we've gotten a new module, we need to use it again due
// to `mocha.ui()` call
@@ -90,7 +90,7 @@ exports.watchParallelRun = (
newMocha.lazyLoadFiles(true);
return newMocha;
},
- fileCollectParams
+ fileCollectParams,
});
};
@@ -108,13 +108,13 @@ exports.watchParallelRun = (
* file collection. See `lib/cli/collect-files.js`.
* @private
*/
-exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
- debug('creating serial watcher');
+exports.watchRun = (mocha, { watchFiles, watchIgnore }, fileCollectParams) => {
+ debug("creating serial watcher");
return createWatcher(mocha, {
watchFiles,
watchIgnore,
- beforeRun({mocha}) {
+ beforeRun({ mocha }) {
mocha.unloadFiles();
// I don't know why we're cloning the root suite.
@@ -126,7 +126,7 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
// this `require` is needed because the require cache has been cleared. the dynamic
// exports set via the below call to `mocha.ui()` won't work properly if a
// test depends on this module.
- const Mocha = require('../mocha');
+ const Mocha = require("../mocha");
// ... and now that we've gotten a new module, we need to use it again due
// to `mocha.ui()` call
@@ -149,7 +149,7 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
return newMocha;
},
- fileCollectParams
+ fileCollectParams,
});
};
@@ -163,35 +163,35 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
* @private
*/
function createPathFilter(globPaths, basePath) {
- debug('creating path filter from glob paths: %s', globPaths);
+ debug("creating path filter from glob paths: %s", globPaths);
/**
* The resulting object to filter paths.
* @type {PathFilter}
*/
const res = {
- dir: {paths: new Set(), globs: new Set()},
- match: {paths: new Set(), globs: new Set()}
+ dir: { paths: new Set(), globs: new Set() },
+ match: { paths: new Set(), globs: new Set() },
};
// for checking if a path ends with `/**/*`
- const globEnd = path.join(path.sep, '**', '*');
+ const globEnd = path.join(path.sep, "**", "*");
/**
* The current glob pattern to check.
* @type {Pattern[]}
*/
- const patterns = globPaths.flatMap(globPath => {
+ const patterns = globPaths.flatMap((globPath) => {
return new glob.Glob(globPath, {
dot: true,
magicalBraces: true,
- windowsPathsNoEscape: true
+ windowsPathsNoEscape: true,
}).patterns;
}, []);
// each pattern will have its own path because of the `magicalBraces` option
for (const pattern of patterns) {
- debug('processing glob pattern: %s', pattern.globString());
+ debug("processing glob pattern: %s", pattern.globString());
/**
* Path segments before the glob pattern.
@@ -209,11 +209,11 @@ function createPathFilter(globPaths, basePath) {
do {
// save string patterns until a non-string (glob or regexp) is matched
const entry = currentPattern.pattern();
- const isString = typeof entry === 'string';
+ const isString = typeof entry === "string";
debug(
- 'found %s pattern: %s',
- isString ? 'string' : 'glob or regexp',
- entry
+ "found %s pattern: %s",
+ isString ? "string" : "glob or regexp",
+ entry,
);
if (!isString) {
// if the entry is a glob
@@ -226,28 +226,28 @@ function createPathFilter(globPaths, basePath) {
// go to next pattern
} while ((currentPattern = currentPattern.rest()));
if (!isGlob) {
- debug('all subpatterns of %j processed', pattern.globString());
+ debug("all subpatterns of %j processed", pattern.globString());
}
// match `cleanPath` (path without the glob part) and its subdirectories
const cleanPath = path.resolve(basePath, ...segments);
- debug('clean path: %s', cleanPath);
+ debug("clean path: %s", cleanPath);
res.dir.paths.add(cleanPath);
- res.dir.globs.add(path.resolve(cleanPath, '**', '*'));
+ res.dir.globs.add(path.resolve(cleanPath, "**", "*"));
// match `absPath` and all of its contents
const absPath = path.resolve(basePath, pattern.globString());
- debug('absolute path: %s', absPath);
+ debug("absolute path: %s", absPath);
(isGlob ? res.match.globs : res.match.paths).add(absPath);
// always include `/**/*` to the full pattern for matching
// since it's possible for the last path segment to be a directory
if (!absPath.endsWith(globEnd)) {
- res.match.globs.add(path.resolve(absPath, '**', '*'));
+ res.match.globs.add(path.resolve(absPath, "**", "*"));
}
}
- debug('returning path filter: %o', res);
+ debug("returning path filter: %o", res);
return res;
}
@@ -276,7 +276,7 @@ function matchPattern(filePath, pattern, matchParent) {
// loop through the set of glob paths instead of converting it into an array
for (const globPath of pattern.globs) {
if (
- minimatch(filePath, globPath, {dot: true, windowsPathsNoEscape: true})
+ minimatch(filePath, globPath, { dot: true, windowsPathsNoEscape: true })
) {
return true;
}
@@ -296,9 +296,9 @@ function matchPattern(filePath, pattern, matchParent) {
*/
function createPathMatcher(allowed, ignored, basePath) {
debug(
- 'creating path matcher from allowed: %o, ignored: %o',
+ "creating path matcher from allowed: %o, ignored: %o",
allowed,
- ignored
+ ignored,
);
/**
@@ -379,7 +379,7 @@ function createPathMatcher(allowed, ignored, basePath) {
cache(ignoreCache, filePath, ignore);
return ignore;
- }
+ },
};
return matcher;
@@ -404,14 +404,14 @@ function createPathMatcher(allowed, ignored, basePath) {
*/
const createWatcher = (
mocha,
- {watchFiles, watchIgnore, beforeRun, fileCollectParams}
+ { watchFiles, watchIgnore, beforeRun, fileCollectParams },
) => {
if (!watchFiles) {
- watchFiles = fileCollectParams.extension.map(ext => `**/*.${ext}`);
+ watchFiles = fileCollectParams.extension.map((ext) => `**/*.${ext}`);
}
- debug('watching files: %s', watchFiles);
- debug('ignoring files matching: %s', watchIgnore);
+ debug("watching files: %s", watchFiles);
+ debug("ignoring files matching: %s", watchIgnore);
let globalFixtureContext;
// we handle global fixtures manually
@@ -431,23 +431,23 @@ const createWatcher = (
// Chokidar has to watch the directory paths in case new files are created
const watcher = chokidar.watch(Array.from(allowed.dir.paths), {
ignoreInitial: true,
- ignored: matcher.ignore
+ ignored: matcher.ignore,
});
const rerunner = createRerunner(mocha, watcher, {
- beforeRun
+ beforeRun,
});
- watcher.on('ready', async () => {
- debug('watcher ready');
+ watcher.on("ready", async () => {
+ debug("watcher ready");
if (!globalFixtureContext) {
- debug('triggering global setup');
+ debug("triggering global setup");
globalFixtureContext = await mocha.runGlobalSetup();
}
rerunner.run();
});
- watcher.on('all', (_event, filePath) => {
+ watcher.on("all", (_event, filePath) => {
// only allow file paths that match the allowed patterns
if (matcher.allow(filePath)) {
rerunner.scheduleRun();
@@ -455,7 +455,7 @@ const createWatcher = (
});
hideCursor();
- process.on('exit', () => {
+ process.on("exit", () => {
showCursor();
});
@@ -468,21 +468,21 @@ const createWatcher = (
// there may be another way to solve this, but it too will be a hack.
// for our watch tests on win32 we must _fork_ mocha with an IPC channel
if (process.connected) {
- process.on('message', msg => {
- if (msg === 'SIGINT') {
- process.emit('SIGINT');
+ process.on("message", (msg) => {
+ if (msg === "SIGINT") {
+ process.emit("SIGINT");
}
});
}
let exiting = false;
- process.on('SIGINT', async () => {
+ process.on("SIGINT", async () => {
showCursor();
console.error(`${logSymbols.warning} [mocha] cleaning up, please wait...`);
if (!exiting) {
exiting = true;
if (mocha.hasGlobalTeardownFixtures()) {
- debug('running global teardown');
+ debug("running global teardown");
try {
await mocha.runGlobalTeardown(globalFixtureContext);
} catch (err) {
@@ -495,10 +495,10 @@ const createWatcher = (
// Keyboard shortcut for restarting when "rs\n" is typed (ala Nodemon)
process.stdin.resume();
- process.stdin.setEncoding('utf8');
- process.stdin.on('data', data => {
+ process.stdin.setEncoding("utf8");
+ process.stdin.on("data", (data) => {
const str = data.toString().trim().toLowerCase();
- if (str === 'rs') rerunner.scheduleRun();
+ if (str === "rs") rerunner.scheduleRun();
});
return watcher;
@@ -515,7 +515,7 @@ const createWatcher = (
* @ignore
* @private
*/
-const createRerunner = (mocha, watcher, {beforeRun} = {}) => {
+const createRerunner = (mocha, watcher, { beforeRun } = {}) => {
// Set to a `Runner` when mocha is running. Set to `null` when mocha is not
// running.
let runner = null;
@@ -525,9 +525,9 @@ const createRerunner = (mocha, watcher, {beforeRun} = {}) => {
const run = () => {
try {
- mocha = beforeRun ? beforeRun({mocha, watcher}) || mocha : mocha;
+ mocha = beforeRun ? beforeRun({ mocha, watcher }) || mocha : mocha;
runner = mocha.run(() => {
- debug('finished watch run');
+ debug("finished watch run");
runner = null;
blastCache(watcher);
if (rerunScheduled) {
@@ -562,7 +562,7 @@ const createRerunner = (mocha, watcher, {beforeRun} = {}) => {
return {
scheduleRun,
- run
+ run,
};
};
@@ -574,14 +574,14 @@ const createRerunner = (mocha, watcher, {beforeRun} = {}) => {
* @ignore
* @private
*/
-const getWatchedFiles = watcher => {
+const getWatchedFiles = (watcher) => {
const watchedDirs = watcher.getWatched();
return Object.keys(watchedDirs).reduce(
(acc, dir) => [
...acc,
- ...watchedDirs[dir].map(file => path.join(dir, file))
+ ...watchedDirs[dir].map((file) => path.join(dir, file)),
],
- []
+ [],
);
};
@@ -591,7 +591,7 @@ const getWatchedFiles = watcher => {
* @private
*/
const hideCursor = () => {
- process.stdout.write('\u001b[?25l');
+ process.stdout.write("\u001b[?25l");
};
/**
@@ -600,7 +600,7 @@ const hideCursor = () => {
* @private
*/
const showCursor = () => {
- process.stdout.write('\u001b[?25h');
+ process.stdout.write("\u001b[?25h");
};
/**
@@ -608,7 +608,7 @@ const showCursor = () => {
* @private
*/
const eraseLine = () => {
- process.stdout.write('\u001b[2K');
+ process.stdout.write("\u001b[2K");
};
/**
@@ -617,10 +617,10 @@ const eraseLine = () => {
* @ignore
* @private
*/
-const blastCache = watcher => {
+const blastCache = (watcher) => {
const files = getWatchedFiles(watcher);
- files.forEach(file => {
+ files.forEach((file) => {
delete require.cache[file];
});
- debug('deleted %d file(s) from the require cache', files.length);
+ debug("deleted %d file(s) from the require cache", files.length);
};
diff --git a/lib/context.js b/lib/context.js
index 247a1c17..900a0f4d 100644
--- a/lib/context.js
+++ b/lib/context.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('./runnable.js')} Runnable
diff --git a/lib/error-constants.js b/lib/error-constants.js
index 62e1034d..362078b0 100644
--- a/lib/error-constants.js
+++ b/lib/error-constants.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* When Mocha throws exceptions (or rejects `Promise`s), it attempts to assign a `code` property to the `Error` object, for easier handling. These are the potential values of `code`.
@@ -12,112 +12,112 @@ var constants = {
* @constant
* @default
*/
- FATAL: 'ERR_MOCHA_FATAL',
+ FATAL: "ERR_MOCHA_FATAL",
/**
* The type of an argument to a function call is invalid
* @constant
* @default
*/
- INVALID_ARG_TYPE: 'ERR_MOCHA_INVALID_ARG_TYPE',
+ INVALID_ARG_TYPE: "ERR_MOCHA_INVALID_ARG_TYPE",
/**
* The value of an argument to a function call is invalid
* @constant
* @default
*/
- INVALID_ARG_VALUE: 'ERR_MOCHA_INVALID_ARG_VALUE',
+ INVALID_ARG_VALUE: "ERR_MOCHA_INVALID_ARG_VALUE",
/**
* Something was thrown, but it wasn't an `Error`
* @constant
* @default
*/
- INVALID_EXCEPTION: 'ERR_MOCHA_INVALID_EXCEPTION',
+ INVALID_EXCEPTION: "ERR_MOCHA_INVALID_EXCEPTION",
/**
* An interface (e.g., `Mocha.interfaces`) is unknown or invalid
* @constant
* @default
*/
- INVALID_INTERFACE: 'ERR_MOCHA_INVALID_INTERFACE',
+ INVALID_INTERFACE: "ERR_MOCHA_INVALID_INTERFACE",
/**
* A reporter (.e.g, `Mocha.reporters`) is unknown or invalid
* @constant
* @default
*/
- INVALID_REPORTER: 'ERR_MOCHA_INVALID_REPORTER',
+ INVALID_REPORTER: "ERR_MOCHA_INVALID_REPORTER",
/**
* `done()` was called twice in a `Test` or `Hook` callback
* @constant
* @default
*/
- MULTIPLE_DONE: 'ERR_MOCHA_MULTIPLE_DONE',
+ MULTIPLE_DONE: "ERR_MOCHA_MULTIPLE_DONE",
/**
* No files matched the pattern provided by the user
* @constant
* @default
*/
- NO_FILES_MATCH_PATTERN: 'ERR_MOCHA_NO_FILES_MATCH_PATTERN',
+ NO_FILES_MATCH_PATTERN: "ERR_MOCHA_NO_FILES_MATCH_PATTERN",
/**
* Known, but unsupported behavior of some kind
* @constant
* @default
*/
- UNSUPPORTED: 'ERR_MOCHA_UNSUPPORTED',
+ UNSUPPORTED: "ERR_MOCHA_UNSUPPORTED",
/**
* Invalid state transition occurring in `Mocha` instance
* @constant
* @default
*/
- INSTANCE_ALREADY_RUNNING: 'ERR_MOCHA_INSTANCE_ALREADY_RUNNING',
+ INSTANCE_ALREADY_RUNNING: "ERR_MOCHA_INSTANCE_ALREADY_RUNNING",
/**
* Invalid state transition occurring in `Mocha` instance
* @constant
* @default
*/
- INSTANCE_ALREADY_DISPOSED: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED',
+ INSTANCE_ALREADY_DISPOSED: "ERR_MOCHA_INSTANCE_ALREADY_DISPOSED",
/**
* Use of `only()` w/ `--forbid-only` results in this error.
* @constant
* @default
*/
- FORBIDDEN_EXCLUSIVITY: 'ERR_MOCHA_FORBIDDEN_EXCLUSIVITY',
+ FORBIDDEN_EXCLUSIVITY: "ERR_MOCHA_FORBIDDEN_EXCLUSIVITY",
/**
* To be thrown when a user-defined plugin implementation (e.g., `mochaHooks`) is invalid
* @constant
* @default
*/
- INVALID_PLUGIN_IMPLEMENTATION: 'ERR_MOCHA_INVALID_PLUGIN_IMPLEMENTATION',
+ INVALID_PLUGIN_IMPLEMENTATION: "ERR_MOCHA_INVALID_PLUGIN_IMPLEMENTATION",
/**
* To be thrown when a builtin or third-party plugin definition (the _definition_ of `mochaHooks`) is invalid
* @constant
* @default
*/
- INVALID_PLUGIN_DEFINITION: 'ERR_MOCHA_INVALID_PLUGIN_DEFINITION',
+ INVALID_PLUGIN_DEFINITION: "ERR_MOCHA_INVALID_PLUGIN_DEFINITION",
/**
* When a runnable exceeds its allowed run time.
* @constant
* @default
*/
- TIMEOUT: 'ERR_MOCHA_TIMEOUT',
+ TIMEOUT: "ERR_MOCHA_TIMEOUT",
/**
* Input file is not able to be parsed
* @constant
* @default
*/
- UNPARSABLE_FILE: 'ERR_MOCHA_UNPARSABLE_FILE'
+ UNPARSABLE_FILE: "ERR_MOCHA_UNPARSABLE_FILE",
};
module.exports = { constants };
diff --git a/lib/errors.js b/lib/errors.js
index 79786c24..cc2d5b8a 100644
--- a/lib/errors.js
+++ b/lib/errors.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('./mocha.js')} Mocha
@@ -7,8 +7,8 @@
* @typedef {import('./types.d.ts').PluginDefinition} PluginDefinition
*/
-const {format} = require('node:util');
-const { constants } = require('./error-constants.js');
+const { format } = require("node:util");
+const { constants } = require("./error-constants.js");
/**
* Contains error codes, factory functions to create throwable error objects,
@@ -27,7 +27,7 @@ const emitWarning = (msg, type) => {
} else {
/* istanbul ignore next */
process.nextTick(function () {
- console.warn(type + ': ' + msg);
+ console.warn(type + ": " + msg);
});
}
};
@@ -39,11 +39,11 @@ const emitWarning = (msg, type) => {
* @param {string} [msg] - Warning to print
* @private
*/
-const deprecate = msg => {
+const deprecate = (msg) => {
msg = String(msg);
if (msg && !deprecate.cache[msg]) {
deprecate.cache[msg] = true;
- emitWarning(msg, 'DeprecationWarning');
+ emitWarning(msg, "DeprecationWarning");
}
};
deprecate.cache = {};
@@ -55,7 +55,7 @@ deprecate.cache = {};
* @param {string} [msg] - Warning to print
* @private
*/
-const warn = msg => {
+const warn = (msg) => {
if (msg) {
emitWarning(msg);
}
@@ -177,7 +177,7 @@ function createInvalidArgumentValueError(message, argument, value, reason) {
err.code = constants.INVALID_ARG_VALUE;
err.argument = argument;
err.value = value;
- err.reason = typeof reason !== 'undefined' ? reason : 'is invalid';
+ err.reason = typeof reason !== "undefined" ? reason : "is invalid";
return err;
}
@@ -225,9 +225,9 @@ function createFatalError(message, value) {
*/
function createInvalidLegacyPluginError(message, pluginType, pluginId) {
switch (pluginType) {
- case 'reporter':
+ case "reporter":
return createInvalidReporterError(message, pluginId);
- case 'ui':
+ case "ui":
return createInvalidInterfaceError(message, pluginId);
default:
throw new Error('unknown pluginType "' + pluginType + '"');
@@ -246,7 +246,7 @@ function createInvalidLegacyPluginError(message, pluginType, pluginId) {
* @returns {Error}
*/
function createInvalidPluginError(...args) {
- deprecate('Use createInvalidLegacyPluginError() instead');
+ deprecate("Use createInvalidLegacyPluginError() instead");
return createInvalidLegacyPluginError(...args);
}
@@ -260,7 +260,7 @@ function createInvalidPluginError(...args) {
function createMochaInstanceAlreadyDisposedError(
message,
cleanReferencesAfterRun,
- instance
+ instance,
) {
var err = new Error(message);
err.code = constants.INSTANCE_ALREADY_DISPOSED;
@@ -294,23 +294,23 @@ function createMochaInstanceAlreadyRunningError(message, instance) {
function createMultipleDoneError(runnable, originalErr) {
var title;
try {
- title = format('<%s>', runnable.fullTitle());
+ title = format("<%s>", runnable.fullTitle());
if (runnable.parent.root) {
- title += ' (of root suite)';
+ title += " (of root suite)";
}
} catch (ignored) {
- title = format('<%s> (of unknown suite)', runnable.title);
+ title = format("<%s> (of unknown suite)", runnable.title);
}
var message = format(
- 'done() called multiple times in %s %s',
- runnable.type ? runnable.type : 'unknown runnable',
- title
+ "done() called multiple times in %s %s",
+ runnable.type ? runnable.type : "unknown runnable",
+ title,
);
if (runnable.file) {
- message += format(' of file %s', runnable.file);
+ message += format(" of file %s", runnable.file);
}
if (originalErr) {
- message += format('; in addition, done() received error: %s', originalErr);
+ message += format("; in addition, done() received error: %s", originalErr);
}
var err = new Error(message);
@@ -331,8 +331,8 @@ function createMultipleDoneError(runnable, originalErr) {
function createForbiddenExclusivityError(mocha) {
var err = new Error(
mocha.isWorker
- ? '`.only` is not supported in parallel mode'
- : '`.only` forbidden by --forbid-only'
+ ? "`.only` is not supported in parallel mode"
+ : "`.only` forbidden by --forbid-only",
);
err.code = constants.FORBIDDEN_EXCLUSIVITY;
return err;
@@ -365,7 +365,7 @@ function createInvalidPluginDefinitionError(msg, pluginDef) {
*/
function createInvalidPluginImplementationError(
msg,
- {pluginDef, pluginImpl} = {}
+ { pluginDef, pluginImpl } = {},
) {
const err = new Error(msg);
err.code = constants.INVALID_PLUGIN_IMPLEMENTATION;
@@ -411,8 +411,8 @@ function createUnparsableFileError(message) {
* @param {*} err - Error, or anything
* @returns {boolean}
*/
-const isMochaError = err =>
- Boolean(err && typeof err === 'object' && MOCHA_ERRORS.has(err.code));
+const isMochaError = (err) =>
+ Boolean(err && typeof err === "object" && MOCHA_ERRORS.has(err.code));
module.exports = {
createFatalError,
@@ -436,5 +436,5 @@ module.exports = {
createUnsupportedError,
deprecate,
isMochaError,
- warn
+ warn,
};
diff --git a/lib/hook.js b/lib/hook.js
index 862271e7..fb50d825 100644
--- a/lib/hook.js
+++ b/lib/hook.js
@@ -1,8 +1,8 @@
-'use strict';
+"use strict";
-var Runnable = require('./runnable');
-const {inherits, constants} = require('./utils');
-const {MOCHA_ID_PROP_NAME} = constants;
+var Runnable = require("./runnable");
+const { inherits, constants } = require("./utils");
+const { MOCHA_ID_PROP_NAME } = constants;
/**
* Expose `Hook`.
@@ -20,7 +20,7 @@ module.exports = Hook;
*/
function Hook(title, fn) {
Runnable.call(this, title, fn);
- this.type = 'hook';
+ this.type = "hook";
}
/**
@@ -71,19 +71,19 @@ Hook.prototype.serialize = function serialize() {
? {
currentTest: {
title: this.ctx.currentTest.title,
- [MOCHA_ID_PROP_NAME]: this.ctx.currentTest.id
- }
+ [MOCHA_ID_PROP_NAME]: this.ctx.currentTest.id,
+ },
}
: {},
duration: this.duration,
file: this.file,
parent: {
$$fullTitle: this.parent.fullTitle(),
- [MOCHA_ID_PROP_NAME]: this.parent.id
+ [MOCHA_ID_PROP_NAME]: this.parent.id,
},
state: this.state,
title: this.title,
type: this.type,
- [MOCHA_ID_PROP_NAME]: this.id
+ [MOCHA_ID_PROP_NAME]: this.id,
};
};
diff --git a/lib/interfaces/bdd.js b/lib/interfaces/bdd.js
index 60b4de4a..231fa907 100644
--- a/lib/interfaces/bdd.js
+++ b/lib/interfaces/bdd.js
@@ -1,12 +1,12 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../suite.js')} Suite
*/
-var Test = require('../test');
+var Test = require("../test");
var EVENT_FILE_PRE_REQUIRE =
- require('../suite').constants.EVENT_FILE_PRE_REQUIRE;
+ require("../suite").constants.EVENT_FILE_PRE_REQUIRE;
/**
* BDD-style interface:
@@ -29,7 +29,7 @@ module.exports = function bddInterface(suite) {
var suites = [suite];
suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) {
- var common = require('./common')(suites, context, mocha);
+ var common = require("./common")(suites, context, mocha);
context.before = common.before;
context.after = common.after;
@@ -46,7 +46,7 @@ module.exports = function bddInterface(suite) {
return common.suite.create({
title,
file,
- fn
+ fn,
});
};
@@ -61,7 +61,7 @@ module.exports = function bddInterface(suite) {
return common.suite.skip({
title,
file,
- fn
+ fn,
});
};
@@ -73,7 +73,7 @@ module.exports = function bddInterface(suite) {
return common.suite.only({
title,
file,
- fn
+ fn,
});
};
@@ -115,4 +115,4 @@ module.exports = function bddInterface(suite) {
});
};
-module.exports.description = 'BDD or RSpec style [default]';
+module.exports.description = "BDD or RSpec style [default]";
diff --git a/lib/interfaces/common.js b/lib/interfaces/common.js
index 1e9f148c..a1406225 100644
--- a/lib/interfaces/common.js
+++ b/lib/interfaces/common.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../context.js')} Context
@@ -9,8 +9,8 @@
@module interfaces/common
*/
-var Suite = require('../suite');
-var errors = require('../errors');
+var Suite = require("../suite");
+var errors = require("../errors");
var createMissingArgumentError = errors.createMissingArgumentError;
var createUnsupportedError = errors.createUnsupportedError;
var createForbiddenExclusivityError = errors.createForbiddenExclusivityError;
@@ -147,26 +147,26 @@ module.exports = function (suites, context, mocha) {
mocha.options.forbidPending &&
shouldBeTested(suite)
) {
- throw createUnsupportedError('Pending test forbidden');
+ throw createUnsupportedError("Pending test forbidden");
}
- if (typeof opts.fn === 'function') {
+ if (typeof opts.fn === "function") {
opts.fn.call(suite);
suites.shift();
- } else if (typeof opts.fn === 'undefined' && !suite.pending) {
+ } else if (typeof opts.fn === "undefined" && !suite.pending) {
throw createMissingArgumentError(
'Suite "' +
suite.fullTitle() +
'" was defined but no callback was supplied. ' +
- 'Supply a callback or explicitly skip the suite.',
- 'callback',
- 'function'
+ "Supply a callback or explicitly skip the suite.",
+ "callback",
+ "function",
);
} else if (!opts.fn && suite.pending) {
suites.shift();
}
return suite;
- }
+ },
},
test: {
@@ -192,7 +192,7 @@ module.exports = function (suites, context, mocha) {
*/
skip: function (title) {
context.test(title);
- }
- }
+ },
+ },
};
};
diff --git a/lib/interfaces/exports.js b/lib/interfaces/exports.js
index 79b762b5..fac6aedb 100644
--- a/lib/interfaces/exports.js
+++ b/lib/interfaces/exports.js
@@ -1,6 +1,6 @@
-'use strict';
-var Suite = require('../suite');
-var Test = require('../test');
+"use strict";
+var Suite = require("../suite");
+var Test = require("../test");
/**
* Exports-style (as Node.js module) interface:
@@ -27,19 +27,19 @@ module.exports = function (suite) {
function visit(obj, file) {
var suite;
for (var key in obj) {
- if (typeof obj[key] === 'function') {
+ if (typeof obj[key] === "function") {
var fn = obj[key];
switch (key) {
- case 'before':
+ case "before":
suites[0].beforeAll(fn);
break;
- case 'after':
+ case "after":
suites[0].afterAll(fn);
break;
- case 'beforeEach':
+ case "beforeEach":
suites[0].beforeEach(fn);
break;
- case 'afterEach':
+ case "afterEach":
suites[0].afterEach(fn);
break;
default:
diff --git a/lib/interfaces/index.js b/lib/interfaces/index.js
index 0bd810ab..48ad0fd1 100644
--- a/lib/interfaces/index.js
+++ b/lib/interfaces/index.js
@@ -1,6 +1,6 @@
-'use strict';
+"use strict";
-exports.bdd = require('./bdd');
-exports.tdd = require('./tdd');
-exports.qunit = require('./qunit');
-exports.exports = require('./exports');
+exports.bdd = require("./bdd");
+exports.tdd = require("./tdd");
+exports.qunit = require("./qunit");
+exports.exports = require("./exports");
diff --git a/lib/interfaces/qunit.js b/lib/interfaces/qunit.js
index fc7adaa3..c47d48d9 100644
--- a/lib/interfaces/qunit.js
+++ b/lib/interfaces/qunit.js
@@ -1,11 +1,11 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../suite.js')} Suite
*/
-var Test = require('../test');
+var Test = require("../test");
var EVENT_FILE_PRE_REQUIRE =
- require('../suite').constants.EVENT_FILE_PRE_REQUIRE;
+ require("../suite").constants.EVENT_FILE_PRE_REQUIRE;
/**
* QUnit-style interface:
@@ -36,7 +36,7 @@ module.exports = function qUnitInterface(suite) {
var suites = [suite];
suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) {
- var common = require('./common')(suites, context, mocha);
+ var common = require("./common")(suites, context, mocha);
context.before = common.before;
context.after = common.after;
@@ -54,7 +54,7 @@ module.exports = function qUnitInterface(suite) {
return common.suite.create({
title,
file,
- fn: false
+ fn: false,
});
};
@@ -69,7 +69,7 @@ module.exports = function qUnitInterface(suite) {
return common.suite.only({
title,
file,
- fn: false
+ fn: false,
});
};
@@ -98,4 +98,4 @@ module.exports = function qUnitInterface(suite) {
});
};
-module.exports.description = 'QUnit style';
+module.exports.description = "QUnit style";
diff --git a/lib/interfaces/tdd.js b/lib/interfaces/tdd.js
index c917c1ca..6b669814 100644
--- a/lib/interfaces/tdd.js
+++ b/lib/interfaces/tdd.js
@@ -1,12 +1,12 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../suite.js')} Suite
*/
-var Test = require('../test');
+var Test = require("../test");
var EVENT_FILE_PRE_REQUIRE =
- require('../suite').constants.EVENT_FILE_PRE_REQUIRE;
+ require("../suite").constants.EVENT_FILE_PRE_REQUIRE;
/**
* TDD-style interface:
@@ -37,7 +37,7 @@ module.exports = function (suite) {
var suites = [suite];
suite.on(EVENT_FILE_PRE_REQUIRE, function (context, file, mocha) {
- var common = require('./common')(suites, context, mocha);
+ var common = require("./common")(suites, context, mocha);
context.setup = common.beforeEach;
context.teardown = common.afterEach;
@@ -53,7 +53,7 @@ module.exports = function (suite) {
return common.suite.create({
title,
file,
- fn
+ fn,
});
};
@@ -64,7 +64,7 @@ module.exports = function (suite) {
return common.suite.skip({
title,
file,
- fn
+ fn,
});
};
@@ -75,7 +75,7 @@ module.exports = function (suite) {
return common.suite.only({
title,
file,
- fn
+ fn,
});
};
diff --git a/lib/mocha.js b/lib/mocha.js
index 472e8d03..df250ec2 100644
--- a/lib/mocha.js
+++ b/lib/mocha.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/*!
* mocha
@@ -6,24 +6,24 @@
* MIT Licensed
*/
-var escapeRe = require('escape-string-regexp');
-var path = require('node:path');
-var builtinReporters = require('./reporters');
-var utils = require('./utils');
-var mocharc = require('./mocharc.json');
-var Suite = require('./suite');
-var esmUtils = require('./nodejs/esm-utils');
-var createStatsCollector = require('./stats-collector');
+var escapeRe = require("escape-string-regexp");
+var path = require("node:path");
+var builtinReporters = require("./reporters");
+var utils = require("./utils");
+var mocharc = require("./mocharc.json");
+var Suite = require("./suite");
+var esmUtils = require("./nodejs/esm-utils");
+var createStatsCollector = require("./stats-collector");
const {
createInvalidReporterError,
createInvalidInterfaceError,
createMochaInstanceAlreadyDisposedError,
createMochaInstanceAlreadyRunningError,
- createUnsupportedError
-} = require('./errors');
-const {EVENT_FILE_PRE_REQUIRE, EVENT_FILE_POST_REQUIRE, EVENT_FILE_REQUIRE} =
+ createUnsupportedError,
+} = require("./errors");
+const { EVENT_FILE_PRE_REQUIRE, EVENT_FILE_POST_REQUIRE, EVENT_FILE_REQUIRE } =
Suite.constants;
-var debug = require('debug')('mocha:mocha');
+var debug = require("debug")("mocha:mocha");
/**
* @typedef {import('./types.d.ts').DoneCB} DoneCB
@@ -45,32 +45,32 @@ var mochaStates = utils.defineConstants({
* Initial state of the mocha instance
* @private
*/
- INIT: 'init',
+ INIT: "init",
/**
* Mocha instance is running tests
* @private
*/
- RUNNING: 'running',
+ RUNNING: "running",
/**
* Mocha instance is done running tests and references to test functions and hooks are cleaned.
* You can reset this state by unloading the test files.
* @private
*/
- REFERENCES_CLEANED: 'referencesCleaned',
+ REFERENCES_CLEANED: "referencesCleaned",
/**
* Mocha instance is disposed and can no longer be used.
* @private
*/
- DISPOSED: 'disposed'
+ DISPOSED: "disposed",
});
/**
* To require local UIs and reporters when running in node.
*/
-if (!utils.isBrowser() && typeof module.paths !== 'undefined') {
+if (!utils.isBrowser() && typeof module.paths !== "undefined") {
var cwd = utils.cwd();
- module.paths.push(cwd, path.join(cwd, 'node_modules'));
+ module.paths.push(cwd, path.join(cwd, "node_modules"));
}
/**
@@ -79,34 +79,34 @@ if (!utils.isBrowser() && typeof module.paths !== 'undefined') {
*/
exports.utils = utils;
-exports.interfaces = require('./interfaces');
+exports.interfaces = require("./interfaces");
/**
* @public
* @memberof Mocha
*/
exports.reporters = builtinReporters;
-exports.Runnable = require('./runnable');
-exports.Context = require('./context');
+exports.Runnable = require("./runnable");
+exports.Context = require("./context");
/**
*
* @memberof Mocha
*/
-exports.Runner = require('./runner');
+exports.Runner = require("./runner");
exports.Suite = Suite;
-exports.Hook = require('./hook');
-exports.Test = require('./test');
+exports.Hook = require("./hook");
+exports.Test = require("./test");
let currentContext;
exports.afterEach = function (...args) {
return (currentContext.afterEach || currentContext.teardown).apply(
this,
- args
+ args,
);
};
exports.after = function (...args) {
return (currentContext.after || currentContext.suiteTeardown).apply(
this,
- args
+ args,
);
};
exports.beforeEach = function (...args) {
@@ -121,13 +121,13 @@ exports.describe = function (...args) {
exports.describe.only = function (...args) {
return (currentContext.describe || currentContext.suite).only.apply(
this,
- args
+ args,
);
};
exports.describe.skip = function (...args) {
return (currentContext.describe || currentContext.suite).skip.apply(
this,
- args
+ args,
);
};
exports.it = function (...args) {
@@ -159,11 +159,11 @@ exports.run = function (...args) {
* @param {MochaOptions} [options] - Settings object.
*/
function Mocha(options = {}) {
- options = {...mocharc, ...options};
+ options = { ...mocharc, ...options };
this.files = [];
this.options = options;
// root suite
- this.suite = new exports.Suite('', new exports.Context(), true);
+ this.suite = new exports.Suite("", new exports.Context(), true);
this._cleanReferencesAfterRun = true;
this._state = mochaStates.INIT;
@@ -172,38 +172,38 @@ function Mocha(options = {}) {
.ui(options.ui)
.reporter(
options.reporter,
- options['reporter-option'] ||
+ options["reporter-option"] ||
options.reporterOption ||
- options.reporterOptions // for backwards compatibility
+ options.reporterOptions, // for backwards compatibility
)
.slow(options.slow)
.global(options.global);
// this guard exists because Suite#timeout does not consider `undefined` to be valid input
- if (typeof options.timeout !== 'undefined') {
+ if (typeof options.timeout !== "undefined") {
this.timeout(options.timeout === false ? 0 : options.timeout);
}
- if ('retries' in options) {
+ if ("retries" in options) {
this.retries(options.retries);
}
[
- 'allowUncaught',
- 'asyncOnly',
- 'bail',
- 'checkLeaks',
- 'color',
- 'delay',
- 'diff',
- 'dryRun',
- 'passOnFailingTestSuite',
- 'failZero',
- 'forbidOnly',
- 'forbidPending',
- 'fullTrace',
- 'inlineDiffs',
- 'invert'
+ "allowUncaught",
+ "asyncOnly",
+ "bail",
+ "checkLeaks",
+ "color",
+ "delay",
+ "diff",
+ "dryRun",
+ "passOnFailingTestSuite",
+ "failZero",
+ "forbidOnly",
+ "forbidPending",
+ "fullTrace",
+ "inlineDiffs",
+ "invert",
].forEach(function (opt) {
if (options[opt]) {
this[opt]();
@@ -246,9 +246,9 @@ function Mocha(options = {}) {
if (
options.parallel &&
- (typeof options.jobs === 'undefined' || options.jobs > 1)
+ (typeof options.jobs === "undefined" || options.jobs > 1)
) {
- debug('attempting to enable parallel mode');
+ debug("attempting to enable parallel mode");
this.parallelMode(true);
}
}
@@ -302,10 +302,10 @@ Mocha.prototype.addFile = function (file) {
* mocha.reporter('xunit', { output: '/path/to/testspec.xunit.xml' });
*/
Mocha.prototype.reporter = function (reporterName, reporterOptions) {
- if (typeof reporterName === 'function') {
+ if (typeof reporterName === "function") {
this._reporter = reporterName;
} else {
- reporterName = reporterName || 'spec';
+ reporterName = reporterName || "spec";
var reporter;
// Try to load a built-in reporter.
if (builtinReporters[reporterName]) {
@@ -350,10 +350,10 @@ Mocha.prototype.reporter = function (reporterName, reporterOptions) {
*/
Mocha.prototype.ui = function (ui) {
var bindInterface;
- if (typeof ui === 'function') {
+ if (typeof ui === "function") {
bindInterface = ui;
} else {
- ui = ui || 'bdd';
+ ui = ui || "bdd";
bindInterface = exports.interfaces[ui];
if (!bindInterface) {
try {
@@ -421,7 +421,7 @@ Mocha.prototype.loadFiles = function (fn) {
* .then(() => mocha.run(failures => process.exitCode = failures ? 1 : 0))
* .catch(() => process.exitCode = 1);
*/
-Mocha.prototype.loadFilesAsync = function ({esmDecorator} = {}) {
+Mocha.prototype.loadFilesAsync = function ({ esmDecorator } = {}) {
var self = this;
var suite = this.suite;
this.lazyLoadFiles(true);
@@ -435,7 +435,7 @@ Mocha.prototype.loadFilesAsync = function ({esmDecorator} = {}) {
suite.emit(EVENT_FILE_REQUIRE, resultModule, file, self);
suite.emit(EVENT_FILE_POST_REQUIRE, global, file, self);
},
- esmDecorator
+ esmDecorator,
);
};
@@ -450,10 +450,10 @@ Mocha.prototype.loadFilesAsync = function ({esmDecorator} = {}) {
Mocha.unloadFile = function (file) {
if (utils.isBrowser()) {
throw createUnsupportedError(
- 'unloadFile() is only supported in a Node.js environment'
+ "unloadFile() is only supported in a Node.js environment",
);
}
- return require('./nodejs/file-unloader').unloadFile(file);
+ return require("./nodejs/file-unloader").unloadFile(file);
};
/**
@@ -474,9 +474,9 @@ Mocha.unloadFile = function (file) {
Mocha.prototype.unloadFiles = function () {
if (this._state === mochaStates.DISPOSED) {
throw createMochaInstanceAlreadyDisposedError(
- 'Mocha instance is already disposed, it cannot be used again.',
+ "Mocha instance is already disposed, it cannot be used again.",
this._cleanReferencesAfterRun,
- this
+ this,
);
}
@@ -606,7 +606,7 @@ Mocha.prototype.cleanReferencesAfterRun = function (cleanReferencesAfterRun) {
Mocha.prototype.dispose = function () {
if (this._state === mochaStates.RUNNING) {
throw createMochaInstanceAlreadyRunningError(
- 'Cannot dispose while the mocha instance is still running tests.'
+ "Cannot dispose while the mocha instance is still running tests.",
);
}
this.unloadFiles();
@@ -861,7 +861,7 @@ Mocha.prototype.failZero = function (failZero) {
* @return {Mocha} this
* @chainable
*/
-Mocha.prototype.passOnFailingTestSuite = function(passOnFailingTestSuite) {
+Mocha.prototype.passOnFailingTestSuite = function (passOnFailingTestSuite) {
this.options.passOnFailingTestSuite = passOnFailingTestSuite === true;
return this;
};
@@ -901,8 +901,8 @@ Mocha.prototype.forbidPending = function (forbidPending) {
Mocha.prototype._guardRunningStateTransition = function () {
if (this._state === mochaStates.RUNNING) {
throw createMochaInstanceAlreadyRunningError(
- 'Mocha instance is currently running tests, cannot start a next test run until this one is done',
- this
+ "Mocha instance is currently running tests, cannot start a next test run until this one is done",
+ this,
);
}
if (
@@ -910,9 +910,9 @@ Mocha.prototype._guardRunningStateTransition = function () {
this._state === mochaStates.REFERENCES_CLEANED
) {
throw createMochaInstanceAlreadyDisposedError(
- 'Mocha instance is already disposed, cannot start a new test run. Please create a new mocha instance. Be sure to set disable `cleanReferencesAfterRun` when you want to reuse the same mocha instance for multiple test runs.',
+ "Mocha instance is already disposed, cannot start a new test run. Please create a new mocha instance. Be sure to set disable `cleanReferencesAfterRun` when you want to reuse the same mocha instance for multiple test runs.",
this._cleanReferencesAfterRun,
- this
+ this,
);
}
};
@@ -924,11 +924,11 @@ Mocha.prototype._guardRunningStateTransition = function () {
* @type string
* @readonly
*/
-Object.defineProperty(Mocha.prototype, 'version', {
- value: require('../package.json').version,
+Object.defineProperty(Mocha.prototype, "version", {
+ value: require("../package.json").version,
configurable: false,
enumerable: true,
- writable: false
+ writable: false,
});
/**
@@ -966,7 +966,7 @@ Mocha.prototype.run = function (fn) {
cleanReferencesAfterRun: this._cleanReferencesAfterRun,
delay: options.delay,
dryRun: options.dryRun,
- failZero: options.failZero
+ failZero: options.failZero,
});
createStatsCollector(runner);
var reporter = new this._reporter(runner, options);
@@ -988,30 +988,30 @@ Mocha.prototype.run = function (fn) {
exports.reporters.Base.inlineDiffs = options.inlineDiffs;
exports.reporters.Base.hideDiff = !options.diff;
- const done = failures => {
+ const done = (failures) => {
this._previousRunner = runner;
this._state = this._cleanReferencesAfterRun
? mochaStates.REFERENCES_CLEANED
: mochaStates.INIT;
fn = fn || utils.noop;
- if (typeof reporter.done === 'function') {
+ if (typeof reporter.done === "function") {
reporter.done(failures, fn);
} else {
fn(failures);
}
};
- const runAsync = async runner => {
+ const runAsync = async (runner) => {
const context =
this.options.enableGlobalSetup && this.hasGlobalSetupFixtures()
? await this.runGlobalSetup(runner)
: {};
const failureCount = await runner.runAsync({
files: this.files,
- options
+ options,
});
if (this.options.enableGlobalTeardown && this.hasGlobalTeardownFixtures()) {
- await this.runGlobalTeardown(runner, {context});
+ await this.runGlobalTeardown(runner, { context });
}
return failureCount;
};
@@ -1035,22 +1035,22 @@ Mocha.prototype.rootHooks = function rootHooks({
beforeAll = [],
beforeEach = [],
afterAll = [],
- afterEach = []
+ afterEach = [],
} = {}) {
beforeAll = utils.castArray(beforeAll);
beforeEach = utils.castArray(beforeEach);
afterAll = utils.castArray(afterAll);
afterEach = utils.castArray(afterEach);
- beforeAll.forEach(hook => {
+ beforeAll.forEach((hook) => {
this.suite.beforeAll(hook);
});
- beforeEach.forEach(hook => {
+ beforeEach.forEach((hook) => {
this.suite.beforeEach(hook);
});
- afterAll.forEach(hook => {
+ afterAll.forEach((hook) => {
this.suite.afterAll(hook);
});
- afterEach.forEach(hook => {
+ afterEach.forEach((hook) => {
this.suite.afterEach(hook);
});
return this;
@@ -1073,7 +1073,7 @@ Mocha.prototype.rootHooks = function rootHooks({
*/
Mocha.prototype.parallelMode = function parallelMode(enable = true) {
if (utils.isBrowser()) {
- throw createUnsupportedError('parallel mode is only supported in Node.js');
+ throw createUnsupportedError("parallel mode is only supported in Node.js");
}
const parallel = Boolean(enable);
if (
@@ -1085,14 +1085,14 @@ Mocha.prototype.parallelMode = function parallelMode(enable = true) {
}
if (this._state !== mochaStates.INIT) {
throw createUnsupportedError(
- 'cannot change parallel mode after having called run()'
+ "cannot change parallel mode after having called run()",
);
}
this.options.parallel = parallel;
// swap Runner class
this._runnerClass = parallel
- ? require('./nodejs/parallel-buffered-runner')
+ ? require("./nodejs/parallel-buffered-runner")
: exports.Runner;
// lazyLoadFiles may have been set `true` otherwise (for ESM loading),
@@ -1112,7 +1112,7 @@ Mocha.prototype.parallelMode = function parallelMode(enable = true) {
*/
Mocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) {
this._lazyLoadFiles = enable === true;
- debug('set lazy load to %s', enable);
+ debug("set lazy load to %s", enable);
return this;
};
@@ -1128,7 +1128,7 @@ Mocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) {
Mocha.prototype.globalSetup = function globalSetup(setupFns = []) {
setupFns = utils.castArray(setupFns);
this.options.globalSetup = setupFns;
- debug('configured %d global setup functions', setupFns.length);
+ debug("configured %d global setup functions", setupFns.length);
return this;
};
@@ -1144,7 +1144,7 @@ Mocha.prototype.globalSetup = function globalSetup(setupFns = []) {
Mocha.prototype.globalTeardown = function globalTeardown(teardownFns = []) {
teardownFns = utils.castArray(teardownFns);
this.options.globalTeardown = teardownFns;
- debug('configured %d global teardown functions', teardownFns.length);
+ debug("configured %d global teardown functions", teardownFns.length);
return this;
};
@@ -1159,11 +1159,11 @@ Mocha.prototype.globalTeardown = function globalTeardown(teardownFns = []) {
* @returns {Promise<object>} Context object
*/
Mocha.prototype.runGlobalSetup = async function runGlobalSetup(context = {}) {
- const {globalSetup} = this.options;
+ const { globalSetup } = this.options;
if (globalSetup && globalSetup.length) {
- debug('run(): global setup starting');
+ debug("run(): global setup starting");
await this._runGlobalFixtures(globalSetup, context);
- debug('run(): global setup complete');
+ debug("run(): global setup complete");
}
return context;
};
@@ -1179,14 +1179,14 @@ Mocha.prototype.runGlobalSetup = async function runGlobalSetup(context = {}) {
* @returns {Promise<object>} Context object
*/
Mocha.prototype.runGlobalTeardown = async function runGlobalTeardown(
- context = {}
+ context = {},
) {
- const {globalTeardown} = this.options;
+ const { globalTeardown } = this.options;
if (globalTeardown && globalTeardown.length) {
- debug('run(): global teardown starting');
+ debug("run(): global teardown starting");
await this._runGlobalFixtures(globalTeardown, context);
}
- debug('run(): global teardown complete');
+ debug("run(): global teardown complete");
return context;
};
@@ -1199,7 +1199,7 @@ Mocha.prototype.runGlobalTeardown = async function runGlobalTeardown(
*/
Mocha.prototype._runGlobalFixtures = async function _runGlobalFixtures(
fixtureFns = [],
- context = {}
+ context = {},
) {
for await (const fixtureFn of fixtureFns) {
await fixtureFn.call(context);
@@ -1229,7 +1229,7 @@ Mocha.prototype.enableGlobalSetup = function enableGlobalSetup(enabled = true) {
* @returns {Mocha}
*/
Mocha.prototype.enableGlobalTeardown = function enableGlobalTeardown(
- enabled = true
+ enabled = true,
) {
this.options.enableGlobalTeardown = Boolean(enabled);
return this;
diff --git a/lib/nodejs/buffered-worker-pool.js b/lib/nodejs/buffered-worker-pool.js
index ba9e879c..c8b3f3a3 100644
--- a/lib/nodejs/buffered-worker-pool.js
+++ b/lib/nodejs/buffered-worker-pool.js
@@ -5,7 +5,7 @@
* @module buffered-worker-pool
*/
-'use strict';
+"use strict";
/**
* @typedef {import('workerpool').WorkerPoolOptions} WorkerPoolOptions
@@ -13,13 +13,13 @@
* @typedef {import('../types.d.ts').SerializedWorkerResult} SerializedWorkerResult
*/
-const serializeJavascript = require('serialize-javascript');
-const workerpool = require('workerpool');
-const {deserialize} = require('./serializer');
-const debug = require('debug')('mocha:parallel:buffered-worker-pool');
-const {createInvalidArgumentTypeError} = require('../errors');
+const serializeJavascript = require("serialize-javascript");
+const workerpool = require("workerpool");
+const { deserialize } = require("./serializer");
+const debug = require("debug")("mocha:parallel:buffered-worker-pool");
+const { createInvalidArgumentTypeError } = require("../errors");
-const WORKER_PATH = require.resolve('./worker.js');
+const WORKER_PATH = require.resolve("./worker.js");
/**
* A mapping of Mocha `Options` objects to serialized values.
@@ -36,11 +36,11 @@ let optionsCache = new WeakMap();
*/
const WORKER_POOL_DEFAULT_OPTS = {
// use child processes, not worker threads!
- workerType: 'process',
+ workerType: "process",
// ensure the same flags sent to `node` for this `mocha` invocation are passed
// along to children
- forkOpts: {execArgv: process.execArgv},
- maxWorkers: workerpool.cpus - 1
+ forkOpts: { execArgv: process.execArgv },
+ maxWorkers: workerpool.cpus - 1,
};
/**
@@ -55,40 +55,40 @@ class BufferedWorkerPool {
constructor(opts = {}) {
const maxWorkers = Math.max(
1,
- typeof opts.maxWorkers === 'undefined'
+ typeof opts.maxWorkers === "undefined"
? WORKER_POOL_DEFAULT_OPTS.maxWorkers
- : opts.maxWorkers
+ : opts.maxWorkers,
);
/* istanbul ignore next */
if (workerpool.cpus < 2) {
// TODO: decide whether we should warn
debug(
- 'not enough CPU cores available to run multiple jobs; avoid --parallel on this machine'
+ "not enough CPU cores available to run multiple jobs; avoid --parallel on this machine",
);
} else if (maxWorkers >= workerpool.cpus) {
// TODO: decide whether we should warn
debug(
- '%d concurrent job(s) requested, but only %d core(s) available',
+ "%d concurrent job(s) requested, but only %d core(s) available",
maxWorkers,
- workerpool.cpus
+ workerpool.cpus,
);
}
/* istanbul ignore next */
debug(
- 'run(): starting worker pool of max size %d, using node args: %s',
+ "run(): starting worker pool of max size %d, using node args: %s",
maxWorkers,
- process.execArgv.join(' ')
+ process.execArgv.join(" "),
);
let counter = 0;
- const onCreateWorker = ({forkOpts}) => {
+ const onCreateWorker = ({ forkOpts }) => {
return {
forkOpts: {
...forkOpts,
// adds an incremental id to all workers, which can be useful to allocate resources for each process
- env: {...process.env, MOCHA_WORKER_ID: counter++}
- }
+ env: { ...process.env, MOCHA_WORKER_ID: counter++ },
+ },
};
};
@@ -96,7 +96,7 @@ class BufferedWorkerPool {
...WORKER_POOL_DEFAULT_OPTS,
...opts,
maxWorkers,
- onCreateWorker
+ onCreateWorker,
};
this._pool = workerpool.pool(WORKER_PATH, this.options);
}
@@ -109,7 +109,7 @@ class BufferedWorkerPool {
*/
async terminate(force = false) {
/* istanbul ignore next */
- debug('terminate(): terminating with force = %s', force);
+ debug("terminate(): terminating with force = %s", force);
return this._pool.terminate(force);
}
@@ -124,15 +124,15 @@ class BufferedWorkerPool {
* @returns {Promise<SerializedWorkerResult>}
*/
async run(filepath, options = {}) {
- if (!filepath || typeof filepath !== 'string') {
+ if (!filepath || typeof filepath !== "string") {
throw createInvalidArgumentTypeError(
- 'Expected a non-empty filepath',
- 'filepath',
- 'string'
+ "Expected a non-empty filepath",
+ "filepath",
+ "string",
);
}
const serializedOptions = BufferedWorkerPool.serializeOptions(options);
- const result = await this._pool.exec('run', [filepath, serializedOptions]);
+ const result = await this._pool.exec("run", [filepath, serializedOptions]);
return deserialize(result);
}
@@ -167,14 +167,14 @@ class BufferedWorkerPool {
if (!optionsCache.has(opts)) {
const serialized = serializeJavascript(opts, {
unsafe: true, // this means we don't care about XSS
- ignoreFunction: true // do not serialize functions
+ ignoreFunction: true, // do not serialize functions
});
optionsCache.set(opts, serialized);
/* istanbul ignore next */
debug(
- 'serializeOptions(): serialized options %O to: %s',
+ "serializeOptions(): serialized options %O to: %s",
opts,
- serialized
+ serialized,
);
}
return optionsCache.get(opts);
diff --git a/lib/nodejs/esm-utils.js b/lib/nodejs/esm-utils.js
index 77541d7f..363e7182 100644
--- a/lib/nodejs/esm-utils.js
+++ b/lib/nodejs/esm-utils.js
@@ -1,8 +1,8 @@
-const path = require('node:path');
-const url = require('node:url');
-const debug = require('debug')('mocha:esm-utils');
+const path = require("node:path");
+const url = require("node:url");
+const debug = require("debug")("mocha:esm-utils");
-const forward = x => x;
+const forward = (x) => x;
const formattedImport = async (file, esmDecorator = forward) => {
if (path.isAbsolute(file)) {
@@ -23,7 +23,7 @@ const formattedImport = async (file, esmDecorator = forward) => {
const newErrorWithFilename = new SyntaxError(err.message);
newErrorWithFilename.stack = err.stack.replace(
/^SyntaxError/,
- `SyntaxError[ @${file} ]`
+ `SyntaxError[ @${file} ]`,
);
throw newErrorWithFilename;
}
@@ -33,23 +33,23 @@ const formattedImport = async (file, esmDecorator = forward) => {
return exports.doImport(esmDecorator(file));
};
-exports.doImport = async file => import(file);
+exports.doImport = async (file) => import(file);
// When require(esm) is not available, we need to use `import()` to load ESM modules.
// In this case, CJS modules are loaded using `import()` as well. When Node.js' builtin
// TypeScript support is enabled, `.ts` files are also loaded using `import()`, and
// compilers based on `require.extensions` are omitted.
const tryImportAndRequire = async (file, esmDecorator) => {
- if (path.extname(file) === '.mjs') {
+ if (path.extname(file) === ".mjs") {
return formattedImport(file, esmDecorator);
}
try {
return dealWithExports(await formattedImport(file, esmDecorator));
} catch (err) {
if (
- err.code === 'ERR_MODULE_NOT_FOUND' ||
- err.code === 'ERR_UNKNOWN_FILE_EXTENSION' ||
- err.code === 'ERR_UNSUPPORTED_DIR_IMPORT'
+ err.code === "ERR_MODULE_NOT_FOUND" ||
+ err.code === "ERR_UNKNOWN_FILE_EXTENSION" ||
+ err.code === "ERR_UNSUPPORTED_DIR_IMPORT"
) {
try {
// Importing a file usually works, but the resolution of `import` is the ESM
@@ -58,11 +58,11 @@ const tryImportAndRequire = async (file, esmDecorator) => {
return require(file);
} catch (requireErr) {
if (
- requireErr.code === 'ERR_REQUIRE_ESM' ||
+ requireErr.code === "ERR_REQUIRE_ESM" ||
(requireErr instanceof SyntaxError &&
requireErr
.toString()
- .includes('Cannot use import statement outside a module'))
+ .includes("Cannot use import statement outside a module"))
) {
// ERR_REQUIRE_ESM happens when the test file is a JS file, but via type:module is actually ESM,
// AND has an import to a file that doesn't exist.
@@ -91,13 +91,13 @@ const tryImportAndRequire = async (file, esmDecorator) => {
// and `require.cache` effective, while allowing us to load ESM modules
// and CJS modules in the same way.
const requireModule = async (file, esmDecorator) => {
- if (path.extname(file) === '.mjs') {
+ if (path.extname(file) === ".mjs") {
return formattedImport(file, esmDecorator);
}
try {
return require(file);
} catch (requireErr) {
- debug('requireModule caught err: %O', requireErr.message);
+ debug("requireModule caught err: %O", requireErr.message);
try {
return dealWithExports(await formattedImport(file, esmDecorator));
} catch (importErr) {
@@ -107,7 +107,7 @@ const requireModule = async (file, esmDecorator) => {
// See: https://github.com/mochajs/mocha/issues/5393
if (
/\.(cts|mts|ts)$/.test(file) ||
- importErr.code === 'ERR_UNKNOWN_FILE_EXTENSION'
+ importErr.code === "ERR_UNKNOWN_FILE_EXTENSION"
) {
throw requireErr;
}
@@ -115,7 +115,7 @@ const requireModule = async (file, esmDecorator) => {
// Similarly, for an exports/imports mismatch such as a missing 'default',
// the require() error will be more informative for users.
// See: https://github.com/mochajs/mocha/issues/5411
- if (importErr.code === 'ERR_INTERNAL_ASSERTION') {
+ if (importErr.code === "ERR_INTERNAL_ASSERTION") {
throw requireErr;
}
@@ -126,7 +126,10 @@ const requireModule = async (file, esmDecorator) => {
// We only assign this `requireOrImport` function once based on Node version
// We check for file extensions in `requireModule` and `tryImportAndRequire`
-debug('assigning requireOrImport, require_module === %O', process.features.require_module);
+debug(
+ "assigning requireOrImport, require_module === %O",
+ process.features.require_module,
+);
if (process.features.require_module) {
exports.requireOrImport = requireModule;
} else {
@@ -137,7 +140,7 @@ function dealWithExports(module) {
if (module.default) {
return module.default;
} else {
- return {...module, default: undefined};
+ return { ...module, default: undefined };
}
}
@@ -145,13 +148,13 @@ exports.loadFilesAsync = async (
files,
preLoadFunc,
postLoadFunc,
- esmDecorator
+ esmDecorator,
) => {
for (const file of files) {
preLoadFunc(file);
const result = await exports.requireOrImport(
path.resolve(file),
- esmDecorator
+ esmDecorator,
);
postLoadFunc(file, result);
}
diff --git a/lib/nodejs/file-unloader.js b/lib/nodejs/file-unloader.js
index 50a81783..f6a8cfe6 100644
--- a/lib/nodejs/file-unloader.js
+++ b/lib/nodejs/file-unloader.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* This module should not be in the browser bundle, so it's here.
@@ -10,6 +10,6 @@
* Deletes a file from the `require` cache.
* @param {string} file - File
*/
-exports.unloadFile = file => {
+exports.unloadFile = (file) => {
delete require.cache[require.resolve(file)];
};
diff --git a/lib/nodejs/parallel-buffered-runner.js b/lib/nodejs/parallel-buffered-runner.js
index 5af1e3a1..be6f59d7 100644
--- a/lib/nodejs/parallel-buffered-runner.js
+++ b/lib/nodejs/parallel-buffered-runner.js
@@ -4,7 +4,7 @@
* @private
*/
-'use strict';
+"use strict";
/**
* @typedef {import('../types.d.ts').FileRunner} FileRunner
@@ -13,29 +13,29 @@
* @typedef {import('../types.d.ts').SigIntListener} SigIntListener
*/
-const Runner = require('../runner');
-const {EVENT_RUN_BEGIN, EVENT_RUN_END} = Runner.constants;
-const debug = require('debug')('mocha:parallel:parallel-buffered-runner');
-const {BufferedWorkerPool} = require('./buffered-worker-pool');
-const {setInterval, clearInterval} = global;
-const {createMap, constants} = require('../utils');
-const {MOCHA_ID_PROP_NAME} = constants;
-const {createFatalError} = require('../errors');
+const Runner = require("../runner");
+const { EVENT_RUN_BEGIN, EVENT_RUN_END } = Runner.constants;
+const debug = require("debug")("mocha:parallel:parallel-buffered-runner");
+const { BufferedWorkerPool } = require("./buffered-worker-pool");
+const { setInterval, clearInterval } = global;
+const { createMap, constants } = require("../utils");
+const { MOCHA_ID_PROP_NAME } = constants;
+const { createFatalError } = require("../errors");
const DEFAULT_WORKER_REPORTER = require.resolve(
- './reporters/parallel-buffered'
+ "./reporters/parallel-buffered",
);
/**
* List of options to _not_ serialize for transmission to workers
*/
const DENY_OPTIONS = [
- 'globalSetup',
- 'globalTeardown',
- 'parallel',
- 'p',
- 'jobs',
- 'j'
+ "globalSetup",
+ "globalTeardown",
+ "parallel",
+ "p",
+ "jobs",
+ "j",
];
/**
@@ -43,14 +43,14 @@ const DENY_OPTIONS = [
* @param {BufferedWorkerPool} pool - Worker pool
*/
/* istanbul ignore next */
-const debugStats = pool => {
- const {totalWorkers, busyWorkers, idleWorkers, pendingTasks} = pool.stats();
+const debugStats = (pool) => {
+ const { totalWorkers, busyWorkers, idleWorkers, pendingTasks } = pool.stats();
debug(
- '%d/%d busy workers; %d idle; %d tasks queued',
+ "%d/%d busy workers; %d idle; %d tasks queued",
busyWorkers,
totalWorkers,
idleWorkers,
- pendingTasks
+ pendingTasks,
);
};
@@ -59,13 +59,13 @@ const debugStats = pool => {
*/
const DEBUG_STATS_INTERVAL = 5000;
-const ABORTED = 'ABORTED';
-const IDLE = 'IDLE';
-const ABORTING = 'ABORTING';
-const RUNNING = 'RUNNING';
-const BAILING = 'BAILING';
-const BAILED = 'BAILED';
-const COMPLETE = 'COMPLETE';
+const ABORTED = "ABORTED";
+const IDLE = "IDLE";
+const ABORTING = "ABORTING";
+const RUNNING = "RUNNING";
+const BAILING = "BAILING";
+const BAILED = "BAILED";
+const COMPLETE = "COMPLETE";
const states = createMap({
[IDLE]: new Set([RUNNING, ABORTING]),
@@ -74,7 +74,7 @@ const states = createMap({
[ABORTED]: new Set(),
[ABORTING]: new Set([ABORTED]),
[BAILING]: new Set([BAILED, ABORTING]),
- [BAILED]: new Set([COMPLETE, ABORTING])
+ [BAILED]: new Set([COMPLETE, ABORTING]),
});
/**
@@ -87,7 +87,7 @@ class ParallelBufferedRunner extends Runner {
super(...args);
let state = IDLE;
- Object.defineProperty(this, '_state', {
+ Object.defineProperty(this, "_state", {
get() {
return state;
},
@@ -97,7 +97,7 @@ class ParallelBufferedRunner extends Runner {
} else {
throw new Error(`invalid state transition: ${state} => ${newState}`);
}
- }
+ },
});
this._workerReporter = DEFAULT_WORKER_REPORTER;
@@ -130,7 +130,7 @@ class ParallelBufferedRunner extends Runner {
event.data._bail &&
(failureCount || event.error)
) {
- debug('run(): nonzero failure count & found bail flag');
+ debug("run(): nonzero failure count & found bail flag");
// we need to let the events complete for this file, as the worker
// should run any cleanup hooks
this._state = BAILING;
@@ -141,13 +141,13 @@ class ParallelBufferedRunner extends Runner {
* Given an event, recursively find any objects in its data that have ID's, and create object references to already-seen objects.
* @param {Object} event - Event having `eventName`, maybe `data` and maybe `error`
*/
- const linkEvent = event => {
- const stack = [{parent: event, prop: 'data'}];
+ const linkEvent = (event) => {
+ const stack = [{ parent: event, prop: "data" }];
while (stack.length) {
- const {parent, prop} = stack.pop();
+ const { parent, prop } = stack.pop();
const obj = parent[prop];
let newObj;
- if (obj && typeof obj === 'object') {
+ if (obj && typeof obj === "object") {
if (obj[MOCHA_ID_PROP_NAME]) {
const id = obj[MOCHA_ID_PROP_NAME];
newObj = this._linkedObjectMap.has(id)
@@ -157,24 +157,24 @@ class ParallelBufferedRunner extends Runner {
parent[prop] = newObj;
} else {
throw createFatalError(
- 'Object missing ID received in event data',
- obj
+ "Object missing ID received in event data",
+ obj,
);
}
}
- Object.keys(newObj).forEach(key => {
+ Object.keys(newObj).forEach((key) => {
const value = obj[key];
- if (value && typeof value === 'object' && value[MOCHA_ID_PROP_NAME]) {
- stack.push({obj: value, parent: newObj, prop: key});
+ if (value && typeof value === "object" && value[MOCHA_ID_PROP_NAME]) {
+ stack.push({ obj: value, parent: newObj, prop: key });
}
});
}
};
- return async file => {
- debug('run(): enqueueing test file %s', file);
+ return async (file) => {
+ debug("run(): enqueueing test file %s", file);
try {
- const {failureCount, events} = await pool.run(file, options);
+ const { failureCount, events } = await pool.run(file, options);
if (this._state === BAILED) {
// short-circuit after a graceful bail. if this happens,
@@ -184,10 +184,10 @@ class ParallelBufferedRunner extends Runner {
return;
}
debug(
- 'run(): completed run of file %s; %d failures / %d events',
+ "run(): completed run of file %s; %d failures / %d events",
file,
failureCount,
- events.length
+ events.length,
);
this.failures += failureCount; // can this ever be non-numeric?
let event = events.shift();
@@ -212,12 +212,12 @@ class ParallelBufferedRunner extends Runner {
} catch (err) {
if (this._state === BAILED || this._state === ABORTING) {
debug(
- 'run(): worker pool terminated with intent; skipping file %s',
- file
+ "run(): worker pool terminated with intent; skipping file %s",
+ file,
);
} else {
// this is an uncaught exception
- debug('run(): encountered uncaught exception: %O', err);
+ debug("run(): encountered uncaught exception: %O", err);
if (this.allowUncaught) {
// still have to clean up
this._state = ABORTING;
@@ -226,7 +226,7 @@ class ParallelBufferedRunner extends Runner {
throw err;
}
} finally {
- debug('run(): done running file %s', file);
+ debug("run(): done running file %s", file);
}
};
}
@@ -240,27 +240,27 @@ class ParallelBufferedRunner extends Runner {
*/
_bindSigIntListener(pool) {
const sigIntListener = async () => {
- debug('run(): caught a SIGINT');
+ debug("run(): caught a SIGINT");
this._state = ABORTING;
try {
- debug('run(): force-terminating worker pool');
+ debug("run(): force-terminating worker pool");
await pool.terminate(true);
} catch (err) {
console.error(
- `Error while attempting to force-terminate worker pool: ${err}`
+ `Error while attempting to force-terminate worker pool: ${err}`,
);
process.exitCode = 1;
} finally {
process.nextTick(() => {
- debug('run(): imminent death');
+ debug("run(): imminent death");
this._state = ABORTED;
- process.kill(process.pid, 'SIGINT');
+ process.kill(process.pid, "SIGINT");
});
}
};
- process.once('SIGINT', sigIntListener);
+ process.once("SIGINT", sigIntListener);
return sigIntListener;
}
@@ -279,7 +279,7 @@ class ParallelBufferedRunner extends Runner {
* number of test failures.
* @param {RunnerOptions} [opts] - options
*/
- run(callback, {files, options = {}} = {}) {
+ run(callback, { files, options = {} } = {}) {
/**
* Listener on `Process.SIGINT` which tries to cleanly terminate the worker pool.
*/
@@ -287,7 +287,7 @@ class ParallelBufferedRunner extends Runner {
// assign the reporter the worker will use, which will be different than the
// main process' reporter
- options = {...options, reporter: this._workerReporter};
+ options = { ...options, reporter: this._workerReporter };
// This function should _not_ return a `Promise`; its parent (`Runner#run`)
// returns this instance, so this should do the same. However, we want to make
@@ -304,14 +304,14 @@ class ParallelBufferedRunner extends Runner {
let pool;
try {
- pool = BufferedWorkerPool.create({maxWorkers: options.jobs});
+ pool = BufferedWorkerPool.create({ maxWorkers: options.jobs });
sigIntListener = this._bindSigIntListener(pool);
/* istanbul ignore next */
debugInterval = setInterval(
() => debugStats(pool),
- DEBUG_STATS_INTERVAL
+ DEBUG_STATS_INTERVAL,
).unref();
// this is set for uncaught exception handling in `Runner#uncaught`
@@ -321,21 +321,21 @@ class ParallelBufferedRunner extends Runner {
this.emit(EVENT_RUN_BEGIN);
- options = {...options};
- DENY_OPTIONS.forEach(opt => {
+ options = { ...options };
+ DENY_OPTIONS.forEach((opt) => {
delete options[opt];
});
const results = await Promise.allSettled(
- files.map(this._createFileRunner(pool, options))
+ files.map(this._createFileRunner(pool, options)),
);
// note that pool may already be terminated due to --bail
await pool.terminate();
results
- .filter(({status}) => status === 'rejected')
- .forEach(({reason}) => {
+ .filter(({ status }) => status === "rejected")
+ .forEach(({ reason }) => {
if (this.allowUncaught) {
// yep, just the first one.
throw reason;
@@ -350,19 +350,19 @@ class ParallelBufferedRunner extends Runner {
}
this.emit(EVENT_RUN_END);
- debug('run(): completing with failure count %d', this.failures);
+ debug("run(): completing with failure count %d", this.failures);
callback(this.failures);
} catch (err) {
// this `nextTick` takes us out of the `Promise` scope, so the
// exception will not be caught and returned as a rejected `Promise`,
// which would lead to an `unhandledRejection` event.
process.nextTick(() => {
- debug('run(): re-throwing uncaught exception');
+ debug("run(): re-throwing uncaught exception");
throw err;
});
} finally {
clearInterval(debugInterval);
- process.removeListener('SIGINT', sigIntListener);
+ process.removeListener("SIGINT", sigIntListener);
}
})();
return this;
diff --git a/lib/nodejs/reporters/parallel-buffered.js b/lib/nodejs/reporters/parallel-buffered.js
index 272ce29d..085e09bd 100644
--- a/lib/nodejs/reporters/parallel-buffered.js
+++ b/lib/nodejs/reporters/parallel-buffered.js
@@ -4,7 +4,7 @@
* @public
*/
-'use strict';
+"use strict";
/**
* @typedef {import('../../types.d.ts').BufferedEvent} BufferedEvent
@@ -28,11 +28,14 @@ const {
EVENT_DELAY_END,
EVENT_HOOK_BEGIN,
EVENT_HOOK_END,
- EVENT_RUN_END
-} = require('../../runner').constants;
-const {SerializableEvent, SerializableWorkerResult} = require('../serializer');
-const debug = require('debug')('mocha:reporters:buffered');
-const Base = require('../../reporters/base');
+ EVENT_RUN_END,
+} = require("../../runner").constants;
+const {
+ SerializableEvent,
+ SerializableWorkerResult,
+} = require("../serializer");
+const debug = require("debug")("mocha:reporters:buffered");
+const Base = require("../../reporters/base");
/**
* List of events to listen to; these will be buffered and sent
@@ -48,7 +51,7 @@ const EVENT_NAMES = [
EVENT_TEST_RETRY,
EVENT_TEST_END,
EVENT_HOOK_BEGIN,
- EVENT_HOOK_END
+ EVENT_HOOK_END,
];
/**
@@ -122,15 +125,15 @@ class ParallelBuffered extends Base {
* @chainable
*/
createListeners(runner) {
- EVENT_NAMES.forEach(evt => {
+ EVENT_NAMES.forEach((evt) => {
runner.on(evt, this.createListener(evt));
});
- ONCE_EVENT_NAMES.forEach(evt => {
+ ONCE_EVENT_NAMES.forEach((evt) => {
runner.once(evt, this.createListener(evt));
});
runner.once(EVENT_RUN_END, () => {
- debug('received EVENT_RUN_END');
+ debug("received EVENT_RUN_END");
this.listeners.forEach((listener, evt) => {
runner.removeListener(evt, listener);
this.listeners.delete(evt);
diff --git a/lib/nodejs/serializer.js b/lib/nodejs/serializer.js
index b9f5a12d..8e6253ff 100644
--- a/lib/nodejs/serializer.js
+++ b/lib/nodejs/serializer.js
@@ -4,21 +4,21 @@
* @private
*/
-'use strict';
+"use strict";
/**
* @typedef {import('../types.d.ts').SerializedEvent} SerializedEvent
* @typedef {import('../types.d.ts').SerializedWorkerResult} SerializedWorkerResult
*/
-const {type, breakCircularDeps} = require('../utils');
-const {createInvalidArgumentTypeError} = require('../errors');
+const { type, breakCircularDeps } = require("../utils");
+const { createInvalidArgumentTypeError } = require("../errors");
// this is not named `mocha:parallel:serializer` because it's noisy and it's
// helpful to be able to write `DEBUG=mocha:parallel*` and get everything else.
-const debug = require('debug')('mocha:serializer');
+const debug = require("debug")("mocha:serializer");
-const SERIALIZABLE_RESULT_NAME = 'SerializableWorkerResult';
-const SERIALIZABLE_TYPES = new Set(['object', 'array', 'function', 'error']);
+const SERIALIZABLE_RESULT_NAME = "SerializableWorkerResult";
+const SERIALIZABLE_TYPES = new Set(["object", "array", "function", "error"]);
/**
* The serializable result of a test file run from a worker.
@@ -51,10 +51,10 @@ class SerializableWorkerResult {
* this object (once it's been received over IPC).
* @type {Readonly<"SerializableWorkerResult">}
*/
- Object.defineProperty(this, '__type', {
+ Object.defineProperty(this, "__type", {
value: SERIALIZABLE_RESULT_NAME,
enumerable: true,
- writable: false
+ writable: false,
});
}
@@ -73,7 +73,7 @@ class SerializableWorkerResult {
* @returns {Readonly<SerializableWorkerResult>}
*/
serialize() {
- this.events.forEach(event => {
+ this.events.forEach((event) => {
event.serialize();
});
return Object.freeze(this);
@@ -87,7 +87,7 @@ class SerializableWorkerResult {
* @returns {SerializedWorkerResult}
*/
static deserialize(obj) {
- obj.events.forEach(event => {
+ obj.events.forEach((event) => {
SerializableEvent.deserialize(event);
});
return obj;
@@ -102,7 +102,7 @@ class SerializableWorkerResult {
static isSerializedWorkerResult(value) {
return (
value instanceof SerializableWorkerResult ||
- (type(value) === 'object' && value.__type === SERIALIZABLE_RESULT_NAME)
+ (type(value) === "object" && value.__type === SERIALIZABLE_RESULT_NAME)
);
}
}
@@ -137,9 +137,9 @@ class SerializableEvent {
constructor(eventName, originalValue, originalError) {
if (!eventName) {
throw createInvalidArgumentTypeError(
- 'Empty `eventName` string argument',
- 'eventName',
- 'string'
+ "Empty `eventName` string argument",
+ "eventName",
+ "string",
);
}
/**
@@ -148,20 +148,20 @@ class SerializableEvent {
*/
this.eventName = eventName;
const originalValueType = type(originalValue);
- if (originalValueType !== 'object' && originalValueType !== 'undefined') {
+ if (originalValueType !== "object" && originalValueType !== "undefined") {
throw createInvalidArgumentTypeError(
`Expected object but received ${originalValueType}`,
- 'originalValue',
- 'object'
+ "originalValue",
+ "object",
);
}
/**
* An error, if present.
* @memberof SerializableEvent
*/
- Object.defineProperty(this, 'originalError', {
+ Object.defineProperty(this, "originalError", {
value: originalError,
- enumerable: false
+ enumerable: false,
});
/**
@@ -171,9 +171,9 @@ class SerializableEvent {
*
* @memberof SerializableEvent
*/
- Object.defineProperty(this, 'originalValue', {
+ Object.defineProperty(this, "originalValue", {
value: originalValue,
- enumerable: false
+ enumerable: false,
});
}
@@ -197,44 +197,44 @@ class SerializableEvent {
static _serialize(pairs, parent, key) {
let value = parent[key];
let _type = type(value);
- if (_type === 'error') {
+ if (_type === "error") {
// we need to reference the stack prop b/c it's lazily-loaded.
// `__type` is necessary for deserialization to create an `Error` later.
// `message` is apparently not enumerable, so we must handle it specifically.
value = Object.assign(Object.create(null), value, {
stack: value.stack,
message: value.message,
- __type: 'Error'
+ __type: "Error",
});
parent[key] = value;
// after this, set the result of type(value) to be `object`, and we'll throw
// whatever other junk is in the original error into the new `value`.
- _type = 'object';
+ _type = "object";
}
switch (_type) {
- case 'object':
- if (type(value.serialize) === 'function') {
+ case "object":
+ if (type(value.serialize) === "function") {
parent[key] = value.serialize();
} else {
// by adding props to the `pairs` array, we will process it further
pairs.push(
...Object.keys(value)
- .filter(key => SERIALIZABLE_TYPES.has(type(value[key])))
- .map(key => [value, key])
+ .filter((key) => SERIALIZABLE_TYPES.has(type(value[key])))
+ .map((key) => [value, key]),
);
}
break;
- case 'function':
+ case "function":
// we _may_ want to dig in to functions for some assertion libraries
// that might put a usable property on a function.
// for now, just zap it.
delete parent[key];
break;
- case 'array':
+ case "array":
pairs.push(
...value
- .filter(value => SERIALIZABLE_TYPES.has(type(value)))
- .map((value, index) => [value, index])
+ .filter((value) => SERIALIZABLE_TYPES.has(type(value)))
+ .map((value, index) => [value, index]),
);
break;
}
@@ -256,17 +256,17 @@ class SerializableEvent {
const originalValue = this.originalValue;
const result = Object.assign(Object.create(null), {
data:
- type(originalValue) === 'object' &&
- type(originalValue.serialize) === 'function'
+ type(originalValue) === "object" &&
+ type(originalValue.serialize) === "function"
? originalValue.serialize()
: originalValue,
- error: this.originalError
+ error: this.originalError,
});
// mutates the object
breakCircularDeps(result.error);
- const pairs = Object.keys(result).map(key => [result, key]);
+ const pairs = Object.keys(result).map((key) => [result, key]);
const seenPairs = new Set();
let pair;
@@ -307,7 +307,7 @@ class SerializableEvent {
* @param {string|number} key - Some prop name or array index within `parent`
*/
static _deserializeObject(parent, key) {
- if (key === '__proto__') {
+ if (key === "__proto__") {
delete parent[key];
return;
}
@@ -315,21 +315,21 @@ class SerializableEvent {
// keys beginning with `$$` are converted into functions returning the value
// and renamed, stripping the `$$` prefix.
// functions defined this way cannot be array members!
- if (type(key) === 'string' && key.startsWith('$$')) {
+ if (type(key) === "string" && key.startsWith("$$")) {
const newKey = key.slice(2);
parent[newKey] = () => value;
delete parent[key];
key = newKey;
}
- if (type(value) === 'array') {
+ if (type(value) === "array") {
value.forEach((_, idx) => {
SerializableEvent._deserializeObject(value, idx);
});
- } else if (type(value) === 'object') {
- if (value.__type === 'Error') {
+ } else if (type(value) === "object") {
+ if (value.__type === "Error") {
parent[key] = SerializableEvent._deserializeError(value);
} else {
- Object.keys(value).forEach(key => {
+ Object.keys(value).forEach((key) => {
SerializableEvent._deserializeObject(value, key);
});
}
@@ -345,13 +345,13 @@ class SerializableEvent {
*/
static deserialize(obj) {
if (!obj) {
- throw createInvalidArgumentTypeError('Expected value', obj);
+ throw createInvalidArgumentTypeError("Expected value", obj);
}
obj = Object.assign(Object.create(null), obj);
if (obj.data) {
- Object.keys(obj.data).forEach(key => {
+ Object.keys(obj.data).forEach((key) => {
SerializableEvent._deserializeObject(obj.data, key);
});
}
@@ -373,10 +373,10 @@ class SerializableEvent {
*/
exports.serialize = function serialize(value) {
const result =
- type(value) === 'object' && type(value.serialize) === 'function'
+ type(value) === "object" && type(value.serialize) === "function"
? value.serialize()
: value;
- debug('serialized: %O', result);
+ debug("serialized: %O", result);
return result;
};
@@ -392,7 +392,7 @@ exports.deserialize = function deserialize(value) {
const result = SerializableWorkerResult.isSerializedWorkerResult(value)
? SerializableWorkerResult.deserialize(value)
: value;
- debug('deserialized: %O', result);
+ debug("deserialized: %O", result);
return result;
};
diff --git a/lib/nodejs/worker.js b/lib/nodejs/worker.js
index 732f5feb..4b87d98f 100644
--- a/lib/nodejs/worker.js
+++ b/lib/nodejs/worker.js
@@ -4,7 +4,7 @@
* @private
*/
-'use strict';
+"use strict";
/**
* @typedef {import('../types.d.ts').BufferedEvent} BufferedEvent
@@ -13,22 +13,22 @@
const {
createInvalidArgumentTypeError,
- createInvalidArgumentValueError
-} = require('../errors');
-const workerpool = require('workerpool');
-const Mocha = require('../mocha');
-const {handleRequires, validateLegacyPlugin} = require('../cli/run-helpers');
-const d = require('debug');
+ createInvalidArgumentValueError,
+} = require("../errors");
+const workerpool = require("workerpool");
+const Mocha = require("../mocha");
+const { handleRequires, validateLegacyPlugin } = require("../cli/run-helpers");
+const d = require("debug");
const debug = d.debug(`mocha:parallel:worker:${process.pid}`);
const isDebugEnabled = d.enabled(`mocha:parallel:worker:${process.pid}`);
-const {serialize} = require('./serializer');
-const {setInterval, clearInterval} = global;
+const { serialize } = require("./serializer");
+const { setInterval, clearInterval } = global;
let rootHooks;
if (workerpool.isMainThread) {
throw new Error(
- 'This script is intended to be run as a worker (by the `workerpool` package).'
+ "This script is intended to be run as a worker (by the `workerpool` package).",
);
}
@@ -43,16 +43,16 @@ if (workerpool.isMainThread) {
*
* @param {MochaOptions} argv - Command-line options
*/
-let bootstrap = async argv => {
+let bootstrap = async (argv) => {
// globalSetup and globalTeardown do not run in workers
const plugins = await handleRequires(argv.require, {
- ignoredPlugins: ['mochaGlobalSetup', 'mochaGlobalTeardown']
+ ignoredPlugins: ["mochaGlobalSetup", "mochaGlobalTeardown"],
});
- validateLegacyPlugin(argv, 'ui', Mocha.interfaces);
+ validateLegacyPlugin(argv, "ui", Mocha.interfaces);
rootHooks = plugins.rootHooks;
bootstrap = () => {};
- debug('bootstrap(): finished with args: %O', argv);
+ debug("bootstrap(): finished with args: %O", argv);
};
/**
@@ -63,43 +63,43 @@ let bootstrap = async argv => {
* @returns {Promise<{failures: number, events: BufferedEvent[]}>} - Test
* failure count and list of events.
*/
-async function run(filepath, serializedOptions = '{}') {
+async function run(filepath, serializedOptions = "{}") {
if (!filepath) {
throw createInvalidArgumentTypeError(
'Expected a non-empty "filepath" argument',
- 'file',
- 'string'
+ "file",
+ "string",
);
}
- debug('run(): running test file %s', filepath);
+ debug("run(): running test file %s", filepath);
- if (typeof serializedOptions !== 'string') {
+ if (typeof serializedOptions !== "string") {
throw createInvalidArgumentTypeError(
- 'run() expects second parameter to be a string which was serialized by the `serialize-javascript` module',
- 'serializedOptions',
- 'string'
+ "run() expects second parameter to be a string which was serialized by the `serialize-javascript` module",
+ "serializedOptions",
+ "string",
);
}
let argv;
try {
// eslint-disable-next-line no-eval
- argv = eval('(' + serializedOptions + ')');
+ argv = eval("(" + serializedOptions + ")");
} catch (err) {
throw createInvalidArgumentValueError(
- 'run() was unable to deserialize the options',
- 'serializedOptions',
- serializedOptions
+ "run() was unable to deserialize the options",
+ "serializedOptions",
+ serializedOptions,
);
}
- const opts = Object.assign({ui: 'bdd'}, argv, {
+ const opts = Object.assign({ ui: "bdd" }, argv, {
// if this was true, it would cause infinite recursion.
parallel: false,
// this doesn't work in parallel mode
forbidOnly: true,
// it's useful for a Mocha instance to know if it's running in a worker process.
- isWorker: true
+ isWorker: true,
});
await bootstrap(opts);
@@ -111,7 +111,7 @@ async function run(filepath, serializedOptions = '{}') {
try {
await mocha.loadFilesAsync();
} catch (err) {
- debug('run(): could not load file %s: %s', filepath, err);
+ debug("run(): could not load file %s: %s", filepath, err);
throw err;
}
@@ -120,25 +120,25 @@ async function run(filepath, serializedOptions = '{}') {
/* istanbul ignore next */
if (isDebugEnabled) {
debugInterval = setInterval(() => {
- debug('run(): still running %s...', filepath);
+ debug("run(): still running %s...", filepath);
}, 5000).unref();
}
- mocha.run(result => {
+ mocha.run((result) => {
// Runner adds these; if we don't remove them, we'll get a leak.
- process.removeAllListeners('uncaughtException');
- process.removeAllListeners('unhandledRejection');
+ process.removeAllListeners("uncaughtException");
+ process.removeAllListeners("unhandledRejection");
try {
const serialized = serialize(result);
debug(
- 'run(): completed run with %d test failures; returning to main process',
- typeof result.failures === 'number' ? result.failures : 0
+ "run(): completed run with %d test failures; returning to main process",
+ typeof result.failures === "number" ? result.failures : 0,
);
resolve(serialized);
} catch (err) {
// TODO: figure out exactly what the sad path looks like here.
// rejection should only happen if an error is "unrecoverable"
- debug('run(): serialization failed; rejecting: %O', err);
+ debug("run(): serialization failed; rejecting: %O", err);
reject(err);
} finally {
clearInterval(debugInterval);
@@ -148,9 +148,9 @@ async function run(filepath, serializedOptions = '{}') {
}
// this registers the `run` function.
-workerpool.worker({run});
+workerpool.worker({ run });
-debug('started worker process');
+debug("started worker process");
// for testing
exports.run = run;
diff --git a/lib/pending.js b/lib/pending.js
index cf9cc84a..dedea5eb 100644
--- a/lib/pending.js
+++ b/lib/pending.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
@module Pending
diff --git a/lib/plugin-loader.js b/lib/plugin-loader.js
index 80934476..4469621a 100644
--- a/lib/plugin-loader.js
+++ b/lib/plugin-loader.js
@@ -13,14 +13,14 @@
* @module plugin
*/
-'use strict';
+"use strict";
-const debug = require('debug')('mocha:plugin-loader');
+const debug = require("debug")("mocha:plugin-loader");
const {
createInvalidPluginDefinitionError,
- createInvalidPluginImplementationError
-} = require('./errors');
-const {castArray} = require('./utils');
+ createInvalidPluginImplementationError,
+} = require("./errors");
+const { castArray } = require("./utils");
/**
* @typedef {import('./types.d.ts').PluginLoaderOptions} PluginLoaderOptions
@@ -35,24 +35,24 @@ const MochaPlugins = [
* @type {PluginDefinition}
*/
{
- exportName: 'mochaHooks',
- optionName: 'rootHooks',
+ exportName: "mochaHooks",
+ optionName: "rootHooks",
validate(value) {
if (
Array.isArray(value) ||
- (typeof value !== 'function' && typeof value !== 'object')
+ (typeof value !== "function" && typeof value !== "object")
) {
throw createInvalidPluginImplementationError(
- `mochaHooks must be an object or a function returning (or fulfilling with) an object`
+ `mochaHooks must be an object or a function returning (or fulfilling with) an object`,
);
}
},
async finalize(rootHooks) {
if (rootHooks.length) {
const rootHookObjects = await Promise.all(
- rootHooks.map(async hook =>
- typeof hook === 'function' ? hook() : hook
- )
+ rootHooks.map(async (hook) =>
+ typeof hook === "function" ? hook() : hook,
+ ),
);
return rootHookObjects.reduce(
@@ -62,68 +62,68 @@ const MochaPlugins = [
beforeEach: [],
afterAll: [],
afterEach: [],
- ...hook
+ ...hook,
};
return {
beforeAll: [...acc.beforeAll, ...castArray(hook.beforeAll)],
beforeEach: [...acc.beforeEach, ...castArray(hook.beforeEach)],
afterAll: [...acc.afterAll, ...castArray(hook.afterAll)],
- afterEach: [...acc.afterEach, ...castArray(hook.afterEach)]
+ afterEach: [...acc.afterEach, ...castArray(hook.afterEach)],
};
},
- {beforeAll: [], beforeEach: [], afterAll: [], afterEach: []}
+ { beforeAll: [], beforeEach: [], afterAll: [], afterEach: [] },
);
}
- }
+ },
},
/**
* Global setup fixture plugin definition
* @type {PluginDefinition}
*/
{
- exportName: 'mochaGlobalSetup',
- optionName: 'globalSetup',
+ exportName: "mochaGlobalSetup",
+ optionName: "globalSetup",
validate(value) {
let isValid = true;
if (Array.isArray(value)) {
- if (value.some(item => typeof item !== 'function')) {
+ if (value.some((item) => typeof item !== "function")) {
isValid = false;
}
- } else if (typeof value !== 'function') {
+ } else if (typeof value !== "function") {
isValid = false;
}
if (!isValid) {
throw createInvalidPluginImplementationError(
`mochaGlobalSetup must be a function or an array of functions`,
- {pluginDef: this, pluginImpl: value}
+ { pluginDef: this, pluginImpl: value },
);
}
- }
+ },
},
/**
* Global teardown fixture plugin definition
* @type {PluginDefinition}
*/
{
- exportName: 'mochaGlobalTeardown',
- optionName: 'globalTeardown',
+ exportName: "mochaGlobalTeardown",
+ optionName: "globalTeardown",
validate(value) {
let isValid = true;
if (Array.isArray(value)) {
- if (value.some(item => typeof item !== 'function')) {
+ if (value.some((item) => typeof item !== "function")) {
isValid = false;
}
- } else if (typeof value !== 'function') {
+ } else if (typeof value !== "function") {
isValid = false;
}
if (!isValid) {
throw createInvalidPluginImplementationError(
`mochaGlobalTeardown must be a function or an array of functions`,
- {pluginDef: this, pluginImpl: value}
+ { pluginDef: this, pluginImpl: value },
);
}
- }
- }
+ },
+ },
];
/**
@@ -138,7 +138,7 @@ class PluginLoader {
* Initializes plugin names, plugin map, etc.
* @param {PluginLoaderOptions} [opts] - Options
*/
- constructor({pluginDefs = MochaPlugins, ignore = []} = {}) {
+ constructor({ pluginDefs = MochaPlugins, ignore = [] } = {}) {
/**
* Map of registered plugin defs
* @type {Map<string,PluginDefinition>}
@@ -169,14 +169,14 @@ class PluginLoader {
*/
this.ignoredExportNames = new Set(castArray(ignore));
- castArray(pluginDefs).forEach(pluginDef => {
+ castArray(pluginDefs).forEach((pluginDef) => {
this.register(pluginDef);
});
debug(
- 'registered %d plugin defs (%d ignored)',
+ "registered %d plugin defs (%d ignored)",
this.registered.size,
- this.ignoredExportNames.size
+ this.ignoredExportNames.size,
);
}
@@ -185,23 +185,23 @@ class PluginLoader {
* @param {PluginDefinition} pluginDef - Plugin definition
*/
register(pluginDef) {
- if (!pluginDef || typeof pluginDef !== 'object') {
+ if (!pluginDef || typeof pluginDef !== "object") {
throw createInvalidPluginDefinitionError(
- 'pluginDef is non-object or falsy',
- pluginDef
+ "pluginDef is non-object or falsy",
+ pluginDef,
);
}
if (!pluginDef.exportName) {
throw createInvalidPluginDefinitionError(
`exportName is expected to be a non-empty string`,
- pluginDef
+ pluginDef,
);
}
- let {exportName} = pluginDef;
+ let { exportName } = pluginDef;
if (this.ignoredExportNames.has(exportName)) {
debug(
'refusing to register ignored plugin with export name "%s"',
- exportName
+ exportName,
);
return;
}
@@ -210,7 +210,7 @@ class PluginLoader {
if (this.knownExportNames.has(exportName)) {
throw createInvalidPluginDefinitionError(
`Plugin definition conflict: ${exportName}; exportName must be unique`,
- pluginDef
+ pluginDef,
);
}
this.loaded.set(exportName, []);
@@ -229,24 +229,24 @@ class PluginLoader {
load(requiredModule) {
// we should explicitly NOT fail if other stuff is exported.
// we only care about the plugins we know about.
- if (requiredModule && typeof requiredModule === 'object') {
+ if (requiredModule && typeof requiredModule === "object") {
return Array.from(this.knownExportNames).reduce(
(pluginImplFound, pluginName) => {
const pluginImpl = requiredModule[pluginName];
if (pluginImpl) {
const plugin = this.registered.get(pluginName);
- if (typeof plugin.validate === 'function') {
+ if (typeof plugin.validate === "function") {
plugin.validate(pluginImpl);
}
this.loaded.set(pluginName, [
...this.loaded.get(pluginName),
- ...castArray(pluginImpl)
+ ...castArray(pluginImpl),
]);
return true;
}
return pluginImplFound;
},
- false
+ false,
);
}
return false;
@@ -265,13 +265,13 @@ class PluginLoader {
if (pluginImpls.length) {
const plugin = this.registered.get(exportName);
finalizedPlugins[plugin.optionName] =
- typeof plugin.finalize === 'function'
+ typeof plugin.finalize === "function"
? await plugin.finalize(pluginImpls)
: pluginImpls;
}
}
- debug('finalized plugins: %O', finalizedPlugins);
+ debug("finalized plugins: %O", finalizedPlugins);
return finalizedPlugins;
}
@@ -279,8 +279,8 @@ class PluginLoader {
* Constructs a {@link PluginLoader}
* @param {PluginLoaderOptions} [opts] - Plugin loader options
*/
- static create({pluginDefs = MochaPlugins, ignore = []} = {}) {
- return new PluginLoader({pluginDefs, ignore});
+ static create({ pluginDefs = MochaPlugins, ignore = [] } = {}) {
+ return new PluginLoader({ pluginDefs, ignore });
}
}
diff --git a/lib/reporters/base.js b/lib/reporters/base.js
index bc210ca2..3c200388 100644
--- a/lib/reporters/base.js
+++ b/lib/reporters/base.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -13,19 +13,19 @@
* Module dependencies.
*/
-var diff = require('diff');
-var milliseconds = require('ms');
-var utils = require('../utils');
-var supportsColor = require('supports-color');
-var symbols = require('log-symbols');
-var constants = require('../runner').constants;
+var diff = require("diff");
+var milliseconds = require("ms");
+var utils = require("../utils");
+var supportsColor = require("supports-color");
+var symbols = require("log-symbols");
+var constants = require("../runner").constants;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
const isBrowser = utils.isBrowser();
function getBrowserWindowSize() {
- if ('innerHeight' in global) {
+ if ("innerHeight" in global) {
return [global.innerHeight, global.innerWidth];
}
// In a Web Worker, the DOM Window is not available.
@@ -75,25 +75,25 @@ exports.maxDiffSize = 8192;
exports.colors = {
pass: 90,
fail: 31,
- 'bright pass': 92,
- 'bright fail': 91,
- 'bright yellow': 93,
+ "bright pass": 92,
+ "bright fail": 91,
+ "bright yellow": 93,
pending: 36,
suite: 0,
- 'error title': 0,
- 'error message': 31,
- 'error stack': 90,
+ "error title": 0,
+ "error message": 31,
+ "error stack": 90,
checkmark: 32,
fast: 90,
medium: 33,
slow: 31,
green: 32,
light: 90,
- 'diff gutter': 90,
- 'diff added': 32,
- 'diff removed': 31,
- 'diff added inline': '30;42',
- 'diff removed inline': '30;41'
+ "diff gutter": 90,
+ "diff added": 32,
+ "diff removed": 31,
+ "diff added inline": "30;42",
+ "diff removed inline": "30;41",
};
/**
@@ -103,9 +103,9 @@ exports.colors = {
exports.symbols = {
ok: symbols.success,
err: symbols.error,
- dot: '.',
- comma: ',',
- bang: '!'
+ dot: ".",
+ comma: ",",
+ bang: "!",
};
/**
@@ -123,7 +123,7 @@ var color = (exports.color = function (type, str) {
if (!exports.useColors) {
return String(str);
}
- return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m';
+ return "\u001b[" + exports.colors[type] + "m" + str + "\u001b[0m";
});
/**
@@ -131,7 +131,7 @@ var color = (exports.color = function (type, str) {
*/
exports.window = {
- width: 75
+ width: 75,
};
if (isatty) {
@@ -148,19 +148,19 @@ if (isatty) {
exports.cursor = {
hide: function () {
- isatty && process.stdout.write('\u001b[?25l');
+ isatty && process.stdout.write("\u001b[?25l");
},
show: function () {
- isatty && process.stdout.write('\u001b[?25h');
+ isatty && process.stdout.write("\u001b[?25h");
},
deleteLine: function () {
- isatty && process.stdout.write('\u001b[2K');
+ isatty && process.stdout.write("\u001b[2K");
},
beginningOfLine: function () {
- isatty && process.stdout.write('\u001b[0G');
+ isatty && process.stdout.write("\u001b[0G");
},
CR: function () {
@@ -168,9 +168,9 @@ exports.cursor = {
exports.cursor.deleteLine();
exports.cursor.beginningOfLine();
} else {
- process.stdout.write('\r');
+ process.stdout.write("\r");
}
- }
+ },
};
var showDiff = (exports.showDiff = function (err) {
@@ -219,11 +219,11 @@ var generateDiff = (exports.generateDiff = function (actual, expected) {
return result;
} catch (err) {
var msg =
- '\n ' +
- color('diff added', '+ expected') +
- ' ' +
- color('diff removed', '- actual: failed to generate Mocha diff') +
- '\n';
+ "\n " +
+ color("diff added", "+ expected") +
+ " " +
+ color("diff removed", "- actual: failed to generate Mocha diff") +
+ "\n";
return msg;
}
});
@@ -238,17 +238,17 @@ var generateDiff = (exports.generateDiff = function (actual, expected) {
*/
var getFullErrorStack = function (err, seen) {
if (seen && seen.has(err)) {
- return { message: '', msg: '<circular>', stack: '' };
+ return { message: "", msg: "<circular>", stack: "" };
}
var message;
- if (typeof err.inspect === 'function') {
- message = err.inspect() + '';
- } else if (err.message && typeof err.message.toString === 'function') {
- message = err.message + '';
+ if (typeof err.inspect === "function") {
+ message = err.inspect() + "";
+ } else if (err.message && typeof err.message.toString === "function") {
+ message = err.message + "";
} else {
- message = '';
+ message = "";
}
var msg;
@@ -266,15 +266,18 @@ var getFullErrorStack = function (err, seen) {
if (err.cause) {
seen = seen || new Set();
seen.add(err);
- const causeStack = getFullErrorStack(err.cause, seen)
- stack += '\n Caused by: ' + causeStack.msg + (causeStack.stack ? '\n' + causeStack.stack : '');
+ const causeStack = getFullErrorStack(err.cause, seen);
+ stack +=
+ "\n Caused by: " +
+ causeStack.msg +
+ (causeStack.stack ? "\n" + causeStack.stack : "");
}
}
return {
message,
msg,
- stack
+ stack,
};
};
@@ -293,9 +296,9 @@ exports.list = function (failures) {
failures.forEach(function (test, i) {
// format
var fmt =
- color('error title', ' %s) %s:\n') +
- color('error message', ' %s') +
- color('error stack', '\n%s\n');
+ color("error title", " %s) %s:\n") +
+ color("error message", " %s") +
+ color("error stack", "\n%s\n");
// msg
var err;
@@ -313,30 +316,30 @@ exports.list = function (failures) {
// uncaught
if (err.uncaught) {
- msg = 'Uncaught ' + msg;
+ msg = "Uncaught " + msg;
}
// explicitly show diff
if (!exports.hideDiff && showDiff(err)) {
stringifyDiffObjs(err);
fmt =
- color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n');
+ color("error title", " %s) %s:\n%s") + color("error stack", "\n%s\n");
var match = message.match(/^([^:]+): expected/);
- msg = '\n ' + color('error message', match ? match[1] : msg);
+ msg = "\n " + color("error message", match ? match[1] : msg);
msg += generateDiff(err.actual, err.expected);
}
// indent stack trace
- stack = stack.replace(/^/gm, ' ');
+ stack = stack.replace(/^/gm, " ");
// indented test title
- var testTitle = '';
+ var testTitle = "";
test.titlePath().forEach(function (str, index) {
if (index !== 0) {
- testTitle += '\n ';
+ testTitle += "\n ";
}
for (var i = 0; i < index; i++) {
- testTitle += ' ';
+ testTitle += " ";
}
testTitle += str;
});
@@ -361,7 +364,7 @@ function Base(runner, options) {
var failures = (this.failures = []);
if (!runner) {
- throw new TypeError('Missing runner argument');
+ throw new TypeError("Missing runner argument");
}
this.options = options || {};
this.runner = runner;
@@ -375,11 +378,11 @@ function Base(runner, options) {
runner.on(EVENT_TEST_PASS, function (test) {
if (test.duration > test.slow()) {
- test.speed = 'slow';
+ test.speed = "slow";
} else if (test.duration > test.slow() / 2) {
- test.speed = 'medium';
+ test.speed = "medium";
} else {
- test.speed = 'fast';
+ test.speed = "fast";
}
});
@@ -411,22 +414,22 @@ Base.prototype.epilogue = function () {
// passes
fmt =
- color('bright pass', ' ') +
- color('green', ' %d passing') +
- color('light', ' (%s)');
+ color("bright pass", " ") +
+ color("green", " %d passing") +
+ color("light", " (%s)");
Base.consoleLog(fmt, stats.passes || 0, milliseconds(stats.duration));
// pending
if (stats.pending) {
- fmt = color('pending', ' ') + color('pending', ' %d pending');
+ fmt = color("pending", " ") + color("pending", " %d pending");
Base.consoleLog(fmt, stats.pending);
}
// failures
if (stats.failures) {
- fmt = color('fail', ' %d failing');
+ fmt = color("fail", " %d failing");
Base.consoleLog(fmt, stats.failures);
@@ -447,7 +450,7 @@ Base.prototype.epilogue = function () {
*/
function pad(str, len) {
str = String(str);
- return Array(len - str.length + 1).join(' ') + str;
+ return Array(len - str.length + 1).join(" ") + str;
}
/**
@@ -462,28 +465,28 @@ function inlineDiff(actual, expected) {
var msg = errorDiff(actual, expected);
// linenos
- var lines = msg.split('\n');
+ var lines = msg.split("\n");
if (lines.length > 4) {
var width = String(lines.length).length;
msg = lines
.map(function (str, i) {
- return pad(++i, width) + ' |' + ' ' + str;
+ return pad(++i, width) + " |" + " " + str;
})
- .join('\n');
+ .join("\n");
}
// legend
msg =
- '\n' +
- color('diff removed inline', 'actual') +
- ' ' +
- color('diff added inline', 'expected') +
- '\n\n' +
+ "\n" +
+ color("diff removed inline", "actual") +
+ " " +
+ color("diff added inline", "expected") +
+ "\n\n" +
msg +
- '\n';
+ "\n";
// indent
- msg = msg.replace(/^/gm, ' ');
+ msg = msg.replace(/^/gm, " ");
return msg;
}
@@ -496,16 +499,16 @@ function inlineDiff(actual, expected) {
* @return {string} The diff.
*/
function unifiedDiff(actual, expected) {
- var indent = ' ';
+ var indent = " ";
function cleanUp(line) {
- if (line[0] === '+') {
- return indent + colorLines('diff added', line);
+ if (line[0] === "+") {
+ return indent + colorLines("diff added", line);
}
- if (line[0] === '-') {
- return indent + colorLines('diff removed', line);
+ if (line[0] === "-") {
+ return indent + colorLines("diff removed", line);
}
if (line.match(/@@/)) {
- return '--';
+ return "--";
}
if (line.match(/\\ No newline/)) {
return null;
@@ -513,17 +516,17 @@ function unifiedDiff(actual, expected) {
return indent + line;
}
function notBlank(line) {
- return typeof line !== 'undefined' && line !== null;
+ return typeof line !== "undefined" && line !== null;
}
- var msg = diff.createPatch('string', actual, expected);
- var lines = msg.split('\n').splice(5);
+ var msg = diff.createPatch("string", actual, expected);
+ var lines = msg.split("\n").splice(5);
return (
- '\n ' +
- colorLines('diff added', '+ expected') +
- ' ' +
- colorLines('diff removed', '- actual') +
- '\n\n' +
- lines.map(cleanUp).filter(notBlank).join('\n')
+ "\n " +
+ colorLines("diff added", "+ expected") +
+ " " +
+ colorLines("diff removed", "- actual") +
+ "\n\n" +
+ lines.map(cleanUp).filter(notBlank).join("\n")
);
}
@@ -540,14 +543,14 @@ function errorDiff(actual, expected) {
.diffWordsWithSpace(actual, expected)
.map(function (str) {
if (str.added) {
- return colorLines('diff added inline', str.value);
+ return colorLines("diff added inline", str.value);
}
if (str.removed) {
- return colorLines('diff removed inline', str.value);
+ return colorLines("diff removed inline", str.value);
}
return str.value;
})
- .join('');
+ .join("");
}
/**
@@ -560,11 +563,11 @@ function errorDiff(actual, expected) {
*/
function colorLines(name, str) {
return str
- .split('\n')
+ .split("\n")
.map(function (str) {
return color(name, str);
})
- .join('\n');
+ .join("\n");
}
/**
diff --git a/lib/reporters/doc.js b/lib/reporters/doc.js
index f018525e..da8e5d11 100644
--- a/lib/reporters/doc.js
+++ b/lib/reporters/doc.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -11,9 +11,9 @@
* Module dependencies.
*/
-var Base = require('./base');
-var utils = require('../utils');
-var constants = require('../runner').constants;
+var Base = require("./base");
+var utils = require("../utils");
+var constants = require("../runner").constants;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
@@ -41,7 +41,7 @@ function Doc(runner, options) {
var indents = 2;
function indent() {
- return Array(indents).join(' ');
+ return Array(indents).join(" ");
}
runner.on(EVENT_SUITE_BEGIN, function (suite) {
@@ -51,50 +51,50 @@ function Doc(runner, options) {
++indents;
Base.consoleLog('%s<section class="suite">', indent());
++indents;
- Base.consoleLog('%s<h1>%s</h1>', indent(), utils.escape(suite.title));
- Base.consoleLog('%s<dl>', indent());
+ Base.consoleLog("%s<h1>%s</h1>", indent(), utils.escape(suite.title));
+ Base.consoleLog("%s<dl>", indent());
});
runner.on(EVENT_SUITE_END, function (suite) {
if (suite.root) {
return;
}
- Base.consoleLog('%s</dl>', indent());
+ Base.consoleLog("%s</dl>", indent());
--indents;
- Base.consoleLog('%s</section>', indent());
+ Base.consoleLog("%s</section>", indent());
--indents;
});
runner.on(EVENT_TEST_PASS, function (test) {
- Base.consoleLog('%s <dt>%s</dt>', indent(), utils.escape(test.title));
- Base.consoleLog('%s <dt>%s</dt>', indent(), utils.escape(test.file));
+ Base.consoleLog("%s <dt>%s</dt>", indent(), utils.escape(test.title));
+ Base.consoleLog("%s <dt>%s</dt>", indent(), utils.escape(test.file));
var code = utils.escape(utils.clean(test.body));
- Base.consoleLog('%s <dd><pre><code>%s</code></pre></dd>', indent(), code);
+ Base.consoleLog("%s <dd><pre><code>%s</code></pre></dd>", indent(), code);
});
runner.on(EVENT_TEST_FAIL, function (test, err) {
Base.consoleLog(
'%s <dt class="error">%s</dt>',
indent(),
- utils.escape(test.title)
+ utils.escape(test.title),
);
Base.consoleLog(
'%s <dt class="error">%s</dt>',
indent(),
- utils.escape(test.file)
+ utils.escape(test.file),
);
var code = utils.escape(utils.clean(test.body));
Base.consoleLog(
'%s <dd class="error"><pre><code>%s</code></pre></dd>',
indent(),
- code
+ code,
);
Base.consoleLog(
'%s <dd class="error">%s</dd>',
indent(),
- utils.escape(err)
+ utils.escape(err),
);
});
}
-Doc.description = 'HTML documentation';
+Doc.description = "HTML documentation";
diff --git a/lib/reporters/dot.js b/lib/reporters/dot.js
index 46e8b811..f87c36c8 100644
--- a/lib/reporters/dot.js
+++ b/lib/reporters/dot.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -11,9 +11,9 @@
* Module dependencies.
*/
-var Base = require('./base');
-var inherits = require('../utils').inherits;
-var constants = require('../runner').constants;
+var Base = require("./base");
+var inherits = require("../utils").inherits;
+var constants = require("../runner").constants;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
@@ -44,22 +44,22 @@ function Dot(runner, options) {
var n = -1;
runner.on(EVENT_RUN_BEGIN, function () {
- process.stdout.write('\n');
+ process.stdout.write("\n");
});
runner.on(EVENT_TEST_PENDING, function () {
if (++n % width === 0) {
- process.stdout.write('\n ');
+ process.stdout.write("\n ");
}
- process.stdout.write(Base.color('pending', Base.symbols.comma));
+ process.stdout.write(Base.color("pending", Base.symbols.comma));
});
runner.on(EVENT_TEST_PASS, function (test) {
if (++n % width === 0) {
- process.stdout.write('\n ');
+ process.stdout.write("\n ");
}
- if (test.speed === 'slow') {
- process.stdout.write(Base.color('bright yellow', Base.symbols.dot));
+ if (test.speed === "slow") {
+ process.stdout.write(Base.color("bright yellow", Base.symbols.dot));
} else {
process.stdout.write(Base.color(test.speed, Base.symbols.dot));
}
@@ -67,13 +67,13 @@ function Dot(runner, options) {
runner.on(EVENT_TEST_FAIL, function () {
if (++n % width === 0) {
- process.stdout.write('\n ');
+ process.stdout.write("\n ");
}
- process.stdout.write(Base.color('fail', Base.symbols.bang));
+ process.stdout.write(Base.color("fail", Base.symbols.bang));
});
runner.once(EVENT_RUN_END, function () {
- process.stdout.write('\n');
+ process.stdout.write("\n");
self.epilogue();
});
}
@@ -83,4 +83,4 @@ function Dot(runner, options) {
*/
inherits(Dot, Base);
-Dot.description = 'dot matrix representation';
+Dot.description = "dot matrix representation";
diff --git a/lib/reporters/html.js b/lib/reporters/html.js
index 77e0abd3..85cc82f8 100644
--- a/lib/reporters/html.js
+++ b/lib/reporters/html.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -12,10 +12,10 @@
* Module dependencies.
*/
-var Base = require('./base');
-var utils = require('../utils');
-var escapeRe = require('escape-string-regexp');
-var constants = require('../runner').constants;
+var Base = require("./base");
+var utils = require("../utils");
+var escapeRe = require("escape-string-regexp");
+var constants = require("../runner").constants;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
@@ -46,9 +46,9 @@ var statsTemplate =
'<li class="passes"><a href="javascript:void(0);">passes:</a> <em>0</em></li>' +
'<li class="failures"><a href="javascript:void(0);">failures:</a> <em>0</em></li>' +
'<li class="duration">duration: <em>0</em>s</li>' +
- '</ul>';
+ "</ul>";
-var playIcon = '&#x2023;';
+var playIcon = "&#x2023;";
/**
* Constructs a new `HTML` reporter instance.
@@ -66,7 +66,7 @@ function HTML(runner, options) {
var self = this;
var stats = this.stats;
var stat = fragment(statsTemplate);
- var items = stat.getElementsByTagName('li');
+ var items = stat.getElementsByTagName("li");
const resultIndex = 0;
const progressIndex = 1;
const passesIndex = 2;
@@ -77,50 +77,50 @@ function HTML(runner, options) {
/** Passes text and count */
const passesStat = items[passesIndex];
/** Stat item containing the pass count (not the word, just the number) */
- const passesCount = passesStat.getElementsByTagName('em')[0];
+ const passesCount = passesStat.getElementsByTagName("em")[0];
/** Stat item linking to filter to show only passing tests */
- const passesLink = passesStat.getElementsByTagName('a')[0];
+ const passesLink = passesStat.getElementsByTagName("a")[0];
/** Failures text and count */
const failuresStat = items[failuresIndex];
/** Stat item containing the failure count (not the word, just the number) */
- const failuresCount = failuresStat.getElementsByTagName('em')[0];
+ const failuresCount = failuresStat.getElementsByTagName("em")[0];
/** Stat item linking to filter to show only failing tests */
- const failuresLink = failuresStat.getElementsByTagName('a')[0];
+ const failuresLink = failuresStat.getElementsByTagName("a")[0];
/** Stat item linking to the duration time (not the word or unit, just the number) */
- var duration = items[durationIndex].getElementsByTagName('em')[0];
+ var duration = items[durationIndex].getElementsByTagName("em")[0];
var report = fragment('<ul id="mocha-report"></ul>');
var stack = [report];
- var progressText = items[progressIndex].getElementsByTagName('div')[0];
- var progressBar = items[progressIndex].getElementsByTagName('progress')[0];
+ var progressText = items[progressIndex].getElementsByTagName("div")[0];
+ var progressBar = items[progressIndex].getElementsByTagName("progress")[0];
var progressRing = [
- items[progressIndex].getElementsByClassName('ring-flatlight')[0],
- items[progressIndex].getElementsByClassName('ring-highlight')[0]
+ items[progressIndex].getElementsByClassName("ring-flatlight")[0],
+ items[progressIndex].getElementsByClassName("ring-highlight")[0],
];
- var root = document.getElementById('mocha');
+ var root = document.getElementById("mocha");
if (!root) {
- return error('#mocha div missing, add it to your document');
+ return error("#mocha div missing, add it to your document");
}
// pass toggle
- on(passesLink, 'click', function (evt) {
+ on(passesLink, "click", function (evt) {
evt.preventDefault();
unhide();
- var name = /pass/.test(report.className) ? '' : ' pass';
- report.className = report.className.replace(/fail|pass/g, '') + name;
+ var name = /pass/.test(report.className) ? "" : " pass";
+ report.className = report.className.replace(/fail|pass/g, "") + name;
if (report.className.trim()) {
- hideSuitesWithout('test pass');
+ hideSuitesWithout("test pass");
}
});
// failure toggle
- on(failuresLink, 'click', function (evt) {
+ on(failuresLink, "click", function (evt) {
evt.preventDefault();
unhide();
- var name = /fail/.test(report.className) ? '' : ' fail';
- report.className = report.className.replace(/fail|pass/g, '') + name;
+ var name = /fail/.test(report.className) ? "" : " fail";
+ report.className = report.className.replace(/fail|pass/g, "") + name;
if (report.className.trim()) {
- hideSuitesWithout('test fail');
+ hideSuitesWithout("test fail");
}
});
@@ -137,20 +137,20 @@ function HTML(runner, options) {
var el = fragment(
'<li class="suite"><h1><a href="%s">%s</a></h1></li>',
url,
- escape(suite.title)
+ escape(suite.title),
);
// container
stack[0].appendChild(el);
- stack.unshift(document.createElement('ul'));
+ stack.unshift(document.createElement("ul"));
el.appendChild(stack[0]);
});
runner.on(EVENT_SUITE_END, function (suite) {
if (suite.root) {
if (stats.failures === 0) {
- text(resultIndicator, '✓');
- stat.className += ' pass';
+ text(resultIndicator, "✓");
+ stat.className += " pass";
}
updateStats();
return;
@@ -164,7 +164,7 @@ function HTML(runner, options) {
'<li class="test pass %e"><h2>%e<span class="duration">%ems</span> ' +
'<a href="%s" class="replay">' +
playIcon +
- '</a></h2></li>';
+ "</a></h2></li>";
var el = fragment(markup, test.speed, test.title, test.duration, url);
self.addCodeToggle(el, test.body);
appendToStack(el);
@@ -173,22 +173,22 @@ function HTML(runner, options) {
runner.on(EVENT_TEST_FAIL, function (test) {
// Update stat items
- text(resultIndicator, '✖');
- stat.className += ' fail';
+ text(resultIndicator, "✖");
+ stat.className += " fail";
var el = fragment(
'<li class="test fail"><h2>%e <a href="%e" class="replay">' +
playIcon +
- '</a></h2></li>',
+ "</a></h2></li>",
test.title,
- self.testURL(test)
+ self.testURL(test),
);
var stackString; // Note: Includes leading newline
var message = test.err.toString();
// <=IE7 stringifies to [Object Error]. Since it can be overloaded, we
// check for the result of the stringifying.
- if (message === '[object Error]') {
+ if (message === "[object Error]") {
message = test.err.message;
}
@@ -198,31 +198,31 @@ function HTML(runner, options) {
stackString = test.err.stack;
} else {
stackString = test.err.stack.slice(
- test.err.message.length + indexOfMessage
+ test.err.message.length + indexOfMessage,
);
}
} else if (test.err.sourceURL && test.err.line !== undefined) {
// Safari doesn't give you a stack. Let's at least provide a source line.
- stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')';
+ stackString = "\n(" + test.err.sourceURL + ":" + test.err.line + ")";
}
- stackString = stackString || '';
+ stackString = stackString || "";
if (test.err.htmlMessage && stackString) {
el.appendChild(
fragment(
'<div class="html-error">%s\n<pre class="error">%e</pre></div>',
test.err.htmlMessage,
- stackString
- )
+ stackString,
+ ),
);
} else if (test.err.htmlMessage) {
el.appendChild(
- fragment('<div class="html-error">%s</div>', test.err.htmlMessage)
+ fragment('<div class="html-error">%s</div>', test.err.htmlMessage),
);
} else {
el.appendChild(
- fragment('<pre class="error">%e%e</pre>', message, stackString)
+ fragment('<pre class="error">%e%e</pre>', message, stackString),
);
}
@@ -234,7 +234,7 @@ function HTML(runner, options) {
runner.on(EVENT_TEST_PENDING, function (test) {
var el = fragment(
'<li class="test pass pending"><h2>%e</h2></li>',
- test.title
+ test.title,
);
appendToStack(el);
updateStats();
@@ -257,18 +257,22 @@ function HTML(runner, options) {
var decimalPlaces = Math.ceil(Math.log10(runner.total / 100));
text(
progressText,
- percent.toFixed(Math.min(Math.max(decimalPlaces, 0), 100)) + '%'
+ percent.toFixed(Math.min(Math.max(decimalPlaces, 0), 100)) + "%",
);
}
if (progressRing) {
- var radius = parseFloat(getComputedStyle(progressRing[0]).getPropertyValue('r'));
+ var radius = parseFloat(
+ getComputedStyle(progressRing[0]).getPropertyValue("r"),
+ );
var wholeArc = Math.PI * 2 * radius;
var highlightArc = percent * (wholeArc / 100);
// The progress ring is in 2 parts, the flatlight color and highlight color.
// Rendering both on top of the other, seems to make a 3rd color on the edges.
// To create 1 whole ring with 2 colors, both parts are inverse of the other.
- progressRing[0].style['stroke-dasharray'] = `0,${highlightArc}px,${wholeArc}px`;
- progressRing[1].style['stroke-dasharray'] = `${highlightArc}px,${wholeArc}px`;
+ progressRing[0].style["stroke-dasharray"] =
+ `0,${highlightArc}px,${wholeArc}px`;
+ progressRing[1].style["stroke-dasharray"] =
+ `${highlightArc}px,${wholeArc}px`;
}
// update stats
@@ -290,13 +294,15 @@ function makeUrl(s) {
// Remove previous {grep, fgrep, invert} query parameters if present
if (search) {
- search = search.replace(/[?&](?:f?grep|invert)=[^&\s]*/g, '').replace(/^&/, '?');
+ search = search
+ .replace(/[?&](?:f?grep|invert)=[^&\s]*/g, "")
+ .replace(/^&/, "?");
}
return (
window.location.pathname +
- (search ? search + '&' : '?') +
- 'grep=' +
+ (search ? search + "&" : "?") +
+ "grep=" +
encodeURIComponent(s)
);
}
@@ -307,7 +313,7 @@ function makeUrl(s) {
* @param {Object} [suite]
*/
HTML.prototype.suiteURL = function (suite) {
- return makeUrl('^' + escapeRe(suite.fullTitle()) + ' ');
+ return makeUrl("^" + escapeRe(suite.fullTitle()) + " ");
};
/**
@@ -316,7 +322,7 @@ HTML.prototype.suiteURL = function (suite) {
* @param {Object} [test]
*/
HTML.prototype.testURL = function (test) {
- return makeUrl('^' + escapeRe(test.fullTitle()) + '$');
+ return makeUrl("^" + escapeRe(test.fullTitle()) + "$");
};
/**
@@ -326,15 +332,15 @@ HTML.prototype.testURL = function (test) {
* @param {string} contents
*/
HTML.prototype.addCodeToggle = function (el, contents) {
- var h2 = el.getElementsByTagName('h2')[0];
+ var h2 = el.getElementsByTagName("h2")[0];
- on(h2, 'click', function () {
- pre.style.display = pre.style.display === 'none' ? 'block' : 'none';
+ on(h2, "click", function () {
+ pre.style.display = pre.style.display === "none" ? "block" : "none";
});
- var pre = fragment('<pre><code>%e</code></pre>', utils.clean(contents));
+ var pre = fragment("<pre><code>%e</code></pre>", utils.clean(contents));
el.appendChild(pre);
- pre.style.display = 'none';
+ pre.style.display = "none";
};
/**
@@ -353,14 +359,14 @@ function error(msg) {
*/
function fragment(html) {
var args = arguments;
- var div = document.createElement('div');
+ var div = document.createElement("div");
var i = 1;
div.innerHTML = html.replace(/%([se])/g, function (_, type) {
switch (type) {
- case 's':
+ case "s":
return String(args[i++]);
- case 'e':
+ case "e":
return escape(args[i++]);
// no default
}
@@ -376,11 +382,11 @@ function fragment(html) {
* @param {text} classname
*/
function hideSuitesWithout(classname) {
- var suites = document.getElementsByClassName('suite');
+ var suites = document.getElementsByClassName("suite");
for (var i = 0; i < suites.length; i++) {
var els = suites[i].getElementsByClassName(classname);
if (!els.length) {
- suites[i].className += ' hidden';
+ suites[i].className += " hidden";
}
}
}
@@ -389,9 +395,9 @@ function hideSuitesWithout(classname) {
* Unhide .hidden suites.
*/
function unhide() {
- var els = document.getElementsByClassName('suite hidden');
+ var els = document.getElementsByClassName("suite hidden");
while (els.length > 0) {
- els[0].className = els[0].className.replace('suite hidden', 'suite');
+ els[0].className = els[0].className.replace("suite hidden", "suite");
}
}
@@ -416,7 +422,7 @@ function on(el, event, fn) {
if (el.addEventListener) {
el.addEventListener(event, fn, false);
} else {
- el.attachEvent('on' + event, fn);
+ el.attachEvent("on" + event, fn);
}
}
diff --git a/lib/reporters/index.js b/lib/reporters/index.js
index d3b5481e..d7103c1b 100644
--- a/lib/reporters/index.js
+++ b/lib/reporters/index.js
@@ -1,19 +1,19 @@
-'use strict';
+"use strict";
// Alias exports to a their normalized format Mocha#reporter to prevent a need
// for dynamic (try/catch) requires, which Browserify doesn't handle.
-exports.Base = exports.base = require('./base');
-exports.Dot = exports.dot = require('./dot');
-exports.Doc = exports.doc = require('./doc');
-exports.TAP = exports.tap = require('./tap');
-exports.JSON = exports.json = require('./json');
-exports.HTML = exports.html = require('./html');
-exports.List = exports.list = require('./list');
-exports.Min = exports.min = require('./min');
-exports.Spec = exports.spec = require('./spec');
-exports.Nyan = exports.nyan = require('./nyan');
-exports.XUnit = exports.xunit = require('./xunit');
-exports.Markdown = exports.markdown = require('./markdown');
-exports.Progress = exports.progress = require('./progress');
-exports.Landing = exports.landing = require('./landing');
-exports.JSONStream = exports['json-stream'] = require('./json-stream');
+exports.Base = exports.base = require("./base");
+exports.Dot = exports.dot = require("./dot");
+exports.Doc = exports.doc = require("./doc");
+exports.TAP = exports.tap = require("./tap");
+exports.JSON = exports.json = require("./json");
+exports.HTML = exports.html = require("./html");
+exports.List = exports.list = require("./list");
+exports.Min = exports.min = require("./min");
+exports.Spec = exports.spec = require("./spec");
+exports.Nyan = exports.nyan = require("./nyan");
+exports.XUnit = exports.xunit = require("./xunit");
+exports.Markdown = exports.markdown = require("./markdown");
+exports.Progress = exports.progress = require("./progress");
+exports.Landing = exports.landing = require("./landing");
+exports.JSONStream = exports["json-stream"] = require("./json-stream");
diff --git a/lib/reporters/json-stream.js b/lib/reporters/json-stream.js
index a57e4a35..9d157e1e 100644
--- a/lib/reporters/json-stream.js
+++ b/lib/reporters/json-stream.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -12,8 +12,8 @@
* Module dependencies.
*/
-var Base = require('./base');
-var constants = require('../runner').constants;
+var Base = require("./base");
+var constants = require("../runner").constants;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
@@ -42,22 +42,22 @@ function JSONStream(runner, options) {
var total = runner.total;
runner.once(EVENT_RUN_BEGIN, function () {
- writeEvent(['start', {total}]);
+ writeEvent(["start", { total }]);
});
runner.on(EVENT_TEST_PASS, function (test) {
- writeEvent(['pass', clean(test)]);
+ writeEvent(["pass", clean(test)]);
});
runner.on(EVENT_TEST_FAIL, function (test, err) {
test = clean(test);
test.err = err.message;
test.stack = err.stack || null;
- writeEvent(['fail', test]);
+ writeEvent(["fail", test]);
});
runner.once(EVENT_RUN_END, function () {
- writeEvent(['end', self.stats]);
+ writeEvent(["end", self.stats]);
});
}
@@ -68,7 +68,7 @@ function JSONStream(runner, options) {
* @param {unknown[]} event - Mocha event to be output.
*/
function writeEvent(event) {
- process.stdout.write(JSON.stringify(event) + '\n');
+ process.stdout.write(JSON.stringify(event) + "\n");
}
/**
@@ -86,8 +86,8 @@ function clean(test) {
file: test.file,
duration: test.duration,
currentRetry: test.currentRetry(),
- speed: test.speed
+ speed: test.speed,
};
}
-JSONStream.description = 'newline delimited JSON events';
+JSONStream.description = "newline delimited JSON events";
diff --git a/lib/reporters/json.js b/lib/reporters/json.js
index f4e1a9d9..8ceef6bd 100644
--- a/lib/reporters/json.js
+++ b/lib/reporters/json.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -11,12 +11,12 @@
* Module dependencies.
*/
-var Base = require('./base');
-var fs = require('node:fs');
-var path = require('node:path');
-const createUnsupportedError = require('../errors').createUnsupportedError;
-const utils = require('../utils');
-var constants = require('../runner').constants;
+var Base = require("./base");
+var fs = require("node:fs");
+var path = require("node:path");
+const createUnsupportedError = require("../errors").createUnsupportedError;
+const utils = require("../utils");
+var constants = require("../runner").constants;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
@@ -51,7 +51,7 @@ function JSONReporter(runner, options = {}) {
if (options.reporterOption && options.reporterOption.output) {
if (utils.isBrowser()) {
- throw createUnsupportedError('file output not supported in browser');
+ throw createUnsupportedError("file output not supported in browser");
}
output = options.reporterOption.output;
}
@@ -78,7 +78,7 @@ function JSONReporter(runner, options = {}) {
tests: tests.map(clean),
pending: pending.map(clean),
failures: failures.map(clean),
- passes: passes.map(clean)
+ passes: passes.map(clean),
};
runner.testResults = obj;
@@ -86,11 +86,11 @@ function JSONReporter(runner, options = {}) {
var json = JSON.stringify(obj, null, 2);
if (output) {
try {
- fs.mkdirSync(path.dirname(output), {recursive: true});
+ fs.mkdirSync(path.dirname(output), { recursive: true });
fs.writeFileSync(output, json);
} catch (err) {
console.error(
- `${Base.symbols.err} [mocha] writing output to "${output}" failed: ${err.message}\n`
+ `${Base.symbols.err} [mocha] writing output to "${output}" failed: ${err.message}\n`,
);
process.stdout.write(json);
}
@@ -121,7 +121,7 @@ function clean(test) {
duration: test.duration,
currentRetry: test.currentRetry(),
speed: test.speed,
- err: cleanCycles(err)
+ err: cleanCycles(err),
};
}
@@ -136,16 +136,16 @@ function cleanCycles(obj) {
var cache = [];
return JSON.parse(
JSON.stringify(obj, function (key, value) {
- if (typeof value === 'object' && value !== null) {
+ if (typeof value === "object" && value !== null) {
if (cache.indexOf(value) !== -1) {
// Instead of going in a circle, we'll print [object Object]
- return '' + value;
+ return "" + value;
}
cache.push(value);
}
return value;
- })
+ }),
);
}
@@ -164,4 +164,4 @@ function errorJSON(err) {
return res;
}
-JSONReporter.description = 'single JSON object';
+JSONReporter.description = "single JSON object";
diff --git a/lib/reporters/landing.js b/lib/reporters/landing.js
index e30e497a..bbb01c4e 100644
--- a/lib/reporters/landing.js
+++ b/lib/reporters/landing.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -11,13 +11,13 @@
* Module dependencies.
*/
-var Base = require('./base');
-var inherits = require('../utils').inherits;
-var constants = require('../runner').constants;
+var Base = require("./base");
+var inherits = require("../utils").inherits;
+var constants = require("../runner").constants;
var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
var EVENT_RUN_END = constants.EVENT_RUN_END;
var EVENT_TEST_END = constants.EVENT_TEST_END;
-var STATE_FAILED = require('../runnable').constants.STATE_FAILED;
+var STATE_FAILED = require("../runnable").constants.STATE_FAILED;
var cursor = Base.cursor;
var color = Base.color;
@@ -38,7 +38,7 @@ Base.colors.plane = 0;
* Airplane crash color.
*/
-Base.colors['plane crash'] = 31;
+Base.colors["plane crash"] = 31;
/**
* Runway color.
@@ -63,18 +63,18 @@ function Landing(runner, options) {
var width = (Base.window.width * 0.75) | 0;
var stream = process.stdout;
- var plane = color('plane', '✈');
+ var plane = color("plane", "✈");
var crashed = -1;
var n = 0;
var total = 0;
function runway() {
- var buf = Array(width).join('-');
- return ' ' + color('runway', buf);
+ var buf = Array(width).join("-");
+ return " " + color("runway", buf);
}
runner.on(EVENT_RUN_BEGIN, function () {
- stream.write('\n\n\n ');
+ stream.write("\n\n\n ");
cursor.hide();
});
@@ -83,32 +83,32 @@ function Landing(runner, options) {
var col = crashed === -1 ? ((width * ++n) / ++total) | 0 : crashed;
// show the crash
if (test.state === STATE_FAILED) {
- plane = color('plane crash', '✈');
+ plane = color("plane crash", "✈");
crashed = col;
}
// render landing strip
- stream.write('\u001b[' + (width + 1) + 'D\u001b[2A');
+ stream.write("\u001b[" + (width + 1) + "D\u001b[2A");
stream.write(runway());
- stream.write('\n ');
- stream.write(color('runway', Array(col).join('⋅')));
+ stream.write("\n ");
+ stream.write(color("runway", Array(col).join("⋅")));
stream.write(plane);
- stream.write(color('runway', Array(width - col).join('⋅') + '\n'));
+ stream.write(color("runway", Array(width - col).join("⋅") + "\n"));
stream.write(runway());
- stream.write('\u001b[0m');
+ stream.write("\u001b[0m");
});
runner.once(EVENT_RUN_END, function () {
cursor.show();
- process.stdout.write('\n');
+ process.stdout.write("\n");
self.epilogue();
});
// if cursor is hidden when we ctrl-C, then it will remain hidden unless...
- process.once('SIGINT', function () {
+ process.once("SIGINT", function () {
cursor.show();
process.nextTick(function () {
- process.kill(process.pid, 'SIGINT');
+ process.kill(process.pid, "SIGINT");
});
});
}
@@ -118,4 +118,4 @@ function Landing(runner, options) {
*/
inherits(Landing, Base);
-Landing.description = 'Unicode landing strip';
+Landing.description = "Unicode landing strip";
diff --git a/lib/reporters/list.js b/lib/reporters/list.js
index 66dd997d..ff372124 100644
--- a/lib/reporters/list.js
+++ b/lib/reporters/list.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -11,9 +11,9 @@
* Module dependencies.
*/
-var Base = require('./base');
-var inherits = require('../utils').inherits;
-var constants = require('../runner').constants;
+var Base = require("./base");
+var inherits = require("../utils").inherits;
+var constants = require("../runner").constants;
var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
var EVENT_RUN_END = constants.EVENT_RUN_END;
var EVENT_TEST_BEGIN = constants.EVENT_TEST_BEGIN;
@@ -50,26 +50,26 @@ function List(runner, options) {
});
runner.on(EVENT_TEST_BEGIN, function (test) {
- process.stdout.write(color('pass', ' ' + test.fullTitle() + ': '));
+ process.stdout.write(color("pass", " " + test.fullTitle() + ": "));
});
runner.on(EVENT_TEST_PENDING, function (test) {
- var fmt = color('checkmark', ' -') + color('pending', ' %s');
+ var fmt = color("checkmark", " -") + color("pending", " %s");
Base.consoleLog(fmt, test.fullTitle());
});
runner.on(EVENT_TEST_PASS, function (test) {
var fmt =
- color('checkmark', ' ' + Base.symbols.ok) +
- color('pass', ' %s: ') +
- color(test.speed, '%dms');
+ color("checkmark", " " + Base.symbols.ok) +
+ color("pass", " %s: ") +
+ color(test.speed, "%dms");
cursor.CR();
Base.consoleLog(fmt, test.fullTitle(), test.duration);
});
runner.on(EVENT_TEST_FAIL, function (test) {
cursor.CR();
- Base.consoleLog(color('fail', ' %d) %s'), ++n, test.fullTitle());
+ Base.consoleLog(color("fail", " %d) %s"), ++n, test.fullTitle());
});
runner.once(EVENT_RUN_END, self.epilogue.bind(self));
diff --git a/lib/reporters/markdown.js b/lib/reporters/markdown.js
index 2e196d6b..5c2e487d 100644
--- a/lib/reporters/markdown.js
+++ b/lib/reporters/markdown.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -11,9 +11,9 @@
* Module dependencies.
*/
-var Base = require('./base');
-var utils = require('../utils');
-var constants = require('../runner').constants;
+var Base = require("./base");
+var utils = require("../utils");
+var constants = require("../runner").constants;
var EVENT_RUN_END = constants.EVENT_RUN_END;
var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
var EVENT_SUITE_END = constants.EVENT_SUITE_END;
@@ -23,7 +23,7 @@ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
* Constants
*/
-var SUITE_PREFIX = '$';
+var SUITE_PREFIX = "$";
/**
* Expose `Markdown`.
@@ -45,17 +45,17 @@ function Markdown(runner, options) {
Base.call(this, runner, options);
var level = 0;
- var buf = '';
+ var buf = "";
function title(str) {
- return Array(level).join('#') + ' ' + str;
+ return Array(level).join("#") + " " + str;
}
function mapTOC(suite, obj) {
var ret = obj;
var key = SUITE_PREFIX + suite.title;
- obj = obj[key] = obj[key] || {suite};
+ obj = obj[key] = obj[key] || { suite };
suite.suites.forEach(function (suite) {
mapTOC(suite, obj);
});
@@ -65,16 +65,16 @@ function Markdown(runner, options) {
function stringifyTOC(obj, level) {
++level;
- var buf = '';
+ var buf = "";
var link;
for (var key in obj) {
- if (key === 'suite') {
+ if (key === "suite") {
continue;
}
if (key !== SUITE_PREFIX) {
- link = ' - [' + key.substring(1) + ']';
- link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n';
- buf += Array(level).join(' ') + link;
+ link = " - [" + key.substring(1) + "]";
+ link += "(#" + utils.slug(obj[key].suite.fullTitle()) + ")\n";
+ buf += Array(level).join(" ") + link;
}
buf += stringifyTOC(obj[key], level);
}
@@ -91,8 +91,8 @@ function Markdown(runner, options) {
runner.on(EVENT_SUITE_BEGIN, function (suite) {
++level;
var slug = utils.slug(suite.fullTitle());
- buf += '<a name="' + slug + '"></a>' + '\n';
- buf += title(suite.title) + '\n';
+ buf += '<a name="' + slug + '"></a>' + "\n";
+ buf += title(suite.title) + "\n";
});
runner.on(EVENT_SUITE_END, function () {
@@ -101,17 +101,17 @@ function Markdown(runner, options) {
runner.on(EVENT_TEST_PASS, function (test) {
var code = utils.clean(test.body);
- buf += test.title + '.\n';
- buf += '\n```js\n';
- buf += code + '\n';
- buf += '```\n\n';
+ buf += test.title + ".\n";
+ buf += "\n```js\n";
+ buf += code + "\n";
+ buf += "```\n\n";
});
runner.once(EVENT_RUN_END, function () {
- process.stdout.write('# TOC\n');
+ process.stdout.write("# TOC\n");
process.stdout.write(generateTOC(runner.suite));
process.stdout.write(buf);
});
}
-Markdown.description = 'GitHub Flavored Markdown';
+Markdown.description = "GitHub Flavored Markdown";
diff --git a/lib/reporters/min.js b/lib/reporters/min.js
index 6571ec6f..a825e629 100644
--- a/lib/reporters/min.js
+++ b/lib/reporters/min.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -11,9 +11,9 @@
* Module dependencies.
*/
-var Base = require('./base');
-var inherits = require('../utils').inherits;
-var constants = require('../runner').constants;
+var Base = require("./base");
+var inherits = require("../utils").inherits;
+var constants = require("../runner").constants;
var EVENT_RUN_END = constants.EVENT_RUN_END;
var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
@@ -41,9 +41,9 @@ function Min(runner, options) {
runner.on(EVENT_RUN_BEGIN, function () {
// clear screen
- process.stdout.write('\u001b[2J');
+ process.stdout.write("\u001b[2J");
// set cursor position
- process.stdout.write('\u001b[1;3H');
+ process.stdout.write("\u001b[1;3H");
});
runner.once(EVENT_RUN_END, this.epilogue.bind(this));
@@ -54,4 +54,4 @@ function Min(runner, options) {
*/
inherits(Min, Base);
-Min.description = 'essentially just a summary';
+Min.description = "essentially just a summary";
diff --git a/lib/reporters/nyan.js b/lib/reporters/nyan.js
index aaeaf423..85720660 100644
--- a/lib/reporters/nyan.js
+++ b/lib/reporters/nyan.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -11,9 +11,9 @@
* Module dependencies.
*/
-var Base = require('./base');
-var constants = require('../runner').constants;
-var inherits = require('../utils').inherits;
+var Base = require("./base");
+var constants = require("../runner").constants;
+var inherits = require("../utils").inherits;
var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
@@ -71,7 +71,7 @@ function NyanCat(runner, options) {
runner.once(EVENT_RUN_END, function () {
Base.cursor.show();
for (var i = 0; i < self.numberOfLines; i++) {
- process.stdout.write('\n');
+ process.stdout.write("\n");
}
self.epilogue();
});
@@ -107,15 +107,15 @@ NyanCat.prototype.drawScoreboard = function () {
var stats = this.stats;
function draw(type, n) {
- process.stdout.write(' ');
+ process.stdout.write(" ");
process.stdout.write(Base.color(type, n));
- process.stdout.write('\n');
+ process.stdout.write("\n");
}
- draw('green', stats.passes);
- draw('fail', stats.failures);
- draw('pending', stats.pending);
- process.stdout.write('\n');
+ draw("green", stats.passes);
+ draw("fail", stats.failures);
+ draw("pending", stats.pending);
+ process.stdout.write("\n");
this.cursorUp(this.numberOfLines);
};
@@ -127,7 +127,7 @@ NyanCat.prototype.drawScoreboard = function () {
*/
NyanCat.prototype.appendRainbow = function () {
- var segment = this.tick ? '_' : '-';
+ var segment = this.tick ? "_" : "-";
var rainbowified = this.rainbowify(segment);
for (var index = 0; index < this.numberOfLines; index++) {
@@ -149,9 +149,9 @@ NyanCat.prototype.drawRainbow = function () {
var self = this;
this.trajectories.forEach(function (line) {
- process.stdout.write('\u001b[' + self.scoreboardWidth + 'C');
- process.stdout.write(line.join(''));
- process.stdout.write('\n');
+ process.stdout.write("\u001b[" + self.scoreboardWidth + "C");
+ process.stdout.write(line.join(""));
+ process.stdout.write("\n");
});
this.cursorUp(this.numberOfLines);
@@ -165,28 +165,28 @@ NyanCat.prototype.drawRainbow = function () {
NyanCat.prototype.drawNyanCat = function () {
var self = this;
var startWidth = this.scoreboardWidth + this.trajectories[0].length;
- var dist = '\u001b[' + startWidth + 'C';
- var padding = '';
+ var dist = "\u001b[" + startWidth + "C";
+ var padding = "";
process.stdout.write(dist);
- process.stdout.write('_,------,');
- process.stdout.write('\n');
+ process.stdout.write("_,------,");
+ process.stdout.write("\n");
process.stdout.write(dist);
- padding = self.tick ? ' ' : ' ';
- process.stdout.write('_|' + padding + '/\\_/\\ ');
- process.stdout.write('\n');
+ padding = self.tick ? " " : " ";
+ process.stdout.write("_|" + padding + "/\\_/\\ ");
+ process.stdout.write("\n");
process.stdout.write(dist);
- padding = self.tick ? '_' : '__';
- var tail = self.tick ? '~' : '^';
- process.stdout.write(tail + '|' + padding + this.face() + ' ');
- process.stdout.write('\n');
+ padding = self.tick ? "_" : "__";
+ var tail = self.tick ? "~" : "^";
+ process.stdout.write(tail + "|" + padding + this.face() + " ");
+ process.stdout.write("\n");
process.stdout.write(dist);
- padding = self.tick ? ' ' : ' ';
+ padding = self.tick ? " " : " ";
process.stdout.write(padding + '"" "" ');
- process.stdout.write('\n');
+ process.stdout.write("\n");
this.cursorUp(this.numberOfLines);
};
@@ -201,13 +201,13 @@ NyanCat.prototype.drawNyanCat = function () {
NyanCat.prototype.face = function () {
var stats = this.stats;
if (stats.failures) {
- return '( x .x)';
+ return "( x .x)";
} else if (stats.pending) {
- return '( o .o)';
+ return "( o .o)";
} else if (stats.passes) {
- return '( ^ .^)';
+ return "( ^ .^)";
}
- return '( - .-)';
+ return "( - .-)";
};
/**
@@ -218,7 +218,7 @@ NyanCat.prototype.face = function () {
*/
NyanCat.prototype.cursorUp = function (n) {
- process.stdout.write('\u001b[' + n + 'A');
+ process.stdout.write("\u001b[" + n + "A");
};
/**
@@ -229,7 +229,7 @@ NyanCat.prototype.cursorUp = function (n) {
*/
NyanCat.prototype.cursorDown = function (n) {
- process.stdout.write('\u001b[' + n + 'B');
+ process.stdout.write("\u001b[" + n + "B");
};
/**
@@ -266,7 +266,7 @@ NyanCat.prototype.rainbowify = function (str) {
}
var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];
this.colorIndex += 1;
- return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m';
+ return "\u001b[38;5;" + color + "m" + str + "\u001b[0m";
};
NyanCat.description = '"nyan cat"';
diff --git a/lib/reporters/progress.js b/lib/reporters/progress.js
index e25f4f91..9058cdbf 100644
--- a/lib/reporters/progress.js
+++ b/lib/reporters/progress.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -11,12 +11,12 @@
* Module dependencies.
*/
-var Base = require('./base');
-var constants = require('../runner').constants;
+var Base = require("./base");
+var constants = require("../runner").constants;
var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
var EVENT_TEST_END = constants.EVENT_TEST_END;
var EVENT_RUN_END = constants.EVENT_RUN_END;
-var inherits = require('../utils').inherits;
+var inherits = require("../utils").inherits;
var color = Base.color;
var cursor = Base.cursor;
@@ -55,15 +55,15 @@ function Progress(runner, options) {
options = options || {};
var reporterOptions = options.reporterOptions || {};
- options.open = reporterOptions.open || '[';
- options.complete = reporterOptions.complete || '▬';
+ options.open = reporterOptions.open || "[";
+ options.complete = reporterOptions.complete || "▬";
options.incomplete = reporterOptions.incomplete || Base.symbols.dot;
- options.close = reporterOptions.close || ']';
+ options.close = reporterOptions.close || "]";
options.verbose = reporterOptions.verbose || false;
// tests started
runner.on(EVENT_RUN_BEGIN, function () {
- process.stdout.write('\n');
+ process.stdout.write("\n");
cursor.hide();
});
@@ -82,13 +82,13 @@ function Progress(runner, options) {
lastN = n;
cursor.CR();
- process.stdout.write('\u001b[J');
- process.stdout.write(color('progress', ' ' + options.open));
+ process.stdout.write("\u001b[J");
+ process.stdout.write(color("progress", " " + options.open));
process.stdout.write(Array(n).join(options.complete));
process.stdout.write(Array(i).join(options.incomplete));
- process.stdout.write(color('progress', options.close));
+ process.stdout.write(color("progress", options.close));
if (options.verbose) {
- process.stdout.write(color('progress', ' ' + complete + ' of ' + total));
+ process.stdout.write(color("progress", " " + complete + " of " + total));
}
});
@@ -96,7 +96,7 @@ function Progress(runner, options) {
// and the failures if any
runner.once(EVENT_RUN_END, function () {
cursor.show();
- process.stdout.write('\n');
+ process.stdout.write("\n");
self.epilogue();
});
}
@@ -106,4 +106,4 @@ function Progress(runner, options) {
*/
inherits(Progress, Base);
-Progress.description = 'a progress bar';
+Progress.description = "a progress bar";
diff --git a/lib/reporters/spec.js b/lib/reporters/spec.js
index 3d4dd1af..5f2f56d3 100644
--- a/lib/reporters/spec.js
+++ b/lib/reporters/spec.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -12,8 +12,8 @@
* Module dependencies.
*/
-var Base = require('./base');
-var constants = require('../runner').constants;
+var Base = require("./base");
+var constants = require("../runner").constants;
var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
var EVENT_RUN_END = constants.EVENT_RUN_END;
var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
@@ -21,7 +21,7 @@ var EVENT_SUITE_END = constants.EVENT_SUITE_END;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
-var inherits = require('../utils').inherits;
+var inherits = require("../utils").inherits;
var color = Base.color;
/**
@@ -48,7 +48,7 @@ function Spec(runner, options) {
var n = 0;
function indent() {
- return Array(indents).join(' ');
+ return Array(indents).join(" ");
}
runner.on(EVENT_RUN_BEGIN, function () {
@@ -57,7 +57,7 @@ function Spec(runner, options) {
runner.on(EVENT_SUITE_BEGIN, function (suite) {
++indents;
- Base.consoleLog(color('suite', '%s%s'), indent(), suite.title);
+ Base.consoleLog(color("suite", "%s%s"), indent(), suite.title);
});
runner.on(EVENT_SUITE_END, function () {
@@ -68,30 +68,30 @@ function Spec(runner, options) {
});
runner.on(EVENT_TEST_PENDING, function (test) {
- var fmt = indent() + color('pending', ' - %s');
+ var fmt = indent() + color("pending", " - %s");
Base.consoleLog(fmt, test.title);
});
runner.on(EVENT_TEST_PASS, function (test) {
var fmt;
- if (test.speed === 'fast') {
+ if (test.speed === "fast") {
fmt =
indent() +
- color('checkmark', ' ' + Base.symbols.ok) +
- color('pass', ' %s');
+ color("checkmark", " " + Base.symbols.ok) +
+ color("pass", " %s");
Base.consoleLog(fmt, test.title);
} else {
fmt =
indent() +
- color('checkmark', ' ' + Base.symbols.ok) +
- color('pass', ' %s') +
- color(test.speed, ' (%dms)');
+ color("checkmark", " " + Base.symbols.ok) +
+ color("pass", " %s") +
+ color(test.speed, " (%dms)");
Base.consoleLog(fmt, test.title, test.duration);
}
});
runner.on(EVENT_TEST_FAIL, function (test) {
- Base.consoleLog(indent() + color('fail', ' %d) %s'), ++n, test.title);
+ Base.consoleLog(indent() + color("fail", " %d) %s"), ++n, test.title);
});
runner.once(EVENT_RUN_END, self.epilogue.bind(self));
@@ -102,4 +102,4 @@ function Spec(runner, options) {
*/
inherits(Spec, Base);
-Spec.description = 'hierarchical & verbose [default]';
+Spec.description = "hierarchical & verbose [default]";
diff --git a/lib/reporters/tap.js b/lib/reporters/tap.js
index 43e53b82..d34ac981 100644
--- a/lib/reporters/tap.js
+++ b/lib/reporters/tap.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -12,16 +12,16 @@
* Module dependencies.
*/
-var util = require('node:util');
-var Base = require('./base');
-var constants = require('../runner').constants;
+var util = require("node:util");
+var Base = require("./base");
+var constants = require("../runner").constants;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;
var EVENT_RUN_END = constants.EVENT_RUN_END;
var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
var EVENT_TEST_END = constants.EVENT_TEST_END;
-var inherits = require('../utils').inherits;
+var inherits = require("../utils").inherits;
var sprintf = util.format;
/**
@@ -46,7 +46,7 @@ function TAP(runner, options) {
var self = this;
var n = 1;
- var tapVersion = '12';
+ var tapVersion = "12";
if (options && options.reporterOptions) {
if (options.reporterOptions.tapVersion) {
tapVersion = options.reporterOptions.tapVersion.toString();
@@ -93,7 +93,7 @@ inherits(TAP, Base);
* @return {String} title with any hash character removed
*/
function title(test) {
- return test.fullTitle().replace(/#/g, '');
+ return test.fullTitle().replace(/#/g, "");
}
/**
@@ -105,7 +105,7 @@ function title(test) {
*/
function println() {
var vargs = Array.from(arguments);
- vargs[0] += '\n';
+ vargs[0] += "\n";
process.stdout.write(sprintf.apply(null, vargs));
}
@@ -120,13 +120,13 @@ function println() {
function createProducer(tapVersion) {
var producers = {
12: new TAP12Producer(),
- 13: new TAP13Producer()
+ 13: new TAP13Producer(),
};
var producer = producers[tapVersion];
if (!producer) {
throw new Error(
- 'invalid or unsupported TAP version: ' + JSON.stringify(tapVersion)
+ "invalid or unsupported TAP version: " + JSON.stringify(tapVersion),
);
}
@@ -159,7 +159,7 @@ TAPProducer.prototype.writeVersion = function () {};
* @param {number} ntests - Number of tests that are planned to run.
*/
TAPProducer.prototype.writePlan = function (ntests) {
- println('%d..%d', 1, ntests);
+ println("%d..%d", 1, ntests);
};
/**
@@ -170,7 +170,7 @@ TAPProducer.prototype.writePlan = function (ntests) {
* @param {Test} test - Instance containing test information.
*/
TAPProducer.prototype.writePass = function (n, test) {
- println('ok %d %s', n, title(test));
+ println("ok %d %s", n, title(test));
};
/**
@@ -181,7 +181,7 @@ TAPProducer.prototype.writePass = function (n, test) {
* @param {Test} test - Instance containing test information.
*/
TAPProducer.prototype.writePending = function (n, test) {
- println('ok %d %s # SKIP -', n, title(test));
+ println("ok %d %s # SKIP -", n, title(test));
};
/**
@@ -192,7 +192,7 @@ TAPProducer.prototype.writePending = function (n, test) {
* @param {Test} test - Instance containing test information.
*/
TAPProducer.prototype.writeFail = function (n, test) {
- println('not ok %d %s', n, title(test));
+ println("not ok %d %s", n, title(test));
};
/**
@@ -203,10 +203,10 @@ TAPProducer.prototype.writeFail = function (n, test) {
*/
TAPProducer.prototype.writeEpilogue = function (stats) {
// :TBD: Why is this not counting pending tests?
- println('# tests ' + (stats.passes + stats.failures));
- println('# pass ' + stats.passes);
+ println("# tests " + (stats.passes + stats.failures));
+ println("# pass " + stats.passes);
// :TBD: Why are we not showing pending results?
- println('# fail ' + stats.failures);
+ println("# fail " + stats.failures);
this.writePlan(stats.passes + stats.failures + stats.pending);
};
@@ -230,10 +230,10 @@ function TAP12Producer() {
this.writeFail = function (n, test, err) {
TAPProducer.prototype.writeFail.call(this, n, test, err);
if (err.message) {
- println(err.message.replace(/^/gm, ' '));
+ println(err.message.replace(/^/gm, " "));
}
if (err.stack) {
- println(err.stack.replace(/^/gm, ' '));
+ println(err.stack.replace(/^/gm, " "));
}
};
}
@@ -261,7 +261,7 @@ function TAP13Producer() {
* @override
*/
this.writeVersion = function () {
- println('TAP version 13');
+ println("TAP version 13");
};
/**
@@ -272,21 +272,21 @@ function TAP13Producer() {
TAPProducer.prototype.writeFail.call(this, n, test, err);
var emitYamlBlock = err.message != null || err.stack != null;
if (emitYamlBlock) {
- println(indent(1) + '---');
+ println(indent(1) + "---");
if (err.message) {
- println(indent(2) + 'message: |-');
+ println(indent(2) + "message: |-");
println(err.message.replace(/^/gm, indent(3)));
}
if (err.stack) {
- println(indent(2) + 'stack: |-');
+ println(indent(2) + "stack: |-");
println(err.stack.replace(/^/gm, indent(3)));
}
- println(indent(1) + '...');
+ println(indent(1) + "...");
}
};
function indent(level) {
- return Array(level + 1).join(' ');
+ return Array(level + 1).join(" ");
}
}
@@ -295,4 +295,4 @@ function TAP13Producer() {
*/
inherits(TAP13Producer, TAPProducer);
-TAP.description = 'TAP-compatible output';
+TAP.description = "TAP-compatible output";
diff --git a/lib/reporters/xunit.js b/lib/reporters/xunit.js
index 77b71366..0eb48fb6 100644
--- a/lib/reporters/xunit.js
+++ b/lib/reporters/xunit.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('../runner.js')} Runner
@@ -12,18 +12,18 @@
* Module dependencies.
*/
-var Base = require('./base');
-var utils = require('../utils');
-var fs = require('node:fs');
-var path = require('node:path');
-var errors = require('../errors');
+var Base = require("./base");
+var utils = require("../utils");
+var fs = require("node:fs");
+var path = require("node:path");
+var errors = require("../errors");
var createUnsupportedError = errors.createUnsupportedError;
-var constants = require('../runner').constants;
+var constants = require("../runner").constants;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
var EVENT_RUN_END = constants.EVENT_RUN_END;
var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;
-var STATE_FAILED = require('../runnable').constants.STATE_FAILED;
+var STATE_FAILED = require("../runnable").constants.STATE_FAILED;
var inherits = utils.inherits;
var escape = utils.escape;
@@ -59,16 +59,16 @@ function XUnit(runner, options) {
var suiteName;
// the default name of the test suite if none is provided
- var DEFAULT_SUITE_NAME = 'Mocha Tests';
+ var DEFAULT_SUITE_NAME = "Mocha Tests";
if (options && options.reporterOptions) {
if (options.reporterOptions.output) {
if (!fs.createWriteStream) {
- throw createUnsupportedError('file output not supported in browser');
+ throw createUnsupportedError("file output not supported in browser");
}
fs.mkdirSync(path.dirname(options.reporterOptions.output), {
- recursive: true
+ recursive: true,
});
self.fileStream = fs.createWriteStream(options.reporterOptions.output);
}
@@ -95,7 +95,7 @@ function XUnit(runner, options) {
runner.once(EVENT_RUN_END, function () {
self.write(
tag(
- 'testsuite',
+ "testsuite",
{
name: suiteName,
tests: stats.tests,
@@ -103,17 +103,17 @@ function XUnit(runner, options) {
errors: stats.failures,
skipped: stats.tests - stats.failures - stats.passes,
timestamp: new Date().toUTCString(),
- time: stats.duration / 1000 || 0
+ time: stats.duration / 1000 || 0,
},
- false
- )
+ false,
+ ),
);
tests.forEach(function (t) {
self.test(t, options);
});
- self.write('</testsuite>');
+ self.write("</testsuite>");
});
}
@@ -145,9 +145,9 @@ XUnit.prototype.done = function (failures, fn) {
*/
XUnit.prototype.write = function (line) {
if (this.fileStream) {
- this.fileStream.write(line + '\n');
- } else if (typeof process === 'object' && process.stdout) {
- process.stdout.write(line + '\n');
+ this.fileStream.write(line + "\n");
+ } else if (typeof process === "object" && process.stdout) {
+ process.stdout.write(line + "\n");
} else {
Base.consoleLog(line);
}
@@ -165,32 +165,32 @@ XUnit.prototype.test = function (test, options) {
classname: test.parent.fullTitle(),
name: test.title,
file: testFilePath(test.file, options),
- time: test.duration / 1000 || 0
+ time: test.duration / 1000 || 0,
};
if (test.state === STATE_FAILED) {
var err = test.err;
var diff =
!Base.hideDiff && Base.showDiff(err)
- ? '\n' + Base.generateDiff(err.actual, err.expected)
- : '';
+ ? "\n" + Base.generateDiff(err.actual, err.expected)
+ : "";
this.write(
tag(
- 'testcase',
+ "testcase",
attrs,
false,
tag(
- 'failure',
+ "failure",
{},
false,
- escape(err.message) + escape(diff) + '\n' + escape(err.stack)
- )
- )
+ escape(err.message) + escape(diff) + "\n" + escape(err.stack),
+ ),
+ ),
);
} else if (test.isPending()) {
- this.write(tag('testcase', attrs, false, tag('skipped', {}, true)));
+ this.write(tag("testcase", attrs, false, tag("skipped", {}, true)));
} else {
- this.write(tag('testcase', attrs, true));
+ this.write(tag("testcase", attrs, true));
}
};
@@ -204,7 +204,7 @@ XUnit.prototype.test = function (test, options) {
* @return {string}
*/
function tag(name, attrs, close, content) {
- var end = close ? '/>' : '>';
+ var end = close ? "/>" : ">";
var pairs = [];
var tag;
@@ -214,19 +214,23 @@ function tag(name, attrs, close, content) {
}
}
- tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end;
+ tag = "<" + name + (pairs.length ? " " + pairs.join(" ") : "") + end;
if (content) {
- tag += content + '</' + name + end;
+ tag += content + "</" + name + end;
}
return tag;
}
function testFilePath(filepath, options) {
- if (options && options.reporterOptions && options.reporterOptions.showRelativePaths) {
+ if (
+ options &&
+ options.reporterOptions &&
+ options.reporterOptions.showRelativePaths
+ ) {
return path.relative(process.cwd(), filepath);
}
return filepath;
}
-XUnit.description = 'XUnit-compatible XML output';
+XUnit.description = "XUnit-compatible XML output";
diff --git a/lib/runnable.js b/lib/runnable.js
index d1d9e5f6..97097dda 100644
--- a/lib/runnable.js
+++ b/lib/runnable.js
@@ -1,15 +1,15 @@
-'use strict';
+"use strict";
-var EventEmitter = require('node:events').EventEmitter;
-var Pending = require('./pending');
-var debug = require('debug')('mocha:runnable');
-var milliseconds = require('ms');
-var utils = require('./utils');
+var EventEmitter = require("node:events").EventEmitter;
+var Pending = require("./pending");
+var debug = require("debug")("mocha:runnable");
+var milliseconds = require("ms");
+var utils = require("./utils");
const {
createInvalidExceptionError,
createMultipleDoneError,
- createTimeoutError
-} = require('./errors');
+ createTimeoutError,
+} = require("./errors");
/**
* Save timer references to avoid Sinon interfering (see GH-237).
@@ -38,17 +38,17 @@ module.exports = Runnable;
function Runnable(title, fn) {
this.title = title;
this.fn = fn;
- this.body = (fn || '').toString();
+ this.body = (fn || "").toString();
this.async = fn && fn.length;
this.sync = !this.async;
this._timeout = 2000;
this._slow = 75;
this._retries = -1;
utils.assignNewMochaID(this);
- Object.defineProperty(this, 'id', {
+ Object.defineProperty(this, "id", {
get() {
return utils.getMochaID(this);
- }
+ },
});
this.reset();
}
@@ -94,7 +94,7 @@ Runnable.prototype.timeout = function (ms) {
if (!arguments.length) {
return this._timeout;
}
- if (typeof ms === 'string') {
+ if (typeof ms === "string") {
ms = milliseconds(ms);
}
@@ -108,7 +108,7 @@ Runnable.prototype.timeout = function (ms) {
} else {
this._timeout = ms;
}
- debug('timeout %d', this._timeout);
+ debug("timeout %d", this._timeout);
if (this.timer) {
this.resetTimeout();
@@ -124,13 +124,13 @@ Runnable.prototype.timeout = function (ms) {
* @return {Runnable|number} ms or Runnable instance.
*/
Runnable.prototype.slow = function (ms) {
- if (!arguments.length || typeof ms === 'undefined') {
+ if (!arguments.length || typeof ms === "undefined") {
return this._slow;
}
- if (typeof ms === 'string') {
+ if (typeof ms === "string") {
ms = milliseconds(ms);
}
- debug('slow %d', ms);
+ debug("slow %d", ms);
this._slow = ms;
return this;
};
@@ -143,7 +143,7 @@ Runnable.prototype.slow = function (ms) {
*/
Runnable.prototype.skip = function () {
this.pending = true;
- throw new Pending('sync skip; aborting execution');
+ throw new Pending("sync skip; aborting execution");
};
/**
@@ -206,7 +206,7 @@ Runnable.prototype.currentRetry = function (n) {
* @return {string}
*/
Runnable.prototype.fullTitle = function () {
- return this.titlePath().join(' ');
+ return this.titlePath().join(" ");
};
/**
@@ -287,7 +287,7 @@ Runnable.prototype.run = function (fn) {
return;
}
errorWasHandled = true;
- self.emit('error', createMultipleDoneError(self, err));
+ self.emit("error", createMultipleDoneError(self, err));
}
// finished
@@ -313,11 +313,11 @@ Runnable.prototype.run = function (fn) {
// for .resetTimeout() and Runner#uncaught()
this.callback = done;
- if (this.fn && typeof this.fn.call !== 'function') {
+ if (this.fn && typeof this.fn.call !== "function") {
done(
new TypeError(
- 'A runnable must be passed a function as its second argument.'
- )
+ "A runnable must be passed a function as its second argument.",
+ ),
);
return;
}
@@ -331,7 +331,7 @@ Runnable.prototype.run = function (fn) {
this.pending = true;
done();
// halt execution, the uncaught handler will ignore the failure.
- throw new Pending('async skip; aborting execution');
+ throw new Pending("async skip; aborting execution");
};
try {
@@ -364,7 +364,7 @@ Runnable.prototype.run = function (fn) {
function callFn(fn) {
var result = fn.call(ctx);
- if (result && typeof result.then === 'function') {
+ if (result && typeof result.then === "function") {
self.resetTimeout();
result.then(
function () {
@@ -374,15 +374,15 @@ Runnable.prototype.run = function (fn) {
return null;
},
function (reason) {
- done(reason || new Error('Promise rejected with no or falsy reason'));
- }
+ done(reason || new Error("Promise rejected with no or falsy reason"));
+ },
);
} else {
if (self.asyncOnly) {
return done(
new Error(
- '--async-only option in use without declaring `done()` or returning a promise'
- )
+ "--async-only option in use without declaring `done()` or returning a promise",
+ ),
);
}
@@ -392,22 +392,22 @@ Runnable.prototype.run = function (fn) {
function callFnAsync(fn) {
var result = fn.call(ctx, function (err) {
- if (err instanceof Error || toString.call(err) === '[object Error]') {
+ if (err instanceof Error || toString.call(err) === "[object Error]") {
return done(err);
}
if (err) {
- if (Object.prototype.toString.call(err) === '[object Object]') {
+ if (Object.prototype.toString.call(err) === "[object Object]") {
return done(
- new Error('done() invoked with non-Error: ' + JSON.stringify(err))
+ new Error("done() invoked with non-Error: " + JSON.stringify(err)),
);
}
- return done(new Error('done() invoked with non-Error: ' + err));
+ return done(new Error("done() invoked with non-Error: " + err));
}
if (result && utils.isPromise(result)) {
return done(
new Error(
- 'Resolution method is overspecified. Specify a callback *or* return a Promise; not both.'
- )
+ "Resolution method is overspecified. Specify a callback *or* return a Promise; not both.",
+ ),
);
}
@@ -426,7 +426,7 @@ Runnable.prototype.run = function (fn) {
Runnable.prototype._timeoutError = function (ms) {
let msg = `Timeout of ${ms}ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves.`;
if (this.file) {
- msg += ' (' + this.file + ')';
+ msg += " (" + this.file + ")";
}
return createTimeoutError(msg, ms, this.file);
};
@@ -445,16 +445,16 @@ var constants = utils.defineConstants(
/**
* Value of `state` prop when a `Runnable` has failed
*/
- STATE_FAILED: 'failed',
+ STATE_FAILED: "failed",
/**
* Value of `state` prop when a `Runnable` has passed
*/
- STATE_PASSED: 'passed',
+ STATE_PASSED: "passed",
/**
* Value of `state` prop when a `Runnable` has been skipped by user
*/
- STATE_PENDING: 'pending'
- }
+ STATE_PENDING: "pending",
+ },
);
/**
@@ -467,8 +467,8 @@ Runnable.toValueOrError = function (value) {
return (
value ||
createInvalidExceptionError(
- 'Runnable failed with falsy or undefined exception. Please throw an Error instead.',
- value
+ "Runnable failed with falsy or undefined exception. Please throw an Error instead.",
+ value,
)
);
};
diff --git a/lib/runner.js b/lib/runner.js
index 555e919b..ebce7523 100644
--- a/lib/runner.js
+++ b/lib/runner.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('./types.d.ts').RunnerOptions} RunnerOptions
@@ -8,12 +8,12 @@
* Module dependencies.
* @private
*/
-var EventEmitter = require('node:events').EventEmitter;
-var Pending = require('./pending');
-var utils = require('./utils');
-var debug = require('debug')('mocha:runner');
-var Runnable = require('./runnable');
-var Suite = require('./suite');
+var EventEmitter = require("node:events").EventEmitter;
+var Pending = require("./pending");
+var utils = require("./utils");
+var debug = require("debug")("mocha:runner");
+var Runnable = require("./runnable");
+var Suite = require("./suite");
var HOOK_TYPE_BEFORE_EACH = Suite.constants.HOOK_TYPE_BEFORE_EACH;
var HOOK_TYPE_AFTER_EACH = Suite.constants.HOOK_TYPE_AFTER_EACH;
var HOOK_TYPE_AFTER_ALL = Suite.constants.HOOK_TYPE_AFTER_ALL;
@@ -30,8 +30,8 @@ const {
createUnsupportedError,
createFatalError,
isMochaError,
-} = require('./errors');
-const { constants: errorConstants } = require('./error-constants');
+} = require("./errors");
+const { constants: errorConstants } = require("./error-constants");
/**
* Non-enumerable globals.
@@ -39,14 +39,14 @@ const { constants: errorConstants } = require('./error-constants');
* @readonly
*/
var globals = [
- 'setTimeout',
- 'clearTimeout',
- 'setInterval',
- 'clearInterval',
- 'XMLHttpRequest',
- 'Date',
- 'setImmediate',
- 'clearImmediate'
+ "setTimeout",
+ "clearTimeout",
+ "setInterval",
+ "clearInterval",
+ "XMLHttpRequest",
+ "Date",
+ "setImmediate",
+ "clearImmediate",
];
var constants = utils.defineConstants(
@@ -95,43 +95,43 @@ var constants = utils.defineConstants(
/**
* Emitted when {@link Hook} execution begins
*/
- EVENT_HOOK_BEGIN: 'hook',
+ EVENT_HOOK_BEGIN: "hook",
/**
* Emitted when {@link Hook} execution ends
*/
- EVENT_HOOK_END: 'hook end',
+ EVENT_HOOK_END: "hook end",
/**
* Emitted when Root {@link Suite} execution begins (all files have been parsed and hooks/tests are ready for execution)
*/
- EVENT_RUN_BEGIN: 'start',
+ EVENT_RUN_BEGIN: "start",
/**
* Emitted when Root {@link Suite} execution has been delayed via `delay` option
*/
- EVENT_DELAY_BEGIN: 'waiting',
+ EVENT_DELAY_BEGIN: "waiting",
/**
* Emitted when delayed Root {@link Suite} execution is triggered by user via `global.run()`
*/
- EVENT_DELAY_END: 'ready',
+ EVENT_DELAY_END: "ready",
/**
* Emitted when Root {@link Suite} execution ends
*/
- EVENT_RUN_END: 'end',
+ EVENT_RUN_END: "end",
/**
* Emitted when {@link Suite} execution begins
*/
- EVENT_SUITE_BEGIN: 'suite',
+ EVENT_SUITE_BEGIN: "suite",
/**
* Emitted when {@link Suite} execution ends
*/
- EVENT_SUITE_END: 'suite end',
+ EVENT_SUITE_END: "suite end",
/**
* Emitted when {@link Test} execution begins
*/
- EVENT_TEST_BEGIN: 'test',
+ EVENT_TEST_BEGIN: "test",
/**
* Emitted when {@link Test} execution ends
*/
- EVENT_TEST_END: 'test end',
+ EVENT_TEST_END: "test end",
/**
* Emitted when {@link Test} execution fails. Includes an `err` object of type `Error`.
* @example
@@ -141,32 +141,32 @@ var constants = utils.defineConstants(
*
*
*/
- EVENT_TEST_FAIL: 'fail',
+ EVENT_TEST_FAIL: "fail",
/**
* Emitted when {@link Test} execution succeeds
*/
- EVENT_TEST_PASS: 'pass',
+ EVENT_TEST_PASS: "pass",
/**
* Emitted when {@link Test} becomes pending
*/
- EVENT_TEST_PENDING: 'pending',
+ EVENT_TEST_PENDING: "pending",
/**
* Emitted when {@link Test} execution has failed, but will retry
*/
- EVENT_TEST_RETRY: 'retry',
+ EVENT_TEST_RETRY: "retry",
/**
* Initial state of Runner
*/
- STATE_IDLE: 'idle',
+ STATE_IDLE: "idle",
/**
* State set to this value when the Runner has started running
*/
- STATE_RUNNING: 'running',
+ STATE_RUNNING: "running",
/**
* State set to this value when the Runner has stopped
*/
- STATE_STOPPED: 'stopped'
- }
+ STATE_STOPPED: "stopped",
+ },
);
class Runner extends EventEmitter {
@@ -199,7 +199,7 @@ class Runner extends EventEmitter {
*/
this._eventListeners = new Map();
this.on(constants.EVENT_TEST_END, function (test) {
- if (test.type === 'test' && test.retriedTest() && test.parent) {
+ if (test.type === "test" && test.retriedTest() && test.parent) {
var idx =
test.parent.tests && test.parent.tests.indexOf(test.retriedTest());
if (idx > -1) test.parent.tests[idx] = test;
@@ -217,23 +217,23 @@ class Runner extends EventEmitter {
this.unhandled = (reason, promise) => {
if (isMochaError(reason)) {
debug(
- 'trapped unhandled rejection coming out of Mocha; forwarding to uncaught handler:',
- reason
+ "trapped unhandled rejection coming out of Mocha; forwarding to uncaught handler:",
+ reason,
);
this.uncaught(reason);
} else {
debug(
- 'trapped unhandled rejection from (probably) user code; re-emitting on process'
+ "trapped unhandled rejection from (probably) user code; re-emitting on process",
);
this._removeEventListener(
process,
- 'unhandledRejection',
- this.unhandled
+ "unhandledRejection",
+ this.unhandled,
);
try {
- process.emit('unhandledRejection', reason, promise);
+ process.emit("unhandledRejection", reason, promise);
} finally {
- this._addEventListener(process, 'unhandledRejection', this.unhandled);
+ this._addEventListener(process, "unhandledRejection", this.unhandled);
}
}
};
@@ -257,9 +257,9 @@ Runner.immediately = global.setImmediate || process.nextTick;
*/
Runner.prototype._addEventListener = function (target, eventName, listener) {
debug(
- '_addEventListener(): adding for event %s; %d current listeners',
+ "_addEventListener(): adding for event %s; %d current listeners",
eventName,
- target.listenerCount(eventName)
+ target.listenerCount(eventName),
);
/* istanbul ignore next */
if (
@@ -268,8 +268,8 @@ Runner.prototype._addEventListener = function (target, eventName, listener) {
this._eventListeners.get(target).get(eventName).has(listener)
) {
debug(
- 'warning: tried to attach duplicate event listener for %s',
- eventName
+ "warning: tried to attach duplicate event listener for %s",
+ eventName,
);
return;
}
@@ -308,7 +308,7 @@ Runner.prototype._removeEventListener = function (target, eventName, listener) {
this._eventListeners.delete(target);
}
} else {
- debug('trying to remove listener for untracked object %s', target);
+ debug("trying to remove listener for untracked object %s", target);
}
};
@@ -320,7 +320,7 @@ Runner.prototype.dispose = function () {
this.removeAllListeners();
this._eventListeners.forEach((targetListeners, target) => {
targetListeners.forEach((targetEventListeners, eventName) => {
- targetEventListeners.forEach(listener => {
+ targetEventListeners.forEach((listener) => {
target.removeListener(eventName, listener);
});
});
@@ -339,7 +339,7 @@ Runner.prototype.dispose = function () {
* @return {Runner} Runner instance.
*/
Runner.prototype.grep = function (re, invert) {
- debug('grep(): setting to %s', re);
+ debug("grep(): setting to %s", re);
this._grep = re;
this._invert = invert;
this.total = this.grepTotal(this.suite);
@@ -404,7 +404,7 @@ Runner.prototype.globals = function (arr) {
if (!arguments.length) {
return this._globals;
}
- debug('globals(): setting to %O', arr);
+ debug("globals(): setting to %O", arr);
this._globals = this._globals.concat(arr);
return this;
};
@@ -436,7 +436,7 @@ Runner.prototype.checkGlobals = function (test) {
this._globals = this._globals.concat(leaks);
if (leaks.length) {
- var msg = `global leak(s) detected: ${leaks.map(e => `'${e}'`).join(', ')}`;
+ var msg = `global leak(s) detected: ${leaks.map((e) => `'${e}'`).join(", ")}`;
this.fail(test, new Error(msg));
}
};
@@ -472,13 +472,13 @@ Runner.prototype.fail = function (test, err, force) {
throw err;
}
throw createFatalError(
- 'Test failed after root suite execution completed!',
- err
+ "Test failed after root suite execution completed!",
+ err,
);
}
++this.failures;
- debug('total number of failures: %d', this.failures);
+ debug("total number of failures: %d", this.failures);
test.state = STATE_FAILED;
if (!isError(err)) {
@@ -542,8 +542,8 @@ Runner.prototype.hook = function (name, fn) {
self.emit(constants.EVENT_HOOK_BEGIN, hook);
- if (!hook.listeners('error').length) {
- self._addEventListener(hook, 'error', function (err) {
+ if (!hook.listeners("error").length) {
+ self._addEventListener(hook, "error", function (err) {
self.fail(hook, err);
});
}
@@ -566,7 +566,7 @@ Runner.prototype.hook = function (name, fn) {
}
self.emit(constants.EVENT_HOOK_END, hook);
hook.pending = false; // activates hook for next test
- return fn(new Error('abort hookDown'));
+ return fn(new Error("abort hookDown"));
} else if (name === HOOK_TYPE_BEFORE_ALL) {
suite.tests.forEach(function (test) {
test.pending = true;
@@ -577,7 +577,7 @@ Runner.prototype.hook = function (name, fn) {
hooks = [];
} else {
hook.pending = false;
- var errForbid = createUnsupportedError('`this.skip` forbidden');
+ var errForbid = createUnsupportedError("`this.skip` forbidden");
self.fail(hook, errForbid);
return fn(errForbid);
}
@@ -601,7 +601,7 @@ Runner.prototype.hook = function (name, fn) {
if (hook.parent.title) {
parentTitle = hook.parent.title;
} else {
- parentTitle = hook.parent.root ? '{root}' : '';
+ parentTitle = hook.parent.root ? "{root}" : "";
}
hook.title = `${hook.originalTitle} in "${parentTitle}"`;
}
@@ -708,7 +708,7 @@ Runner.prototype.runTest = function (fn) {
if (this.asyncOnly) {
test.asyncOnly = true;
}
- this._addEventListener(test, 'error', function (err) {
+ this._addEventListener(test, "error", function (err) {
self.fail(test, err);
});
if (this.allowUncaught) {
@@ -806,7 +806,7 @@ Runner.prototype.runTests = function (suite, fn) {
// static skip, no hooks are executed
if (test.isPending()) {
if (self.forbidPending) {
- self.fail(test, new Error('Pending test forbidden'), true);
+ self.fail(test, new Error("Pending test forbidden"), true);
} else {
test.state = STATE_PENDING;
self.emit(constants.EVENT_TEST_PENDING, test);
@@ -821,7 +821,7 @@ Runner.prototype.runTests = function (suite, fn) {
// conditional skip within beforeEach
if (test.isPending()) {
if (self.forbidPending) {
- self.fail(test, new Error('Pending test forbidden'), true);
+ self.fail(test, new Error("Pending test forbidden"), true);
} else {
test.state = STATE_PENDING;
self.emit(constants.EVENT_TEST_PENDING, test);
@@ -844,7 +844,7 @@ Runner.prototype.runTests = function (suite, fn) {
// conditional skip within it
if (test.pending) {
if (self.forbidPending) {
- self.fail(test, new Error('Pending test forbidden'), true);
+ self.fail(test, new Error("Pending test forbidden"), true);
} else {
test.state = STATE_PENDING;
self.emit(constants.EVENT_TEST_PENDING, test);
@@ -895,10 +895,10 @@ Runner.prototype.runSuite = function (suite, fn) {
var self = this;
var total = this.grepTotal(suite);
- debug('runSuite(): running %s', suite.fullTitle());
+ debug("runSuite(): running %s", suite.fullTitle());
if (!total || (self.failures && suite._bail)) {
- debug('runSuite(): bailing');
+ debug("runSuite(): bailing");
return fn();
}
@@ -984,32 +984,32 @@ Runner.prototype._uncaught = function (err) {
// of `Runner`.
if (!(this instanceof Runner)) {
throw createFatalError(
- 'Runner#uncaught() called with invalid context',
- this
+ "Runner#uncaught() called with invalid context",
+ this,
);
}
if (err instanceof Pending) {
- debug('uncaught(): caught a Pending');
+ debug("uncaught(): caught a Pending");
return;
}
// browser does not exit script when throwing in global.onerror()
if (this.allowUncaught && !utils.isBrowser()) {
- debug('uncaught(): bubbling exception due to --allow-uncaught');
+ debug("uncaught(): bubbling exception due to --allow-uncaught");
throw err;
}
if (this.state === constants.STATE_STOPPED) {
- debug('uncaught(): throwing after run has completed!');
+ debug("uncaught(): throwing after run has completed!");
throw err;
}
if (err) {
- debug('uncaught(): got truthy exception %O', err);
+ debug("uncaught(): got truthy exception %O", err);
} else {
- debug('uncaught(): undefined/falsy exception');
+ debug("uncaught(): undefined/falsy exception");
err = createInvalidExceptionError(
- 'Caught falsy/undefined exception which would otherwise be uncaught. No stack trace found; try a debugger',
- err
+ "Caught falsy/undefined exception which would otherwise be uncaught. No stack trace found; try a debugger",
+ err,
);
}
@@ -1022,16 +1022,16 @@ Runner.prototype._uncaught = function (err) {
var runnable = this.currentRunnable;
if (!runnable) {
- runnable = new Runnable('Uncaught error outside test suite');
- debug('uncaught(): no current Runnable; created a phony one');
+ runnable = new Runnable("Uncaught error outside test suite");
+ debug("uncaught(): no current Runnable; created a phony one");
runnable.parent = this.suite;
if (this.state === constants.STATE_RUNNING) {
- debug('uncaught(): failing gracefully');
+ debug("uncaught(): failing gracefully");
this.fail(runnable, err);
} else {
// Can't recover from this failure
- debug('uncaught(): test run has not yet started; unrecoverable');
+ debug("uncaught(): test run has not yet started; unrecoverable");
this.emit(constants.EVENT_RUN_BEGIN);
this.fail(runnable, err);
this.emit(constants.EVENT_RUN_END);
@@ -1043,11 +1043,11 @@ Runner.prototype._uncaught = function (err) {
runnable.clearTimeout();
if (runnable.isFailed()) {
- debug('uncaught(): Runnable has already failed');
+ debug("uncaught(): Runnable has already failed");
// Ignore error if already failed
return;
} else if (runnable.isPending()) {
- debug('uncaught(): pending Runnable wound up failing!');
+ debug("uncaught(): pending Runnable wound up failing!");
// report 'pending test' retrospectively as failed
this.fail(runnable, err, true);
return;
@@ -1056,11 +1056,11 @@ Runner.prototype._uncaught = function (err) {
// we cannot recover gracefully if a Runnable has already passed
// then fails asynchronously
if (runnable.isPassed()) {
- debug('uncaught(): Runnable has already passed; bailing gracefully');
+ debug("uncaught(): Runnable has already passed; bailing gracefully");
this.fail(runnable, err);
this.abort();
} else {
- debug('uncaught(): forcing Runnable to complete with Error');
+ debug("uncaught(): forcing Runnable to complete with Error");
return runnable.callback(err);
}
};
@@ -1079,30 +1079,30 @@ Runner.prototype.run = function (fn, opts = {}) {
var rootSuite = this.suite;
var options = opts.options || {};
- debug('run(): got options: %O', options);
+ debug("run(): got options: %O", options);
fn = fn || function () {};
const end = () => {
if (!this.total && this._opts.failZero) this.failures = 1;
- debug('run(): root suite completed; emitting %s', constants.EVENT_RUN_END);
+ debug("run(): root suite completed; emitting %s", constants.EVENT_RUN_END);
this.emit(constants.EVENT_RUN_END);
};
const begin = () => {
- debug('run(): emitting %s', constants.EVENT_RUN_BEGIN);
+ debug("run(): emitting %s", constants.EVENT_RUN_BEGIN);
this.emit(constants.EVENT_RUN_BEGIN);
- debug('run(): emitted %s', constants.EVENT_RUN_BEGIN);
+ debug("run(): emitted %s", constants.EVENT_RUN_BEGIN);
this.runSuite(rootSuite, end);
};
const prepare = () => {
- debug('run(): starting');
+ debug("run(): starting");
// If there is an `only` filter
if (rootSuite.hasOnly()) {
rootSuite.filterOnly();
- debug('run(): filtered exclusive Runnables');
+ debug("run(): filtered exclusive Runnables");
}
this.state = constants.STATE_RUNNING;
if (this._opts.delay) {
@@ -1115,7 +1115,7 @@ Runner.prototype.run = function (fn, opts = {}) {
// references cleanup to avoid memory leaks
if (this._opts.cleanReferencesAfterRun) {
- this.on(constants.EVENT_SUITE_END, suite => {
+ this.on(constants.EVENT_SUITE_END, (suite) => {
suite.cleanReferences();
});
}
@@ -1123,21 +1123,21 @@ Runner.prototype.run = function (fn, opts = {}) {
// callback
this.on(constants.EVENT_RUN_END, function () {
this.state = constants.STATE_STOPPED;
- debug('run(): emitted %s', constants.EVENT_RUN_END);
+ debug("run(): emitted %s", constants.EVENT_RUN_END);
fn(this.failures);
});
- this._removeEventListener(process, 'uncaughtException', this.uncaught);
- this._removeEventListener(process, 'unhandledRejection', this.unhandled);
- this._addEventListener(process, 'uncaughtException', this.uncaught);
- this._addEventListener(process, 'unhandledRejection', this.unhandled);
+ this._removeEventListener(process, "uncaughtException", this.uncaught);
+ this._removeEventListener(process, "unhandledRejection", this.unhandled);
+ this._addEventListener(process, "uncaughtException", this.uncaught);
+ this._addEventListener(process, "unhandledRejection", this.unhandled);
if (this._opts.delay) {
// for reporters, I guess.
// might be nice to debounce some dots while we wait.
this.emit(constants.EVENT_DELAY_BEGIN, rootSuite);
rootSuite.once(EVENT_ROOT_SUITE_RUN, prepare);
- debug('run(): waiting for green light due to --delay');
+ debug("run(): waiting for green light due to --delay");
} else {
Runner.immediately(prepare);
}
@@ -1181,7 +1181,7 @@ Runner.prototype.linkPartialObjects = function () {
* @returns {Promise<number>} Failure count
*/
Runner.prototype.runAsync = async function runAsync(opts = {}) {
- return new Promise(resolve => {
+ return new Promise((resolve) => {
this.run(resolve, opts);
});
};
@@ -1194,7 +1194,7 @@ Runner.prototype.runAsync = async function runAsync(opts = {}) {
* @return {Runner} Runner instance.
*/
Runner.prototype.abort = function () {
- debug('abort(): aborting');
+ debug("abort(): aborting");
this._abort = true;
return this;
@@ -1222,7 +1222,7 @@ Runner.prototype.isParallelMode = function isParallelMode() {
* @abstract
*/
Runner.prototype.workerReporter = function () {
- throw createUnsupportedError('workerReporter() not supported in serial mode');
+ throw createUnsupportedError("workerReporter() not supported in serial mode");
};
/**
@@ -1259,12 +1259,12 @@ function filterLeaks(ok, globals) {
}
var matched = ok.filter(function (ok) {
- if (~ok.indexOf('*')) {
- return key.indexOf(ok.split('*')[0]) === 0;
+ if (~ok.indexOf("*")) {
+ return key.indexOf(ok.split("*")[0]) === 0;
}
return key === ok;
});
- return !matched.length && (!global.navigator || key !== 'onerror');
+ return !matched.length && (!global.navigator || key !== "onerror");
});
}
@@ -1277,7 +1277,7 @@ function filterLeaks(ok, globals) {
* @returns {boolean}
*/
function isError(err) {
- return err instanceof Error || (err && typeof err.message === 'string');
+ return err instanceof Error || (err && typeof err.message === "string");
}
/**
@@ -1291,8 +1291,8 @@ function isError(err) {
function thrown2Error(err) {
return new Error(
`the ${utils.canonicalType(err)} ${stringify(
- err
- )} was thrown, throw an Error :)`
+ err,
+ )} was thrown, throw an Error :)`,
);
}
diff --git a/lib/stats-collector.js b/lib/stats-collector.js
index 9eca0c00..eb3a3339 100644
--- a/lib/stats-collector.js
+++ b/lib/stats-collector.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('./types.d.ts').StatsCollector} StatsCollector
@@ -10,7 +10,7 @@
* @module
*/
-var constants = require('./runner').constants;
+var constants = require("./runner").constants;
var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;
@@ -37,11 +37,11 @@ function createStatsCollector(runner) {
tests: 0,
passes: 0,
pending: 0,
- failures: 0
+ failures: 0,
};
if (!runner) {
- throw new TypeError('Missing runner argument');
+ throw new TypeError("Missing runner argument");
}
runner.stats = stats;
diff --git a/lib/suite.js b/lib/suite.js
index b321349f..20e1a93e 100644
--- a/lib/suite.js
+++ b/lib/suite.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* @typedef {import('./test.js')} Test
@@ -8,8 +8,8 @@
* Module dependencies.
* @private
*/
-const {EventEmitter} = require('node:events');
-const Hook = require('./hook');
+const { EventEmitter } = require("node:events");
+const Hook = require("./hook");
var {
assignNewMochaID,
clamp,
@@ -17,13 +17,13 @@ var {
defineConstants,
getMochaID,
inherits,
- isString
-} = require('./utils');
-const debug = require('debug')('mocha:suite');
-const milliseconds = require('ms');
-const errors = require('./errors');
+ isString,
+} = require("./utils");
+const debug = require("debug")("mocha:suite");
+const milliseconds = require("ms");
+const errors = require("./errors");
-const {MOCHA_ID_PROP_NAME} = utilsConstants;
+const { MOCHA_ID_PROP_NAME } = utilsConstants;
/**
* Expose `Suite`.
@@ -64,8 +64,8 @@ function Suite(title, parentContext, isRoot) {
'Suite argument "title" must be a string. Received type "' +
typeof title +
'"',
- 'title',
- 'string'
+ "title",
+ "string",
);
}
this.title = title;
@@ -88,10 +88,10 @@ function Suite(title, parentContext, isRoot) {
this._onlySuites = [];
assignNewMochaID(this);
- Object.defineProperty(this, 'id', {
+ Object.defineProperty(this, "id", {
get() {
return getMochaID(this);
- }
+ },
});
this.reset();
@@ -126,7 +126,7 @@ Suite.prototype.reset = function () {
*/
Suite.prototype.clone = function () {
var suite = new Suite(this.title);
- debug('clone');
+ debug("clone");
suite.ctx = this.ctx;
suite.root = this.root;
suite.timeout(this.timeout());
@@ -148,7 +148,7 @@ Suite.prototype.timeout = function (ms) {
if (!arguments.length) {
return this._timeout;
}
- if (typeof ms === 'string') {
+ if (typeof ms === "string") {
ms = milliseconds(ms);
}
@@ -157,7 +157,7 @@ Suite.prototype.timeout = function (ms) {
var range = [0, INT_MAX];
ms = clamp(ms, range);
- debug('timeout %d', ms);
+ debug("timeout %d", ms);
this._timeout = parseInt(ms, 10);
return this;
};
@@ -173,7 +173,7 @@ Suite.prototype.retries = function (n) {
if (!arguments.length) {
return this._retries;
}
- debug('retries %d', n);
+ debug("retries %d", n);
this._retries = parseInt(n, 10) || 0;
return this;
};
@@ -189,10 +189,10 @@ Suite.prototype.slow = function (ms) {
if (!arguments.length) {
return this._slow;
}
- if (typeof ms === 'string') {
+ if (typeof ms === "string") {
ms = milliseconds(ms);
}
- debug('slow %d', ms);
+ debug("slow %d", ms);
this._slow = ms;
return this;
};
@@ -208,7 +208,7 @@ Suite.prototype.bail = function (bail) {
if (!arguments.length) {
return this._bail;
}
- debug('bail %s', bail);
+ debug("bail %s", bail);
this._bail = bail;
return this;
};
@@ -252,11 +252,11 @@ Suite.prototype.beforeAll = function (title, fn) {
if (this.isPending()) {
return this;
}
- if (typeof title === 'function') {
+ if (typeof title === "function") {
fn = title;
title = fn.name;
}
- title = '"before all" hook' + (title ? ': ' + title : '');
+ title = '"before all" hook' + (title ? ": " + title : "");
var hook = this._createHook(title, fn);
this._beforeAll.push(hook);
@@ -276,11 +276,11 @@ Suite.prototype.afterAll = function (title, fn) {
if (this.isPending()) {
return this;
}
- if (typeof title === 'function') {
+ if (typeof title === "function") {
fn = title;
title = fn.name;
}
- title = '"after all" hook' + (title ? ': ' + title : '');
+ title = '"after all" hook' + (title ? ": " + title : "");
var hook = this._createHook(title, fn);
this._afterAll.push(hook);
@@ -300,11 +300,11 @@ Suite.prototype.beforeEach = function (title, fn) {
if (this.isPending()) {
return this;
}
- if (typeof title === 'function') {
+ if (typeof title === "function") {
fn = title;
title = fn.name;
}
- title = '"before each" hook' + (title ? ': ' + title : '');
+ title = '"before each" hook' + (title ? ": " + title : "");
var hook = this._createHook(title, fn);
this._beforeEach.push(hook);
@@ -324,11 +324,11 @@ Suite.prototype.afterEach = function (title, fn) {
if (this.isPending()) {
return this;
}
- if (typeof title === 'function') {
+ if (typeof title === "function") {
fn = title;
title = fn.name;
}
- title = '"after each" hook' + (title ? ': ' + title : '');
+ title = '"after each" hook' + (title ? ": " + title : "");
var hook = this._createHook(title, fn);
this._afterEach.push(hook);
@@ -382,7 +382,7 @@ Suite.prototype.addTest = function (test) {
* @return {string}
*/
Suite.prototype.fullTitle = function () {
- return this.titlePath().join(' ');
+ return this.titlePath().join(" ");
};
/**
@@ -526,7 +526,7 @@ Suite.prototype.appendOnlyTest = function (test) {
* @private
*/
Suite.prototype.getHooks = function getHooks(name) {
- return this['_' + name];
+ return this["_" + name];
};
/**
@@ -591,7 +591,7 @@ Suite.prototype.serialize = function serialize() {
root: this.root,
title: this.title,
[MOCHA_ID_PROP_NAME]: this.id,
- parent: this.parent ? {[MOCHA_ID_PROP_NAME]: this.parent.id} : null
+ parent: this.parent ? { [MOCHA_ID_PROP_NAME]: this.parent.id } : null,
};
};
@@ -609,62 +609,62 @@ var constants = defineConstants(
/**
* Event emitted after a test file has been loaded. Not emitted in browser.
*/
- EVENT_FILE_POST_REQUIRE: 'post-require',
+ EVENT_FILE_POST_REQUIRE: "post-require",
/**
* Event emitted before a test file has been loaded. In browser, this is emitted once an interface has been selected.
*/
- EVENT_FILE_PRE_REQUIRE: 'pre-require',
+ EVENT_FILE_PRE_REQUIRE: "pre-require",
/**
* Event emitted immediately after a test file has been loaded. Not emitted in browser.
*/
- EVENT_FILE_REQUIRE: 'require',
+ EVENT_FILE_REQUIRE: "require",
/**
* Event emitted when `global.run()` is called (use with `delay` option).
*/
- EVENT_ROOT_SUITE_RUN: 'run',
+ EVENT_ROOT_SUITE_RUN: "run",
/**
* Namespace for collection of a `Suite`'s "after all" hooks.
*/
- HOOK_TYPE_AFTER_ALL: 'afterAll',
+ HOOK_TYPE_AFTER_ALL: "afterAll",
/**
* Namespace for collection of a `Suite`'s "after each" hooks.
*/
- HOOK_TYPE_AFTER_EACH: 'afterEach',
+ HOOK_TYPE_AFTER_EACH: "afterEach",
/**
* Namespace for collection of a `Suite`'s "before all" hooks.
*/
- HOOK_TYPE_BEFORE_ALL: 'beforeAll',
+ HOOK_TYPE_BEFORE_ALL: "beforeAll",
/**
* Namespace for collection of a `Suite`'s "before each" hooks.
*/
- HOOK_TYPE_BEFORE_EACH: 'beforeEach',
+ HOOK_TYPE_BEFORE_EACH: "beforeEach",
/**
* Emitted after a child `Suite` has been added to a `Suite`.
*/
- EVENT_SUITE_ADD_SUITE: 'suite',
+ EVENT_SUITE_ADD_SUITE: "suite",
/**
* Emitted after an "after all" `Hook` has been added to a `Suite`.
*/
- EVENT_SUITE_ADD_HOOK_AFTER_ALL: 'afterAll',
+ EVENT_SUITE_ADD_HOOK_AFTER_ALL: "afterAll",
/**
* Emitted after an "after each" `Hook` has been added to a `Suite`.
*/
- EVENT_SUITE_ADD_HOOK_AFTER_EACH: 'afterEach',
+ EVENT_SUITE_ADD_HOOK_AFTER_EACH: "afterEach",
/**
* Emitted after an "before all" `Hook` has been added to a `Suite`.
*/
- EVENT_SUITE_ADD_HOOK_BEFORE_ALL: 'beforeAll',
+ EVENT_SUITE_ADD_HOOK_BEFORE_ALL: "beforeAll",
/**
* Emitted after an "before each" `Hook` has been added to a `Suite`.
*/
- EVENT_SUITE_ADD_HOOK_BEFORE_EACH: 'beforeEach',
+ EVENT_SUITE_ADD_HOOK_BEFORE_EACH: "beforeEach",
/**
* Emitted after a `Test` has been added to a `Suite`.
*/
- EVENT_SUITE_ADD_TEST: 'test'
- }
+ EVENT_SUITE_ADD_TEST: "test",
+ },
);
Suite.constants = constants;
diff --git a/lib/test.js b/lib/test.js
index 0b8fe18b..8997b48b 100644
--- a/lib/test.js
+++ b/lib/test.js
@@ -1,11 +1,11 @@
-'use strict';
-var Runnable = require('./runnable');
-var utils = require('./utils');
-var errors = require('./errors');
+"use strict";
+var Runnable = require("./runnable");
+var utils = require("./utils");
+var errors = require("./errors");
var createInvalidArgumentTypeError = errors.createInvalidArgumentTypeError;
var isString = utils.isString;
-const {MOCHA_ID_PROP_NAME} = utils.constants;
+const { MOCHA_ID_PROP_NAME } = utils.constants;
module.exports = Test;
@@ -24,11 +24,11 @@ function Test(title, fn) {
'Test argument "title" should be a string. Received type "' +
typeof title +
'"',
- 'title',
- 'string'
+ "title",
+ "string",
);
}
- this.type = 'test';
+ this.type = "test";
Runnable.call(this, title, fn);
this.reset();
}
@@ -101,13 +101,13 @@ Test.prototype.serialize = function serialize() {
err: this.err,
parent: {
$$fullTitle: this.parent.fullTitle(),
- [MOCHA_ID_PROP_NAME]: this.parent.id
+ [MOCHA_ID_PROP_NAME]: this.parent.id,
},
speed: this.speed,
state: this.state,
title: this.title,
type: this.type,
file: this.file,
- [MOCHA_ID_PROP_NAME]: this.id
+ [MOCHA_ID_PROP_NAME]: this.id,
};
};
diff --git a/lib/types.d.ts b/lib/types.d.ts
index 800aa04b..e50bbe3e 100644
--- a/lib/types.d.ts
+++ b/lib/types.d.ts
@@ -4,11 +4,11 @@
* For now, if you're an external user, you should use the types from @types/mocha.
*/
-import type {FSWatcher, MatchFunction} from 'chokidar';
+import type { FSWatcher, MatchFunction } from "chokidar";
-import type {constants} from './error-constants.js';
-import type Mocha from './mocha.js';
-import Runner from './runner.js';
+import type { constants } from "./error-constants.js";
+import type Mocha from "./mocha.js";
+import Runner from "./runner.js";
/**
* Command-line options
@@ -185,7 +185,7 @@ export type PluginValidator = (this: PluginDefinition, value: unknown) => void;
* @param implementations User-supplied implementations
*/
export type PluginFinalizer = (
- implementations: unknown[]
+ implementations: unknown[],
) => Promise<unknown> | unknown;
/**
@@ -374,7 +374,7 @@ export interface SerializedWorkerResult {
events: SerializedEvent[];
/** Symbol-like to denote the type of object this is */
- __type: 'SerializedWorkerResult';
+ __type: "SerializedWorkerResult";
}
/**
diff --git a/lib/utils.js b/lib/utils.js
index 4971b8de..d3a928b8 100644
--- a/lib/utils.js
+++ b/lib/utils.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* Various utility functions used throughout Mocha's codebase.
@@ -8,11 +8,11 @@
/**
* Module dependencies.
*/
-var path = require('node:path');
-var util = require('node:util');
-var he = require('he');
+var path = require("node:path");
+var util = require("node:util");
+var he = require("he");
-const MOCHA_ID_PROP_NAME = '__mocha_id__';
+const MOCHA_ID_PROP_NAME = "__mocha_id__";
/**
* Inherit the prototype methods from one constructor into another.
@@ -33,7 +33,7 @@ exports.inherits = util.inherits;
* @return {string}
*/
exports.escape = function (html) {
- return he.encode(String(html), {useNamedReferences: false});
+ return he.encode(String(html), { useNamedReferences: false });
};
/**
@@ -44,7 +44,7 @@ exports.escape = function (html) {
* @return {boolean}
*/
exports.isString = function (obj) {
- return typeof obj === 'string';
+ return typeof obj === "string";
};
/**
@@ -57,9 +57,9 @@ exports.isString = function (obj) {
exports.slug = function (str) {
return str
.toLowerCase()
- .replace(/\s+/g, '-')
- .replace(/[^-\w]/g, '')
- .replace(/-{2,}/g, '-');
+ .replace(/\s+/g, "-")
+ .replace(/[^-\w]/g, "")
+ .replace(/-{2,}/g, "-");
};
/**
@@ -70,22 +70,22 @@ exports.slug = function (str) {
*/
exports.clean = function (str) {
str = str
- .replace(/\r\n?|[\n\u2028\u2029]/g, '\n')
- .replace(/^\uFEFF/, '')
+ .replace(/\r\n?|[\n\u2028\u2029]/g, "\n")
+ .replace(/^\uFEFF/, "")
// (traditional)-> space/name parameters body (lambda)-> parameters body multi-statement/single keep body content
.replace(
/^function(?:\s*|\s[^(]*)\([^)]*\)\s*\{((?:.|\n)*?)\}$|^\([^)]*\)\s*=>\s*(?:\{((?:.|\n)*?)\}|((?:.|\n)*))$/,
- '$1$2$3'
+ "$1$2$3",
);
var spaces = str.match(/^\n?( *)/)[1].length;
var tabs = str.match(/^\n?(\t*)/)[1].length;
var re = new RegExp(
- '^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs || spaces) + '}',
- 'gm'
+ "^\n?" + (tabs ? "\t" : " ") + "{" + (tabs || spaces) + "}",
+ "gm",
);
- str = str.replace(re, '');
+ str = str.replace(re, "");
return str.trim();
};
@@ -106,12 +106,12 @@ exports.clean = function (str) {
*/
function emptyRepresentation(value, typeHint) {
switch (typeHint) {
- case 'function':
- return '[Function]';
- case 'object':
- return '{}';
- case 'array':
- return '[]';
+ case "function":
+ return "[Function]";
+ case "object":
+ return "{}";
+ case "array":
+ return "[]";
default:
return value.toString();
}
@@ -142,18 +142,18 @@ function emptyRepresentation(value, typeHint) {
*/
var canonicalType = (exports.canonicalType = function canonicalType(value) {
if (value === undefined) {
- return 'undefined';
+ return "undefined";
} else if (value === null) {
- return 'null';
+ return "null";
} else if (Buffer.isBuffer(value)) {
- return 'buffer';
+ return "buffer";
} else if (Object.getPrototypeOf(value) === null) {
- return 'null-prototype';
+ return "null-prototype";
}
return Object.prototype.toString
.call(value)
- .replace(/^\[.+\s(.+?)]$/, '$1')
+ .replace(/^\[.+\s(.+?)]$/, "$1")
.toLowerCase();
});
@@ -179,21 +179,21 @@ var canonicalType = (exports.canonicalType = function canonicalType(value) {
*/
exports.type = function type(value) {
// Null is special
- if (value === null) return 'null';
+ if (value === null) return "null";
const primitives = new Set([
- 'undefined',
- 'boolean',
- 'number',
- 'string',
- 'bigint',
- 'symbol'
+ "undefined",
+ "boolean",
+ "number",
+ "string",
+ "bigint",
+ "symbol",
]);
const _type = typeof value;
- if (_type === 'function') return _type;
+ if (_type === "function") return _type;
if (primitives.has(_type)) return _type;
- if (value instanceof String) return 'string';
- if (value instanceof Error) return 'error';
- if (Array.isArray(value)) return 'array';
+ if (value instanceof String) return "string";
+ if (value instanceof Error) return "error";
+ if (Array.isArray(value)) return "array";
return _type;
};
@@ -216,24 +216,24 @@ exports.type = function type(value) {
exports.stringify = function (value) {
var typeHint = canonicalType(value);
- if (!~['object', 'array', 'function', 'null-prototype'].indexOf(typeHint)) {
- if (typeHint === 'buffer') {
+ if (!~["object", "array", "function", "null-prototype"].indexOf(typeHint)) {
+ if (typeHint === "buffer") {
var json = Buffer.prototype.toJSON.call(value);
// Based on the toJSON result
return jsonStringify(
json.data && json.type ? json.data : json,
- 2
- ).replace(/,(\n|$)/g, '$1');
+ 2,
+ ).replace(/,(\n|$)/g, "$1");
}
// IE7/IE8 has a bizarre String constructor; needs to be coerced
// into an array and back to obj.
- if (typeHint === 'string' && typeof value === 'object') {
- value = value.split('').reduce(function (acc, char, idx) {
+ if (typeHint === "string" && typeof value === "object") {
+ value = value.split("").reduce(function (acc, char, idx) {
acc[idx] = char;
return acc;
}, {});
- typeHint = 'object';
+ typeHint = "object";
} else {
return jsonStringify(value);
}
@@ -243,8 +243,8 @@ exports.stringify = function (value) {
if (Object.prototype.hasOwnProperty.call(value, prop)) {
return jsonStringify(
exports.canonicalize(value, null, typeHint),
- 2
- ).replace(/,(\n|$)/g, '$1');
+ 2,
+ ).replace(/,(\n|$)/g, "$1");
}
}
@@ -261,17 +261,17 @@ exports.stringify = function (value) {
* @returns {*}
*/
function jsonStringify(object, spaces, depth) {
- if (typeof spaces === 'undefined') {
+ if (typeof spaces === "undefined") {
// primitive types
return _stringify(object);
}
depth = depth || 1;
var space = spaces * depth;
- var str = Array.isArray(object) ? '[' : '{';
- var end = Array.isArray(object) ? ']' : '}';
+ var str = Array.isArray(object) ? "[" : "{";
+ var end = Array.isArray(object) ? "]" : "}";
var length =
- typeof object.length === 'number'
+ typeof object.length === "number"
? object.length
: Object.keys(object).length;
// `.repeat()` polyfill
@@ -281,39 +281,39 @@ function jsonStringify(object, spaces, depth) {
function _stringify(val) {
switch (canonicalType(val)) {
- case 'null':
- case 'undefined':
- val = '[' + val + ']';
+ case "null":
+ case "undefined":
+ val = "[" + val + "]";
break;
- case 'array':
- case 'object':
+ case "array":
+ case "object":
val = jsonStringify(val, spaces, depth + 1);
break;
- case 'boolean':
- case 'regexp':
- case 'symbol':
- case 'number':
+ case "boolean":
+ case "regexp":
+ case "symbol":
+ case "number":
val =
val === 0 && 1 / val === -Infinity // `-0`
- ? '-0'
+ ? "-0"
: val.toString();
break;
- case 'bigint':
- val = val.toString() + 'n';
+ case "bigint":
+ val = val.toString() + "n";
break;
- case 'date':
+ case "date":
var sDate = isNaN(val.getTime()) ? val.toString() : val.toISOString();
- val = '[Date: ' + sDate + ']';
+ val = "[Date: " + sDate + "]";
break;
- case 'buffer':
+ case "buffer":
var json = val.toJSON();
// Based on the toJSON result
json = json.data && json.type ? json.data : json;
- val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']';
+ val = "[Buffer: " + jsonStringify(json, 2, depth + 1) + "]";
break;
default:
val =
- val === '[Function]' || val === '[Circular]'
+ val === "[Function]" || val === "[Circular]"
? val
: JSON.stringify(val); // string
}
@@ -326,17 +326,17 @@ function jsonStringify(object, spaces, depth) {
}
--length;
str +=
- '\n ' +
- repeat(' ', space) +
- (Array.isArray(object) ? '' : '"' + i + '": ') + // key
+ "\n " +
+ repeat(" ", space) +
+ (Array.isArray(object) ? "" : '"' + i + '": ') + // key
_stringify(object[i]) + // value
- (length ? ',' : ''); // comma
+ (length ? "," : ""); // comma
}
return (
str +
// [], {}
- (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end)
+ (str.length !== 1 ? "\n" + repeat(" ", --space) + end : end)
);
}
@@ -374,23 +374,23 @@ exports.canonicalize = function canonicalize(value, stack, typeHint) {
stack = stack || [];
if (stack.indexOf(value) !== -1) {
- return '[Circular]';
+ return "[Circular]";
}
switch (typeHint) {
- case 'undefined':
- case 'buffer':
- case 'null':
+ case "undefined":
+ case "buffer":
+ case "null":
canonicalizedObj = value;
break;
- case 'array':
+ case "array":
withStack(value, function () {
canonicalizedObj = value.map(function (item) {
return exports.canonicalize(item, stack);
});
});
break;
- case 'function':
+ case "function":
/* eslint-disable-next-line no-unused-vars, no-unreachable-loop */
for (prop in value) {
canonicalizedObj = {};
@@ -402,11 +402,11 @@ exports.canonicalize = function canonicalize(value, stack, typeHint) {
break;
}
/* falls through */
- case 'null-prototype':
- case 'object':
+ case "null-prototype":
+ case "object":
canonicalizedObj = canonicalizedObj || {};
- if (typeHint === 'null-prototype' && Symbol.toStringTag in value) {
- canonicalizedObj['[Symbol.toStringTag]'] = value[Symbol.toStringTag];
+ if (typeHint === "null-prototype" && Symbol.toStringTag in value) {
+ canonicalizedObj["[Symbol.toStringTag]"] = value[Symbol.toStringTag];
}
withStack(value, function () {
Object.keys(value)
@@ -416,15 +416,15 @@ exports.canonicalize = function canonicalize(value, stack, typeHint) {
});
});
break;
- case 'date':
- case 'number':
- case 'regexp':
- case 'boolean':
- case 'symbol':
+ case "date":
+ case "number":
+ case "regexp":
+ case "boolean":
+ case "symbol":
canonicalizedObj = value;
break;
default:
- canonicalizedObj = value + '';
+ canonicalizedObj = value + "";
}
return canonicalizedObj;
@@ -441,39 +441,39 @@ exports.canonicalize = function canonicalize(value, stack, typeHint) {
*/
exports.stackTraceFilter = function () {
// TODO: Replace with `process.browser`
- var is = typeof document === 'undefined' ? {node: true} : {browser: true};
+ var is = typeof document === "undefined" ? { node: true } : { browser: true };
var slash = path.sep;
var cwd;
if (is.node) {
cwd = exports.cwd() + slash;
} else {
cwd = (
- typeof location === 'undefined' ? window.location : location
- ).href.replace(/\/[^/]*$/, '/');
- slash = '/';
+ typeof location === "undefined" ? window.location : location
+ ).href.replace(/\/[^/]*$/, "/");
+ slash = "/";
}
function isMochaInternal(line) {
return (
- ~line.indexOf('node_modules' + slash + 'mocha' + slash) ||
- ~line.indexOf(slash + 'mocha.js') ||
- ~line.indexOf(slash + 'mocha.min.js')
+ ~line.indexOf("node_modules" + slash + "mocha" + slash) ||
+ ~line.indexOf(slash + "mocha.js") ||
+ ~line.indexOf(slash + "mocha.min.js")
);
}
function isNodeInternal(line) {
return (
- ~line.indexOf('(timers.js:') ||
- ~line.indexOf('(events.js:') ||
- ~line.indexOf('(node.js:') ||
- ~line.indexOf('(module.js:') ||
- ~line.indexOf('GeneratorFunctionPrototype.next (native)') ||
+ ~line.indexOf("(timers.js:") ||
+ ~line.indexOf("(events.js:") ||
+ ~line.indexOf("(node.js:") ||
+ ~line.indexOf("(module.js:") ||
+ ~line.indexOf("GeneratorFunctionPrototype.next (native)") ||
false
);
}
return function (stack) {
- stack = stack.split('\n');
+ stack = stack.split("\n");
stack = stack.reduce(function (list, line) {
if (isMochaInternal(line)) {
@@ -486,14 +486,14 @@ exports.stackTraceFilter = function () {
// Clean up cwd(absolute)
if (/:\d+:\d+\)?$/.test(line)) {
- line = line.replace('(' + cwd, '(');
+ line = line.replace("(" + cwd, "(");
}
list.push(line);
return list;
}, []);
- return stack.join('\n');
+ return stack.join("\n");
};
};
@@ -505,9 +505,9 @@ exports.stackTraceFilter = function () {
*/
exports.isPromise = function isPromise(value) {
return (
- typeof value === 'object' &&
+ typeof value === "object" &&
value !== null &&
- typeof value.then === 'function'
+ typeof value.then === "function"
);
};
@@ -546,7 +546,7 @@ exports.noop = function () {};
exports.createMap = function () {
return Object.assign.apply(
null,
- [Object.create(null)].concat(Array.prototype.slice.call(arguments))
+ [Object.create(null)].concat(Array.prototype.slice.call(arguments)),
);
};
@@ -563,8 +563,8 @@ exports.createMap = function () {
* @throws {TypeError} if argument is not a non-empty object.
*/
exports.defineConstants = function (obj) {
- if (canonicalType(obj) !== 'object' || !Object.keys(obj).length) {
- throw new TypeError('Invalid argument; expected a non-empty object');
+ if (canonicalType(obj) !== "object" || !Object.keys(obj).length) {
+ throw new TypeError("Invalid argument; expected a non-empty object");
}
return Object.freeze(exports.createMap(obj));
};
@@ -608,8 +608,8 @@ exports.castArray = function castArray(value) {
return [null];
}
if (
- typeof value === 'object' &&
- (typeof value[Symbol.iterator] === 'function' || value.length !== undefined)
+ typeof value === "object" &&
+ (typeof value[Symbol.iterator] === "function" || value.length !== undefined)
) {
return Array.from(value);
}
@@ -617,11 +617,11 @@ exports.castArray = function castArray(value) {
};
exports.constants = exports.defineConstants({
- MOCHA_ID_PROP_NAME
+ MOCHA_ID_PROP_NAME,
});
const uniqueIDBase =
- 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_';
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
/**
* Creates a new unique identifier
@@ -630,19 +630,19 @@ const uniqueIDBase =
* @returns {string} Unique identifier
*/
exports.uniqueID = () => {
- let id = '';
+ let id = "";
for (let i = 0; i < 21; i++) {
id += uniqueIDBase[(Math.random() * 64) | 0];
}
return id;
};
-exports.assignNewMochaID = obj => {
+exports.assignNewMochaID = (obj) => {
const id = exports.uniqueID();
Object.defineProperty(obj, MOCHA_ID_PROP_NAME, {
get() {
return id;
- }
+ },
});
return obj;
};
@@ -652,8 +652,8 @@ exports.assignNewMochaID = obj => {
* @param {*} [obj] - Object
* @returns {string|void}
*/
-exports.getMochaID = obj =>
- obj && typeof obj === 'object' ? obj[MOCHA_ID_PROP_NAME] : undefined;
+exports.getMochaID = (obj) =>
+ obj && typeof obj === "object" ? obj[MOCHA_ID_PROP_NAME] : undefined;
/**
* Replaces any detected circular dependency with the string '[Circular]'
@@ -661,16 +661,16 @@ exports.getMochaID = obj =>
* @param inputObj {*}
* @returns {*}
*/
-exports.breakCircularDeps = inputObj => {
+exports.breakCircularDeps = (inputObj) => {
const seen = new Set();
function _breakCircularDeps(obj) {
- if (obj && typeof obj !== 'object') {
+ if (obj && typeof obj !== "object") {
return obj;
}
if (seen.has(obj)) {
- return '[Circular]';
+ return "[Circular]";
}
seen.add(obj);
@@ -693,6 +693,6 @@ exports.breakCircularDeps = inputObj => {
/**
* Checks if provided input can be parsed as a JavaScript Number.
*/
-exports.isNumeric = input => {
+exports.isNumeric = (input) => {
return !isNaN(parseFloat(input));
};
diff --git a/mocha.css b/mocha.css
index c9839f80..8c3c70a7 100644
--- a/mocha.css
+++ b/mocha.css
@@ -5,7 +5,7 @@
--mocha-bg-color: #fff;
--mocha-test-pass-color: #007f6a;
--mocha-test-pass-duration-color: #fff;
- --mocha-test-pass-shadow-color: rgba(0,0,0, 0.2);
+ --mocha-test-pass-shadow-color: rgba(0, 0, 0, 0.2);
--mocha-test-pass-mediump-color: #c09853;
--mocha-test-pass-slow-color: #b94a48;
--mocha-test-pending-color: #0b97c4;
@@ -27,7 +27,7 @@
--mocha-progress-text-color: #000;
--mocha-error-color: #c00;
- --mocha-code-comment: #ddd;
+ --mocha-code-comment: #ddd;
--mocha-code-init: #2f6fad;
--mocha-code-string: #5890ad;
--mocha-code-keyword: #8a6343;
@@ -36,48 +36,52 @@
@media (prefers-color-scheme: dark) {
:root {
- --mocha-color: #fff;
- --mocha-bg-color: #222;
- --mocha-test-pass-color: #00d6b2;
- --mocha-test-pass-duration-color: #222;
- --mocha-test-pass-shadow-color: rgba(255, 255, 255, 0.2);
- --mocha-test-pass-mediump-color: #f1be67;
- --mocha-test-pass-slow-color: #f49896;
- --mocha-test-pending-color: #0b97c4;
- --mocha-test-pending-icon-color: #0b97c4;
- --mocha-test-fail-color: #f44;
- --mocha-test-fail-icon-color: #f44;
- --mocha-test-fail-pre-color: #fff;
- --mocha-test-fail-pre-error-color: #f44;
- --mocha-test-html-error-color: #fff;
- --mocha-box-shadow-color: #444;
- --mocha-box-bottom-color: #555;
- --mocha-test-replay-color: #fff;
- --mocha-test-replay-bg-color: #444;
- --mocha-stats-color: #aaa;
- --mocha-stats-em-color: #fff;
- --mocha-stats-hover-color: #444;
- --mocha-progress-ring-color: #444;
- --mocha-progress-ring-highlight-color: #888;
- --mocha-progress-text-color: #fff;
- --mocha-error-color: #f44;
-
- --mocha-code-comment: #ddd;
- --mocha-code-init: #9cc7f1;
- --mocha-code-string: #80d4ff;
- --mocha-code-keyword: #e3a470;
- --mocha-code-number: #4ca7ff;
+ --mocha-color: #fff;
+ --mocha-bg-color: #222;
+ --mocha-test-pass-color: #00d6b2;
+ --mocha-test-pass-duration-color: #222;
+ --mocha-test-pass-shadow-color: rgba(255, 255, 255, 0.2);
+ --mocha-test-pass-mediump-color: #f1be67;
+ --mocha-test-pass-slow-color: #f49896;
+ --mocha-test-pending-color: #0b97c4;
+ --mocha-test-pending-icon-color: #0b97c4;
+ --mocha-test-fail-color: #f44;
+ --mocha-test-fail-icon-color: #f44;
+ --mocha-test-fail-pre-color: #fff;
+ --mocha-test-fail-pre-error-color: #f44;
+ --mocha-test-html-error-color: #fff;
+ --mocha-box-shadow-color: #444;
+ --mocha-box-bottom-color: #555;
+ --mocha-test-replay-color: #fff;
+ --mocha-test-replay-bg-color: #444;
+ --mocha-stats-color: #aaa;
+ --mocha-stats-em-color: #fff;
+ --mocha-stats-hover-color: #444;
+ --mocha-progress-ring-color: #444;
+ --mocha-progress-ring-highlight-color: #888;
+ --mocha-progress-text-color: #fff;
+ --mocha-error-color: #f44;
+
+ --mocha-code-comment: #ddd;
+ --mocha-code-init: #9cc7f1;
+ --mocha-code-string: #80d4ff;
+ --mocha-code-keyword: #e3a470;
+ --mocha-code-number: #4ca7ff;
}
}
body {
- margin:0;
+ margin: 0;
background-color: var(--mocha-bg-color);
color: var(--mocha-color);
}
#mocha {
- font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif;
+ font:
+ 20px/1.5 "Helvetica Neue",
+ Helvetica,
+ Arial,
+ sans-serif;
margin: 60px 50px;
}
@@ -113,7 +117,7 @@ body {
#mocha .suite .suite h1 {
margin-top: 0;
- font-size: .8em;
+ font-size: 0.8em;
}
#mocha .hidden {
@@ -136,7 +140,7 @@ body {
}
#mocha .test.pending:hover h2::after {
- content: '(pending)';
+ content: "(pending)";
font-family: arial, sans-serif;
}
@@ -149,7 +153,7 @@ body {
}
#mocha .test.pass::before {
- content: '✓';
+ content: "✓";
font-size: 12px;
display: block;
float: left;
@@ -181,7 +185,7 @@ body {
}
#mocha .test.pending::before {
- content: '◦';
+ content: "◦";
color: var(--mocha-test-pending-icon-color);
}
@@ -194,7 +198,7 @@ body {
}
#mocha .test.fail::before {
- content: '✖';
+ content: "✖";
font-size: 12px;
display: block;
float: left;
@@ -214,7 +218,9 @@ body {
display: block;
float: left;
clear: left;
- font: 12px/1.5 monaco, monospace;
+ font:
+ 12px/1.5 monaco,
+ monospace;
margin: 5px;
padding: 15px;
border: 1px solid var(--mocha-box-shadow-color);
@@ -256,7 +262,9 @@ body {
display: block;
float: left;
clear: left;
- font: 12px/1.5 monaco, monospace;
+ font:
+ 12px/1.5 monaco,
+ monospace;
margin: 5px;
padding: 15px;
border: 1px solid var(--mocha-box-shadow-color);
@@ -294,9 +302,9 @@ body {
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
- -webkit-transition:opacity 200ms;
- -moz-transition:opacity 200ms;
- -o-transition:opacity 200ms;
+ -webkit-transition: opacity 200ms;
+ -moz-transition: opacity 200ms;
+ -o-transition: opacity 200ms;
transition: opacity 200ms;
opacity: 0.7;
color: var(--mocha-test-replay-color);
@@ -438,11 +446,21 @@ body {
padding-top: 11px;
}
-#mocha code .comment { color: var(--mocha-code-comment); }
-#mocha code .init { color: var(--mocha-code-init); }
-#mocha code .string { color: var(--mocha-code-string); }
-#mocha code .keyword { color: var(--mocha-code-keyword); }
-#mocha code .number { color: var(--mocha-code-number); }
+#mocha code .comment {
+ color: var(--mocha-code-comment);
+}
+#mocha code .init {
+ color: var(--mocha-code-init);
+}
+#mocha code .string {
+ color: var(--mocha-code-string);
+}
+#mocha code .keyword {
+ color: var(--mocha-code-keyword);
+}
+#mocha code .number {
+ color: var(--mocha-code-number);
+}
@media screen and (max-device-width: 480px) {
#mocha {
diff --git a/package-lock.json b/package-lock.json
index 1dfdc2f8..69f2e75a 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -75,7 +75,7 @@
"needle": "^2.5.0",
"npm-run-all2": "^6.2.0",
"nyc": "^15.1.0",
- "prettier": "^2.4.1",
+ "prettier": "3.6.2",
"ps-list": "^9.0.0",
"remark": "^14.0.2",
"remark-github": "^11.2.2",
@@ -12677,15 +12677,16 @@
}
},
"node_modules/prettier": {
- "version": "2.8.4",
- "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.4.tgz",
- "integrity": "sha512-vIS4Rlc2FNh0BySk3Wkd6xmwxB0FpOndW5fisM5H8hsZSxU2VWVB5CWIkIjWvrHjIhxk2g3bfMKM87zNTrZddw==",
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz",
+ "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
"dev": true,
+ "license": "MIT",
"bin": {
- "prettier": "bin-prettier.js"
+ "prettier": "bin/prettier.cjs"
},
"engines": {
- "node": ">=10.13.0"
+ "node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
@@ -26550,9 +26551,9 @@
"dev": true
},
"prettier": {
- "version": "2.8.4",
- "resolved": "https://registry.npmjs.org/prettier/-/prettier-2.8.4.tgz",
- "integrity": "sha512-vIS4Rlc2FNh0BySk3Wkd6xmwxB0FpOndW5fisM5H8hsZSxU2VWVB5CWIkIjWvrHjIhxk2g3bfMKM87zNTrZddw==",
+ "version": "3.6.2",
+ "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.6.2.tgz",
+ "integrity": "sha512-I7AIg5boAr5R0FFtJ6rCfD+LFsWHp81dolrFD8S79U9tb8Az2nGrJncnMSnys+bpQJfRUzqs9hnA81OAA3hCuQ==",
"dev": true
},
"pretty": {
diff --git a/package.json b/package.json
index 819f7d50..2ca471c0 100644
--- a/package.json
+++ b/package.json
@@ -53,7 +53,7 @@
"docs:preview": "http-server docs/_site -o",
"docs": "run-s docs-clean docs:api docs:build docs:build-new",
"format:eslint": "eslint --fix . \"bin/*\"",
- "format:prettier": "prettier --write \"!(package*).json\" \".*.json\" \"lib/**/*.json\" \"*.yml\"",
+ "format:prettier": "prettier --write .",
"format": "run-s format:*",
"lint:installed-check": "installed-check --engine-check",
"lint:knip": "knip --cache",
@@ -160,7 +160,7 @@
"needle": "^2.5.0",
"npm-run-all2": "^6.2.0",
"nyc": "^15.1.0",
- "prettier": "^2.4.1",
+ "prettier": "3.6.2",
"ps-list": "^9.0.0",
"remark": "^14.0.2",
"remark-github": "^11.2.2",
@@ -206,13 +206,6 @@
"./lib/nodejs/reporters/parallel-buffered.js": false,
"./lib/cli/index.js": false
},
- "prettier": {
- "arrowParens": "avoid",
- "bracketSpacing": false,
- "endOfLine": "auto",
- "singleQuote": true,
- "trailingComma": "none"
- },
"overrides": {
"@types/eslint": "^9.6.1",
"@types/estree": "^1.0.7",
diff --git a/rollup.config.js b/rollup.config.js
index d476a9a7..c2fe5f60 100644
--- a/rollup.config.js
+++ b/rollup.config.js
@@ -1,47 +1,47 @@
-import alias from '@rollup/plugin-alias';
-import commonjs from '@rollup/plugin-commonjs';
-import nodeResolve from '@rollup/plugin-node-resolve';
-import json from '@rollup/plugin-json';
-import nodePolyfills from 'rollup-plugin-polyfill-node';
-import globals from 'rollup-plugin-node-globals';
+import alias from "@rollup/plugin-alias";
+import commonjs from "@rollup/plugin-commonjs";
+import nodeResolve from "@rollup/plugin-node-resolve";
+import json from "@rollup/plugin-json";
+import nodePolyfills from "rollup-plugin-polyfill-node";
+import globals from "rollup-plugin-node-globals";
// Debugging tools
-import {visualizer} from 'rollup-plugin-visualizer';
+import { visualizer } from "rollup-plugin-visualizer";
-import pickFromPackageJson from './scripts/pick-from-package-json';
-import {version} from './package.json';
+import pickFromPackageJson from "./scripts/pick-from-package-json";
+import { version } from "./package.json";
const config = {
- input: './browser-entry.js',
+ input: "./browser-entry.js",
output: {
- file: './mocha.js',
- format: 'umd',
+ file: "./mocha.js",
+ format: "umd",
sourcemap: true,
- name: 'mocha',
- banner: `// mocha@${version} in javascript ES2018`
+ name: "mocha",
+ banner: `// mocha@${version} in javascript ES2018`,
},
plugins: [
// https://github.com/FredKSchott/rollup-plugin-polyfill-node/issues/84
alias({
- entries: [{find: /^node:(.*)/, replacement: '$1'}]
+ entries: [{ find: /^node:(.*)/, replacement: "$1" }],
}),
json(),
pickFromPackageJson({
- keys: ['name', 'version', 'homepage', 'notifyLogo']
+ keys: ["name", "version", "homepage", "notifyLogo"],
}),
commonjs(),
globals(),
nodePolyfills(),
nodeResolve({
- browser: true
- })
+ browser: true,
+ }),
],
onwarn: (warning, warn) => {
- if (warning.code === 'CIRCULAR_DEPENDENCY') return;
+ if (warning.code === "CIRCULAR_DEPENDENCY") return;
// Use default for everything else
warn(warning);
- }
+ },
};
if (!process.env.CI) {
diff --git a/scripts/karma-rollup-plugin.js b/scripts/karma-rollup-plugin.js
index 2b0d7da3..63fe2ff9 100644
--- a/scripts/karma-rollup-plugin.js
+++ b/scripts/karma-rollup-plugin.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
/**
* This Karma plugin bundles all test files into a single file for browser
@@ -29,14 +29,14 @@
* been modified heavily to simplify and support rollup instead of browserify.
*/
-const os = require('node:os');
-const fs = require('node:fs');
-const path = require('node:path');
-const {randomUUID} = require('node:crypto');
-const rollup = require('rollup');
-const { minimatch } = require('minimatch');
-const loadConfigFile = require('rollup/dist/loadConfigFile.js');
-const multiEntry = require('@rollup/plugin-multi-entry');
+const os = require("node:os");
+const fs = require("node:fs");
+const path = require("node:path");
+const { randomUUID } = require("node:crypto");
+const rollup = require("rollup");
+const { minimatch } = require("minimatch");
+const loadConfigFile = require("rollup/dist/loadConfigFile.js");
+const multiEntry = require("@rollup/plugin-multi-entry");
const fileMap = new Map();
@@ -45,29 +45,29 @@ const fileMap = new Map();
* as well as prepends the bundle file to the karma file configuration.
*/
function framework(fileConfigs, pluginConfig, basePath, preprocessors) {
- const includePatterns = pluginConfig.include.map(pattern =>
- path.resolve(basePath, pattern)
+ const includePatterns = pluginConfig.include.map((pattern) =>
+ path.resolve(basePath, pattern),
);
const bundlePatterns = fileConfigs
- .map(fileConfig => fileConfig.pattern)
- .filter(filePath =>
- includePatterns.some(includePattern =>
- minimatch(filePath, includePattern.replace(/\\/g, '/'))
- )
+ .map((fileConfig) => fileConfig.pattern)
+ .filter((filePath) =>
+ includePatterns.some((includePattern) =>
+ minimatch(filePath, includePattern.replace(/\\/g, "/")),
+ ),
);
const bundleFilename = `${randomUUID()}.rollup.js`;
let bundleLocation = path.resolve(
pluginConfig.bundleDirPath ? pluginConfig.bundleDirPath : os.tmpdir(),
- bundleFilename
+ bundleFilename,
);
- if (process.platform === 'win32') {
- bundleLocation = bundleLocation.replace(/\\/g, '/');
+ if (process.platform === "win32") {
+ bundleLocation = bundleLocation.replace(/\\/g, "/");
}
- fs.closeSync(fs.openSync(bundleLocation, 'w'));
- preprocessors[bundleLocation] = ['rollup'];
+ fs.closeSync(fs.openSync(bundleLocation, "w"));
+ preprocessors[bundleLocation] = ["rollup"];
// Save file mapping for later
fileMap.set(bundleLocation, bundlePatterns);
@@ -77,7 +77,9 @@ function framework(fileConfigs, pluginConfig, basePath, preprocessors) {
// Need to use array mutation, otherwise Karma ignores us
let bundleInjected = false;
for (const bundlePattern of bundlePatterns) {
- const idx = fileConfigs.findIndex(({pattern}) => pattern === bundlePattern);
+ const idx = fileConfigs.findIndex(
+ ({ pattern }) => pattern === bundlePattern,
+ );
if (idx > -1) {
if (bundleInjected) {
@@ -87,7 +89,7 @@ function framework(fileConfigs, pluginConfig, basePath, preprocessors) {
pattern: bundleLocation,
served: true,
included: true,
- watched: true
+ watched: true,
});
bundleInjected = true;
}
@@ -96,10 +98,10 @@ function framework(fileConfigs, pluginConfig, basePath, preprocessors) {
}
framework.$inject = [
- 'config.files',
- 'config.rollup',
- 'config.basePath',
- 'config.preprocessors'
+ "config.files",
+ "config.rollup",
+ "config.basePath",
+ "config.preprocessors",
];
/**
@@ -109,18 +111,18 @@ framework.$inject = [
function bundlePreprocessor(config) {
const {
basePath,
- rollup: {configFile, globals = {}, external = []}
+ rollup: { configFile, globals = {}, external = [] },
} = config;
const configPromise = loadConfigFile(path.resolve(basePath, configFile));
return async function (content, file, done) {
- const {options, warnings} = await configPromise;
+ const { options, warnings } = await configPromise;
const config = options[0];
// plugins is always an array
const pluginConfig = [
...(config.plugins || []),
- multiEntry({exports: false})
+ multiEntry({ exports: false }),
];
// XXX: output is always an array, but we only have one output config.
// if we have multiple, this code needs changing.
@@ -128,7 +130,7 @@ function bundlePreprocessor(config) {
...((config.output || [])[0] || {}),
file: file.path,
globals,
- sourcemap: 'inline'
+ sourcemap: "inline",
};
warnings.flush();
@@ -137,20 +139,20 @@ function bundlePreprocessor(config) {
input: fileMap.get(file.path),
plugins: pluginConfig,
external,
- onwarn: config.onwarn
+ onwarn: config.onwarn,
});
await bundle.write(outputConfig);
console.error(`wrote bundle to ${file.path}`);
- const code = fs.readFileSync(outputConfig.file, 'utf8');
+ const code = fs.readFileSync(outputConfig.file, "utf8");
done(null, code);
};
}
-bundlePreprocessor.$inject = ['config'];
+bundlePreprocessor.$inject = ["config"];
module.exports = {
- 'framework:rollup': ['factory', framework],
- 'preprocessor:rollup': ['factory', bundlePreprocessor]
+ "framework:rollup": ["factory", framework],
+ "preprocessor:rollup": ["factory", bundlePreprocessor],
};
diff --git a/scripts/linkify-changelog.mjs b/scripts/linkify-changelog.mjs
index dc87a680..71422569 100644
--- a/scripts/linkify-changelog.mjs
+++ b/scripts/linkify-changelog.mjs
@@ -2,22 +2,22 @@
* Linkify CHANGELOG.md
*/
-import {readFileSync, writeFileSync} from 'node:fs';
-import {remark} from 'remark';
-import remarkGithub from 'remark-github';
-import remarkInlineLinks from 'remark-inline-links';
+import { readFileSync, writeFileSync } from "node:fs";
+import { remark } from "remark";
+import remarkGithub from "remark-github";
+import remarkInlineLinks from "remark-inline-links";
-const filepath = new URL('../CHANGELOG.md', import.meta.url);
+const filepath = new URL("../CHANGELOG.md", import.meta.url);
writeFileSync(
filepath,
remark()
- .data('settings', {
- bullet: '-',
+ .data("settings", {
+ bullet: "-",
incrementListMarker: false,
- listItemIndent: 'one'
+ listItemIndent: "one",
})
.use([remarkGithub, remarkInlineLinks])
.processSync(readFileSync(filepath))
- .toString()
+ .toString(),
);
diff --git a/scripts/pick-from-package-json.js b/scripts/pick-from-package-json.js
index 30db576d..89ee0b51 100644
--- a/scripts/pick-from-package-json.js
+++ b/scripts/pick-from-package-json.js
@@ -7,11 +7,11 @@
* @param {object} options
* @param {string[]} options.keys List of keys to export from package.json
*/
-export default function pickFromPackageJson({keys}) {
+export default function pickFromPackageJson({ keys }) {
return {
- name: 'pick-from-package-json',
- load: id => {
- if (id.endsWith('mocha/package.json')) {
+ name: "pick-from-package-json",
+ load: (id) => {
+ if (id.endsWith("mocha/package.json")) {
const manifest = require(id);
const result = {};
@@ -20,9 +20,9 @@ export default function pickFromPackageJson({keys}) {
result[key] = manifest[key];
}
- return {code: JSON.stringify(result)};
+ return { code: JSON.stringify(result) };
}
return null;
- }
+ },
};
}
diff --git a/scripts/update-authors.js b/scripts/update-authors.js
index ed5ff524..32ac8db5 100755
--- a/scripts/update-authors.js
+++ b/scripts/update-authors.js
@@ -2,35 +2,35 @@
// Usage: tools/update-author.js [--dry]
// Passing --dry will redirect output to stdout rather than write to 'AUTHORS'.
-'use strict';
-const {spawn} = require('node:child_process');
-const fs = require('node:fs');
-const readline = require('node:readline');
+"use strict";
+const { spawn } = require("node:child_process");
+const fs = require("node:fs");
+const readline = require("node:readline");
const log = spawn(
- 'git',
+ "git",
// Inspect author name/email and body.
- ['log', '--reverse', '--format=Author: %aN <%aE>\n%b'],
+ ["log", "--reverse", "--format=Author: %aN <%aE>\n%b"],
{
- stdio: ['inherit', 'pipe', 'inherit']
- }
+ stdio: ["inherit", "pipe", "inherit"],
+ },
);
-const rl = readline.createInterface({input: log.stdout});
+const rl = readline.createInterface({ input: log.stdout });
let output;
-if (process.argv.includes('--dry')) {
+if (process.argv.includes("--dry")) {
output = process.stdout;
} else {
- output = fs.createWriteStream('AUTHORS');
+ output = fs.createWriteStream("AUTHORS");
}
-output.write('# Authors ordered by first contribution.\n\n');
+output.write("# Authors ordered by first contribution.\n\n");
const seen = new Set();
const excludeEmails = [
- '<greenkeeper[bot]@users.noreply.github.com>'
+ "<greenkeeper[bot]@users.noreply.github.com>",
];
// Support regular git author metadata, as well as `Author:` and
@@ -40,11 +40,11 @@ const excludeEmails = [
const authorRe =
/(^Author:|^Co-authored-by:)\s+(?<author>[^<]+)\s+(?<email><[^>]+>)/i;
-rl.on('line', line => {
+rl.on("line", (line) => {
const match = line.match(authorRe);
if (!match) return;
- const {author, email} = match.groups;
+ const { author, email } = match.groups;
if (seen.has(email) || excludeEmails.includes(email)) {
return;
@@ -54,6 +54,6 @@ rl.on('line', line => {
output.write(`${author} ${email}\n`);
});
-rl.on('close', () => {
- output.end('\n# Generated by scripts/update-authors.js\n');
+rl.on("close", () => {
+ output.end("\n# Generated by scripts/update-authors.js\n");
});
diff --git a/test/README.md b/test/README.md
index 2d1b8e1c..cca03f6c 100644
--- a/test/README.md
+++ b/test/README.md
@@ -1,12 +1,12 @@
# About Mocha's Tests
-- **All assertions should be made using [unexpected](http://unexpected.js.org)**, unless there's a good reason not to. Exceptions include:
- - Testing diff output. Mocha generates diff output unless the assertion library decides to do this itself. Since `unexpected` generates its *own* diff output, we need to use an assertion library that does not; we use the built-in `assert` module.
+- **All assertions should be made using [unexpected](http://unexpected.js.org)**, unless there's a good reason not to. Exceptions include:
+ - Testing diff output. Mocha generates diff output unless the assertion library decides to do this itself. Since `unexpected` generates its _own_ diff output, we need to use an assertion library that does not; we use the built-in `assert` module.
- `test/unit/runnable.spec.js` must avoid 3rd-party code; read source for more info
- Tests asserting interop with other specific assertion libraries.
- All tests have extension `.spec.js`.
- All test fixtures have extension `.fixture.js`.
-- All test fixtures are *ignored* by ESLint.
+- All test fixtures are _ignored_ by ESLint.
- `mocha.opts` will require `test/setup.js`, which is the main harness.
- `test/assertions.js` contains Mocha-specific types and assertions for `unexpected`
- `test/node-unit/` only runs in Node.js; `test/browser-specific/` only runs in the browser.
diff --git a/test/assertions.js b/test/assertions.js
index b6ed7b9c..b5e5a416 100644
--- a/test/assertions.js
+++ b/test/assertions.js
@@ -1,348 +1,348 @@
-'use strict';
+"use strict";
-const {version} = require('../package.json');
-const escapeRe = require('escape-string-regexp');
+const { version } = require("../package.json");
+const escapeRe = require("escape-string-regexp");
module.exports = {
- name: 'unexpected-mocha-internal',
+ name: "unexpected-mocha-internal",
version,
installInto(expect) {
expect
.addType({
- name: 'RawResult',
- base: 'object',
+ name: "RawResult",
+ base: "object",
identify(v) {
return (
this.baseType.identify(v) &&
- typeof v.output === 'string' &&
- 'code' in v && // may be null
+ typeof v.output === "string" &&
+ "code" in v && // may be null
Array.isArray(v.args) &&
- typeof v.command === 'string'
+ typeof v.command === "string"
);
- }
+ },
})
.addType({
- name: 'JSONResult',
- base: 'RawResult',
+ name: "JSONResult",
+ base: "RawResult",
identify(v) {
return (
this.baseType.identify(v) &&
- typeof v.stats === 'object' &&
+ typeof v.stats === "object" &&
Array.isArray(v.failures) &&
Array.isArray(v.passes) &&
Array.isArray(v.tests) &&
Array.isArray(v.pending)
);
- }
+ },
})
.addType({
- name: 'SummarizedResult',
- base: 'RawResult',
+ name: "SummarizedResult",
+ base: "RawResult",
identify(v) {
return (
this.baseType.identify(v) &&
- typeof v.passing === 'number' &&
- typeof v.failing === 'number' &&
- typeof v.pending === 'number'
+ typeof v.passing === "number" &&
+ typeof v.failing === "number" &&
+ typeof v.pending === "number"
);
- }
+ },
})
.addAssertion(
- '<JSONResult> [not] to have (passed|succeeded)',
+ "<JSONResult> [not] to have (passed|succeeded)",
(expect, result) => {
- expect(result, 'to satisfy', {
- code: expect.it('[not] to be', 0),
+ expect(result, "to satisfy", {
+ code: expect.it("[not] to be", 0),
stats: {
- failures: expect.it('[not] to be', 0)
+ failures: expect.it("[not] to be", 0),
},
- failures: expect.it('[not] to be empty')
+ failures: expect.it("[not] to be empty"),
});
- }
+ },
)
.addAssertion(
- '<SummarizedResult|RawResult> [not] to have (passed|succeeded)',
+ "<SummarizedResult|RawResult> [not] to have (passed|succeeded)",
(expect, result) => {
- expect(result, '[not] to have property', 'code', 0);
- }
+ expect(result, "[not] to have property", "code", 0);
+ },
)
.addAssertion(
- '<SummarizedResult|JSONResult> [not] to have completed with [exit] code <number>',
+ "<SummarizedResult|JSONResult> [not] to have completed with [exit] code <number>",
(expect, result, code) => {
- expect(result.code, '[not] to be', code);
- }
+ expect(result.code, "[not] to be", code);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have passed (with|having) count <number>',
+ "<JSONResult> [not] to have passed (with|having) count <number>",
(expect, result, count) => {
- expect(result, '[not] to pass').and('[not] to satisfy', {
- stats: {passes: expect.it('to be', count)}
+ expect(result, "[not] to pass").and("[not] to satisfy", {
+ stats: { passes: expect.it("to be", count) },
});
- }
+ },
)
.addAssertion(
- '<JSONResult> [not] to have failed (with|having) count <number>',
+ "<JSONResult> [not] to have failed (with|having) count <number>",
(expect, result, count) => {
- expect(result, '[not] to have failed').and('[not] to satisfy', {
- stats: {failures: expect.it('to be', count)}
+ expect(result, "[not] to have failed").and("[not] to satisfy", {
+ stats: { failures: expect.it("to be", count) },
});
- }
+ },
)
- .addAssertion('<JSONResult> [not] to have failed', (expect, result) => {
- expect(result, '[not] to satisfy', {
- code: expect.it('to be greater than', 0),
+ .addAssertion("<JSONResult> [not] to have failed", (expect, result) => {
+ expect(result, "[not] to satisfy", {
+ code: expect.it("to be greater than", 0),
stats: {
- failures: expect.it('to be greater than', 0)
+ failures: expect.it("to be greater than", 0),
},
- failures: expect.it('to be non-empty')
+ failures: expect.it("to be non-empty"),
});
})
.addAssertion(
- '<SummarizedResult|RawResult> [not] to have failed',
+ "<SummarizedResult|RawResult> [not] to have failed",
(expect, result) => {
- expect(result, '[not] to satisfy', {
- code: expect.it('to be greater than', 0)
+ expect(result, "[not] to satisfy", {
+ code: expect.it("to be greater than", 0),
});
- }
+ },
)
.addAssertion(
- '<SummarizedResult|RawResult> [not] to have failed (with|having) output <any>',
+ "<SummarizedResult|RawResult> [not] to have failed (with|having) output <any>",
(expect, result, output) => {
- expect(result, '[not] to satisfy', {
- code: expect.it('to be greater than', 0),
- output
+ expect(result, "[not] to satisfy", {
+ code: expect.it("to be greater than", 0),
+ output,
});
- }
+ },
)
.addAssertion(
- '<SummarizedResult|RawResult> [not] to have passed (with|having) output <any>',
+ "<SummarizedResult|RawResult> [not] to have passed (with|having) output <any>",
(expect, result, output) => {
- expect(result, '[not] to satisfy', {
+ expect(result, "[not] to satisfy", {
code: 0,
- output
+ output,
});
- }
+ },
)
.addAssertion(
- '<SummarizedResult> [not] to have failed [test] count <number>',
+ "<SummarizedResult> [not] to have failed [test] count <number>",
(expect, result, count) => {
- expect(result.failing, '[not] to be', count);
- }
+ expect(result.failing, "[not] to be", count);
+ },
)
.addAssertion(
- '<SummarizedResult> [not] to have passed [test] count <number>',
+ "<SummarizedResult> [not] to have passed [test] count <number>",
(expect, result, count) => {
- expect(result.passing, '[not] to be', count);
- }
+ expect(result.passing, "[not] to be", count);
+ },
)
.addAssertion(
- '<SummarizedResult> [not] to have pending [test] count <number>',
+ "<SummarizedResult> [not] to have pending [test] count <number>",
(expect, result, count) => {
- expect(result.pending, '[not] to be', count);
- }
+ expect(result.pending, "[not] to be", count);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have test count <number>',
+ "<JSONResult> [not] to have test count <number>",
(expect, result, count) => {
- expect(result.stats.tests, '[not] to be', count);
- }
+ expect(result.stats.tests, "[not] to be", count);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have failed [test] count <number>',
+ "<JSONResult> [not] to have failed [test] count <number>",
(expect, result, count) => {
- expect(result.stats.failures, '[not] to be', count);
- }
+ expect(result.stats.failures, "[not] to be", count);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have passed [test] count <number>',
+ "<JSONResult> [not] to have passed [test] count <number>",
(expect, result, count) => {
- expect(result.stats.passes, '[not] to be', count);
- }
+ expect(result.stats.passes, "[not] to be", count);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have pending [test] count <number>',
+ "<JSONResult> [not] to have pending [test] count <number>",
(expect, result, count) => {
- expect(result.stats.pending, '[not] to be', count);
- }
+ expect(result.stats.pending, "[not] to be", count);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have run (test|tests) <string+>',
+ "<JSONResult> [not] to have run (test|tests) <string+>",
(expect, result, ...titles) => {
- titles.forEach(title => {
+ titles.forEach((title) => {
expect(
result,
- '[not] to have a value satisfying',
+ "[not] to have a value satisfying",
expect.it(
- 'to have an item satisfying',
+ "to have an item satisfying",
expect
- .it('to have property', 'title', title)
- .or('to have property', 'fullTitle', title)
- )
+ .it("to have property", "title", title)
+ .or("to have property", "fullTitle", title),
+ ),
);
});
- }
+ },
)
.addAssertion(
- '<JSONResult> [not] to have failed (test|tests) <string+>',
+ "<JSONResult> [not] to have failed (test|tests) <string+>",
(expect, result, ...titles) => {
- titles.forEach(title => {
+ titles.forEach((title) => {
expect(
result.failures,
- '[not] to have an item satisfying',
+ "[not] to have an item satisfying",
expect
- .it('to have property', 'title', title)
- .or('to have property', 'fullTitle', title)
+ .it("to have property", "title", title)
+ .or("to have property", "fullTitle", title),
);
});
- }
+ },
)
.addAssertion(
- '<JSONResult> [not] to have (error|errors) <any+>',
+ "<JSONResult> [not] to have (error|errors) <any+>",
(expect, result, ...errors) => {
- errors.forEach(error => {
- expect(result, '[not] to satisfy', {
- failures: expect.it('to have an item satisfying', {
+ errors.forEach((error) => {
+ expect(result, "[not] to satisfy", {
+ failures: expect.it("to have an item satisfying", {
err: expect
- .it('to satisfy', error)
- .or('to satisfy', {message: error})
- })
+ .it("to satisfy", error)
+ .or("to satisfy", { message: error }),
+ }),
});
});
- }
+ },
)
.addAssertion(
- '<JSONResult> [not] to have passed (test|tests) <string+>',
+ "<JSONResult> [not] to have passed (test|tests) <string+>",
(expect, result, ...titles) => {
- titles.forEach(title => {
- expect(result.passes, '[not] to have an item satisfying', {
- title
+ titles.forEach((title) => {
+ expect(result.passes, "[not] to have an item satisfying", {
+ title,
});
});
- }
+ },
)
.addAssertion(
- '<JSONResult> [not] to have test order <string> <array>',
+ "<JSONResult> [not] to have test order <string> <array>",
(expect, result, state, titles) => {
expect(
result[state].slice(0, titles.length),
- '[not] to satisfy',
- titles.map(title => {
- return typeof title === 'string' ? {title} : title;
- })
+ "[not] to satisfy",
+ titles.map((title) => {
+ return typeof title === "string" ? { title } : title;
+ }),
);
- }
+ },
)
.addAssertion(
- '<JSONResult> [not] to have passed test order <array>',
+ "<JSONResult> [not] to have passed test order <array>",
(expect, result, titles) => {
- expect(result, '[not] to have test order', 'passes', titles);
- }
+ expect(result, "[not] to have test order", "passes", titles);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have passed test order <string+>',
+ "<JSONResult> [not] to have passed test order <string+>",
(expect, result, ...titles) => {
- expect(result, '[not] to have test order', 'passes', titles);
- }
+ expect(result, "[not] to have test order", "passes", titles);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have failed test order <array>',
+ "<JSONResult> [not] to have failed test order <array>",
(expect, result, titles) => {
- expect(result, '[not] to have test order', 'failures', titles);
- }
+ expect(result, "[not] to have test order", "failures", titles);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have failed test order <string+>',
+ "<JSONResult> [not] to have failed test order <string+>",
(expect, result, ...titles) => {
- expect(result, '[not] to have test order', 'failures', titles);
- }
+ expect(result, "[not] to have test order", "failures", titles);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have pending test order <array>',
+ "<JSONResult> [not] to have pending test order <array>",
(expect, result, titles) => {
- expect(result, '[not] to have test order', 'pending', titles);
- }
+ expect(result, "[not] to have test order", "pending", titles);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have pending test order <string+>',
+ "<JSONResult> [not] to have pending test order <string+>",
(expect, result, ...titles) => {
- expect(result, '[not] to have test order', 'pending', titles);
- }
+ expect(result, "[not] to have test order", "pending", titles);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have pending tests',
+ "<JSONResult> [not] to have pending tests",
(expect, result) => {
- expect(result.stats.pending, '[not] to be greater than', 0);
- }
+ expect(result.stats.pending, "[not] to be greater than", 0);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have passed tests',
+ "<JSONResult> [not] to have passed tests",
(expect, result) => {
- expect(result.stats.passes, '[not] to be greater than', 0);
- }
+ expect(result.stats.passes, "[not] to be greater than", 0);
+ },
)
.addAssertion(
- '<JSONResult> [not] to have failed tests',
+ "<JSONResult> [not] to have failed tests",
(expect, result) => {
- expect(result.stats.failed, '[not] to be greater than', 0);
- }
+ expect(result.stats.failed, "[not] to be greater than", 0);
+ },
)
- .addAssertion('<JSONResult> [not] to have tests', (expect, result) => {
- expect(result.stats.tests, '[not] to be greater than', 0);
+ .addAssertion("<JSONResult> [not] to have tests", (expect, result) => {
+ expect(result.stats.tests, "[not] to be greater than", 0);
})
.addAssertion(
- '<JSONResult> [not] to have retried test <string>',
+ "<JSONResult> [not] to have retried test <string>",
(expect, result, title) => {
- expect(result.tests, '[not] to have an item satisfying', {
+ expect(result.tests, "[not] to have an item satisfying", {
title,
- currentRetry: expect.it('to be positive')
+ currentRetry: expect.it("to be positive"),
});
- }
+ },
)
.addAssertion(
- '<JSONResult> [not] to have retried test <string> <number>',
+ "<JSONResult> [not] to have retried test <string> <number>",
(expect, result, title, count) => {
- expect(result.tests, '[not] to have an item satisfying', {
+ expect(result.tests, "[not] to have an item satisfying", {
title,
- currentRetry: count
+ currentRetry: count,
});
- }
+ },
)
.addAssertion(
- '<JSONResult> [not] to have failed with (error|errors) <any+>',
+ "<JSONResult> [not] to have failed with (error|errors) <any+>",
function (expect, result, ...errors) {
- errors.forEach(error => {
- expect(result, '[not] to have failed').and('[not] to satisfy', {
- failures: expect.it('to have an item satisfying', {
+ errors.forEach((error) => {
+ expect(result, "[not] to have failed").and("[not] to satisfy", {
+ failures: expect.it("to have an item satisfying", {
err: expect
- .it('to satisfy', error)
- .or('to satisfy', {message: error})
- })
+ .it("to satisfy", error)
+ .or("to satisfy", { message: error }),
+ }),
});
});
- }
+ },
)
.addAssertion(
- '<RawResult|SummarizedResult> [not] to contain [output] <any>',
+ "<RawResult|SummarizedResult> [not] to contain [output] <any>",
(expect, result, output) => {
- expect(result.output, '[not] to satisfy', output);
- }
+ expect(result.output, "[not] to satisfy", output);
+ },
)
.addAssertion(
- '<RawResult|SummarizedResult> to contain [output] once <any>',
+ "<RawResult|SummarizedResult> to contain [output] once <any>",
(expect, result, output) => {
- if (typeof output === 'string') {
+ if (typeof output === "string") {
output = escapeRe(output);
} else if (!(output instanceof RegExp)) {
- throw new TypeError('expected a string or regexp');
+ throw new TypeError("expected a string or regexp");
}
- output = new RegExp(output, 'g');
- expect(result.output.match(output), 'to have length', 1);
- }
+ output = new RegExp(output, "g");
+ expect(result.output.match(output), "to have length", 1);
+ },
)
.addAssertion(
- '<RawResult|SummarizedResult|JSONResult> to have [exit] code <number>',
+ "<RawResult|SummarizedResult|JSONResult> to have [exit] code <number>",
(expect, result, code) => {
- expect(result.code, 'to be', code);
- }
+ expect(result.code, "to be", code);
+ },
);
- }
+ },
};
diff --git a/test/browser-specific/esm.spec.mjs b/test/browser-specific/esm.spec.mjs
index b9b022af..48aacd33 100644
--- a/test/browser-specific/esm.spec.mjs
+++ b/test/browser-specific/esm.spec.mjs
@@ -1,9 +1,9 @@
-import './fixtures/esm.fixture.mjs';
+import "./fixtures/esm.fixture.mjs";
-it('should register a global if it did not fail', function () {
- expect(window.MOCHA_IS_OK, 'to be ok');
+it("should register a global if it did not fail", function () {
+ expect(window.MOCHA_IS_OK, "to be ok");
});
-it('should has global Mocha', function () {
- expect(window.Mocha, 'not to be', undefined);
+it("should has global Mocha", function () {
+ expect(window.Mocha, "not to be", undefined);
});
diff --git a/test/browser-specific/setup.js b/test/browser-specific/setup.js
index 61134666..940db58b 100644
--- a/test/browser-specific/setup.js
+++ b/test/browser-specific/setup.js
@@ -1,10 +1,10 @@
-'use strict';
+"use strict";
-process.stdout = require('browser-stdout')();
+process.stdout = require("browser-stdout")();
-global.expect = require('unexpected')
+global.expect = require("unexpected")
.clone()
- .use(require('unexpected-set'))
- .use(require('unexpected-map'))
- .use(require('unexpected-sinon'))
- .use(require('unexpected-eventemitter'));
+ .use(require("unexpected-set"))
+ .use(require("unexpected-map"))
+ .use(require("unexpected-sinon"))
+ .use(require("unexpected-eventemitter"));
diff --git a/test/compiler-cjs/test.js b/test/compiler-cjs/test.js
index f0032f26..698488df 100644
--- a/test/compiler-cjs/test.js
+++ b/test/compiler-cjs/test.js
@@ -1,9 +1,9 @@
-const obj = { foo: 'bar' };
+const obj = { foo: "bar" };
-describe('cjs written in esm', () => {
- it('should work', () => {
- expect(obj, 'to equal', { foo: 'bar' });
+describe("cjs written in esm", () => {
+ it("should work", () => {
+ expect(obj, "to equal", { foo: "bar" });
});
});
-export const foo = 'bar';
+export const foo = "bar";
diff --git a/test/compiler-cjs/test.ts b/test/compiler-cjs/test.ts
index eac5d130..f787ee28 100644
--- a/test/compiler-cjs/test.ts
+++ b/test/compiler-cjs/test.ts
@@ -1,9 +1,9 @@
-const obj: unknown = { foo: 'bar' };
+const obj: unknown = { foo: "bar" };
-describe('cts written in esm', () => {
- it('should work', () => {
- expect(obj, 'to equal', { foo: 'bar' });
+describe("cts written in esm", () => {
+ it("should work", () => {
+ expect(obj, "to equal", { foo: "bar" });
});
});
-export const foo = 'bar';
+export const foo = "bar";
diff --git a/test/compiler-esm/test-tla.js b/test/compiler-esm/test-tla.js
index 55705485..841a9c13 100644
--- a/test/compiler-esm/test-tla.js
+++ b/test/compiler-esm/test-tla.js
@@ -1,11 +1,11 @@
-const obj = { foo: 'bar' };
+const obj = { foo: "bar" };
-describe('esm written in esm with top-level-await', () => {
- it('should work', () => {
- expect(obj, 'to equal', { foo: 'bar' });
+describe("esm written in esm with top-level-await", () => {
+ it("should work", () => {
+ expect(obj, "to equal", { foo: "bar" });
});
});
await undefined;
-export const foo = 'bar';
+export const foo = "bar";
diff --git a/test/compiler-esm/test-tla.mjs b/test/compiler-esm/test-tla.mjs
index 55705485..841a9c13 100644
--- a/test/compiler-esm/test-tla.mjs
+++ b/test/compiler-esm/test-tla.mjs
@@ -1,11 +1,11 @@
-const obj = { foo: 'bar' };
+const obj = { foo: "bar" };
-describe('esm written in esm with top-level-await', () => {
- it('should work', () => {
- expect(obj, 'to equal', { foo: 'bar' });
+describe("esm written in esm with top-level-await", () => {
+ it("should work", () => {
+ expect(obj, "to equal", { foo: "bar" });
});
});
await undefined;
-export const foo = 'bar';
+export const foo = "bar";
diff --git a/test/compiler-esm/test-tla.ts b/test/compiler-esm/test-tla.ts
index ec6e0e05..bb9bbcad 100644
--- a/test/compiler-esm/test-tla.ts
+++ b/test/compiler-esm/test-tla.ts
@@ -1,14 +1,14 @@
-const obj: unknown = { foo: 'bar' };
+const obj: unknown = { foo: "bar" };
enum Foo {
- Bar = 'bar',
+ Bar = "bar",
}
-describe('esm written in esm with top-level-await', () => {
- it('should work', () => {
- expect(obj, 'to equal', { foo: Foo.Bar });
+describe("esm written in esm with top-level-await", () => {
+ it("should work", () => {
+ expect(obj, "to equal", { foo: Foo.Bar });
});
});
await undefined;
-export const foo = 'bar';
+export const foo = "bar";
diff --git a/test/compiler-esm/test.js b/test/compiler-esm/test.js
index bb457784..2f4dd521 100644
--- a/test/compiler-esm/test.js
+++ b/test/compiler-esm/test.js
@@ -1,9 +1,9 @@
-const obj = { foo: 'bar' };
+const obj = { foo: "bar" };
-describe('esm written in esm', () => {
- it('should work', () => {
- expect(obj, 'to equal', { foo: 'bar' });
+describe("esm written in esm", () => {
+ it("should work", () => {
+ expect(obj, "to equal", { foo: "bar" });
});
});
-export const foo = 'bar';
+export const foo = "bar";
diff --git a/test/compiler-esm/test.mjs b/test/compiler-esm/test.mjs
index 0541b4c9..2f4dd521 100644
--- a/test/compiler-esm/test.mjs
+++ b/test/compiler-esm/test.mjs
@@ -1,9 +1,9 @@
-const obj = {foo: 'bar'};
+const obj = { foo: "bar" };
-describe('esm written in esm', () => {
- it('should work', () => {
- expect(obj, 'to equal', {foo: 'bar'});
+describe("esm written in esm", () => {
+ it("should work", () => {
+ expect(obj, "to equal", { foo: "bar" });
});
});
-export const foo = 'bar';
+export const foo = "bar";
diff --git a/test/compiler-esm/test.ts b/test/compiler-esm/test.ts
index b21a1f08..60a37c06 100644
--- a/test/compiler-esm/test.ts
+++ b/test/compiler-esm/test.ts
@@ -1,12 +1,12 @@
-const obj: unknown = { foo: 'bar' };
+const obj: unknown = { foo: "bar" };
enum Foo {
- Bar = 'bar',
-};
+ Bar = "bar",
+}
-describe('esm written in esm', () => {
- it('should work', () => {
- expect(obj, 'to equal', { foo: Foo.Bar });
+describe("esm written in esm", () => {
+ it("should work", () => {
+ expect(obj, "to equal", { foo: Foo.Bar });
});
});
-export const foo = 'bar';
+export const foo = "bar";
diff --git a/test/compiler-fixtures/esm-loader.fixture.mjs b/test/compiler-fixtures/esm-loader.fixture.mjs
index 45c0a3ff..b98a22ce 100644
--- a/test/compiler-fixtures/esm-loader.fixture.mjs
+++ b/test/compiler-fixtures/esm-loader.fixture.mjs
@@ -1,15 +1,18 @@
-import fsPromises from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
+import fsPromises from "node:fs/promises";
+import { fileURLToPath } from "node:url";
export async function load(url, context, nextLoad) {
- if (!url.includes('compiler-esm') && !url.includes('compiler-cjs')) {
+ if (!url.includes("compiler-esm") && !url.includes("compiler-cjs")) {
return nextLoad(url, context);
}
- const format = url.includes('compiler-esm') ? 'module' : 'commonjs';
- const content = await fsPromises.readFile(fileURLToPath(url + '.compiled'), 'utf8');
+ const format = url.includes("compiler-esm") ? "module" : "commonjs";
+ const content = await fsPromises.readFile(
+ fileURLToPath(url + ".compiled"),
+ "utf8",
+ );
return {
format,
source: content,
shortCircuit: true,
- }
+ };
}
diff --git a/test/compiler-fixtures/esm-only-loader/esm-loader.fixture.mjs b/test/compiler-fixtures/esm-only-loader/esm-loader.fixture.mjs
index 45c0a3ff..b98a22ce 100644
--- a/test/compiler-fixtures/esm-only-loader/esm-loader.fixture.mjs
+++ b/test/compiler-fixtures/esm-only-loader/esm-loader.fixture.mjs
@@ -1,15 +1,18 @@
-import fsPromises from 'node:fs/promises';
-import { fileURLToPath } from 'node:url';
+import fsPromises from "node:fs/promises";
+import { fileURLToPath } from "node:url";
export async function load(url, context, nextLoad) {
- if (!url.includes('compiler-esm') && !url.includes('compiler-cjs')) {
+ if (!url.includes("compiler-esm") && !url.includes("compiler-cjs")) {
return nextLoad(url, context);
}
- const format = url.includes('compiler-esm') ? 'module' : 'commonjs';
- const content = await fsPromises.readFile(fileURLToPath(url + '.compiled'), 'utf8');
+ const format = url.includes("compiler-esm") ? "module" : "commonjs";
+ const content = await fsPromises.readFile(
+ fileURLToPath(url + ".compiled"),
+ "utf8",
+ );
return {
format,
source: content,
shortCircuit: true,
- }
+ };
}
diff --git a/test/compiler-fixtures/esm-only-loader/esm.fixture.js b/test/compiler-fixtures/esm-only-loader/esm.fixture.js
index 33ed3ba5..1b34d1ac 100644
--- a/test/compiler-fixtures/esm-only-loader/esm.fixture.js
+++ b/test/compiler-fixtures/esm-only-loader/esm.fixture.js
@@ -1,3 +1,3 @@
-import Module from 'node:module';
+import Module from "node:module";
-Module.register(new URL('./esm-loader.fixture.mjs', import.meta.url));
+Module.register(new URL("./esm-loader.fixture.mjs", import.meta.url));
diff --git a/test/compiler-fixtures/esm.fixture.js b/test/compiler-fixtures/esm.fixture.js
index c7e09332..1d2ad081 100644
--- a/test/compiler-fixtures/esm.fixture.js
+++ b/test/compiler-fixtures/esm.fixture.js
@@ -1,5 +1,7 @@
-const Module = require('node:module');
-const { pathToFileURL } = require('node:url');
-const path = require('node:path');
+const Module = require("node:module");
+const { pathToFileURL } = require("node:url");
+const path = require("node:path");
-Module.register(pathToFileURL(path.resolve(__dirname, 'esm-loader.fixture.mjs')));
+Module.register(
+ pathToFileURL(path.resolve(__dirname, "esm-loader.fixture.mjs")),
+);
diff --git a/test/compiler-fixtures/foo.fixture.js b/test/compiler-fixtures/foo.fixture.js
index 01338701..1bbc2b19 100644
--- a/test/compiler-fixtures/foo.fixture.js
+++ b/test/compiler-fixtures/foo.fixture.js
@@ -1,11 +1,14 @@
-'use strict';
+"use strict";
-var fs = require('fs');
+var fs = require("fs");
-require.extensions['.foo'] = function (module, filename) {
+require.extensions[".foo"] = function (module, filename) {
var content;
- content = fs.readFileSync(filename, 'utf8');
- var test = 'describe("custom compiler",function(){ it("should work",function() { ' +
- 'expect(' + content + ', "to be", 1); }); });';
+ content = fs.readFileSync(filename, "utf8");
+ var test =
+ 'describe("custom compiler",function(){ it("should work",function() { ' +
+ "expect(" +
+ content +
+ ', "to be", 1); }); });';
return module._compile(test, filename);
};
diff --git a/test/compiler-fixtures/js.fixture.js b/test/compiler-fixtures/js.fixture.js
index 556edb7e..44bfd156 100644
--- a/test/compiler-fixtures/js.fixture.js
+++ b/test/compiler-fixtures/js.fixture.js
@@ -1,12 +1,12 @@
-'use strict';
+"use strict";
-const fs = require('fs');
+const fs = require("fs");
-const original = require.extensions['.js'];
-require.extensions['.js'] = function (module, filename) {
- if (!filename.includes('compiler-cjs')) {
+const original = require.extensions[".js"];
+require.extensions[".js"] = function (module, filename) {
+ if (!filename.includes("compiler-cjs")) {
return original(module, filename);
}
- const content = fs.readFileSync(filename + '.compiled', 'utf8');
+ const content = fs.readFileSync(filename + ".compiled", "utf8");
return module._compile(content, filename);
};
diff --git a/test/compiler-fixtures/ts.fixture.js b/test/compiler-fixtures/ts.fixture.js
index 7ea256bb..a1515f54 100644
--- a/test/compiler-fixtures/ts.fixture.js
+++ b/test/compiler-fixtures/ts.fixture.js
@@ -1,8 +1,8 @@
-'use strict';
+"use strict";
-const fs = require('fs');
+const fs = require("fs");
-require.extensions['.ts'] = function (module, filename) {
- const content = fs.readFileSync(filename + '.compiled', 'utf8');
+require.extensions[".ts"] = function (module, filename) {
+ const content = fs.readFileSync(filename + ".compiled", "utf8");
return module._compile(content, filename);
};
diff --git a/test/integration/color.spec.js b/test/integration/color.spec.js
index d713b35c..a8b93d79 100644
--- a/test/integration/color.spec.js
+++ b/test/integration/color.spec.js
@@ -1,15 +1,15 @@
-'use strict';
+"use strict";
-var childProcess = require('node:child_process');
-var path = require('node:path');
+var childProcess = require("node:child_process");
+var path = require("node:path");
-describe('mocha binary', function () {
- it('should not output colors to pipe', function (done) {
- var command = [path.join('bin', 'mocha'), '--grep', 'missing-test'];
+describe("mocha binary", function () {
+ it("should not output colors to pipe", function (done) {
+ var command = [path.join("bin", "mocha"), "--grep", "missing-test"];
childProcess.execFile(process.execPath, command, function (err, stdout) {
if (err) return done(err);
- expect(stdout, 'not to contain', '[90m');
+ expect(stdout, "not to contain", "[90m");
done();
});
diff --git a/test/integration/common-js-require.spec.js b/test/integration/common-js-require.spec.js
index 43a59d65..5aceb830 100644
--- a/test/integration/common-js-require.spec.js
+++ b/test/integration/common-js-require.spec.js
@@ -1,20 +1,20 @@
-'use strict';
+"use strict";
-const {runMochaAsync} = require('./helpers');
+const { runMochaAsync } = require("./helpers");
-describe('common js require', () => {
- it('should be able to run a test where all mocha exports are used', async () => {
- const result = await runMochaAsync('common-js-require.fixture.js', [
- '--delay'
+describe("common js require", () => {
+ it("should be able to run a test where all mocha exports are used", async () => {
+ const result = await runMochaAsync("common-js-require.fixture.js", [
+ "--delay",
]);
- expect(result.output, 'to contain', 'running before');
- expect(result.output, 'to contain', 'running suiteSetup');
- expect(result.output, 'to contain', 'running setup');
- expect(result.output, 'to contain', 'running beforeEach');
- expect(result.output, 'to contain', 'running it');
- expect(result.output, 'to contain', 'running afterEach');
- expect(result.output, 'to contain', 'running teardown');
- expect(result.output, 'to contain', 'running suiteTeardown');
- expect(result.output, 'to contain', 'running after');
+ expect(result.output, "to contain", "running before");
+ expect(result.output, "to contain", "running suiteSetup");
+ expect(result.output, "to contain", "running setup");
+ expect(result.output, "to contain", "running beforeEach");
+ expect(result.output, "to contain", "running it");
+ expect(result.output, "to contain", "running afterEach");
+ expect(result.output, "to contain", "running teardown");
+ expect(result.output, "to contain", "running suiteTeardown");
+ expect(result.output, "to contain", "running after");
});
});
diff --git a/test/integration/compiler-cjs.spec.js b/test/integration/compiler-cjs.spec.js
index 50e4e68c..ab574779 100644
--- a/test/integration/compiler-cjs.spec.js
+++ b/test/integration/compiler-cjs.spec.js
@@ -1,64 +1,62 @@
-'use strict';
+"use strict";
-var exec = require('node:child_process').exec;
-var path = require('node:path');
+var exec = require("node:child_process").exec;
+var path = require("node:path");
-describe('support CJS require.extension compilers with esm syntax', function () {
- it('should support .js extension', function (done) {
+describe("support CJS require.extension compilers with esm syntax", function () {
+ it("should support .js extension", function (done) {
exec(
'"' +
process.execPath +
'" "' +
- path.join('bin', 'mocha') +
+ path.join("bin", "mocha") +
'" -R json --require test/compiler-fixtures/js.fixture "test/compiler-cjs/*.js"',
- {cwd: path.join(__dirname, '..', '..')},
+ { cwd: path.join(__dirname, "..", "..") },
function (error, stdout) {
if (error && !stdout) {
return done(error);
}
var results = JSON.parse(stdout);
- expect(results, 'to have property', 'tests');
+ expect(results, "to have property", "tests");
var titles = [];
for (var index = 0; index < results.tests.length; index += 1) {
- expect(results.tests[index], 'to have property', 'fullTitle');
+ expect(results.tests[index], "to have property", "fullTitle");
titles.push(results.tests[index].fullTitle);
}
- expect(
- titles,
- 'to contain',
- 'cjs written in esm should work',
- ).and('to have length', 1);
+ expect(titles, "to contain", "cjs written in esm should work").and(
+ "to have length",
+ 1,
+ );
done();
- }
+ },
);
});
- it('should support .ts extension', function (done) {
+ it("should support .ts extension", function (done) {
exec(
'"' +
process.execPath +
'" "' +
- path.join('bin', 'mocha') +
+ path.join("bin", "mocha") +
'" -R json --require test/compiler-fixtures/ts.fixture "test/compiler-cjs/*.ts"',
- {cwd: path.join(__dirname, '..', '..')},
+ { cwd: path.join(__dirname, "..", "..") },
function (error, stdout) {
if (error && !stdout) {
return done(error);
}
var results = JSON.parse(stdout);
- expect(results, 'to have property', 'tests');
+ expect(results, "to have property", "tests");
var titles = [];
for (var index = 0; index < results.tests.length; index += 1) {
- expect(results.tests[index], 'to have property', 'fullTitle');
+ expect(results.tests[index], "to have property", "fullTitle");
titles.push(results.tests[index].fullTitle);
}
- expect(
- titles,
- 'to contain',
- 'cts written in esm should work',
- ).and('to have length', 1);
+ expect(titles, "to contain", "cts written in esm should work").and(
+ "to have length",
+ 1,
+ );
done();
- }
+ },
);
});
});
diff --git a/test/integration/compiler-esm-only-loader.spec.js b/test/integration/compiler-esm-only-loader.spec.js
index c2b222cf..2860eef0 100644
--- a/test/integration/compiler-esm-only-loader.spec.js
+++ b/test/integration/compiler-esm-only-loader.spec.js
@@ -1,10 +1,10 @@
-'use strict';
+"use strict";
-var exec = require('node:child_process').exec;
-var path = require('node:path');
+var exec = require("node:child_process").exec;
+var path = require("node:path");
// Regression test for https://github.com/mochajs/mocha/issues/5380
-describe('support ESM only module loader packages', function () {
+describe("support ESM only module loader packages", function () {
/**
* Load the filename using an ESM-only loader and expect things to work
* @param {string} filename Name of the file to load
@@ -15,40 +15,40 @@ describe('support ESM only module loader packages', function () {
'"' +
process.execPath +
'" "' +
- path.join('bin', 'mocha') +
+ path.join("bin", "mocha") +
`" -R json --require "@test/esm-only-loader" "${filename}"`,
- {cwd: path.join(__dirname, '..', '..')},
+ { cwd: path.join(__dirname, "..", "..") },
function (error, stdout) {
if (error && !stdout) {
return done(error);
}
var results = JSON.parse(stdout);
- expect(results, 'to have property', 'tests');
+ expect(results, "to have property", "tests");
var titles = [];
for (var index = 0; index < results.tests.length; index += 1) {
- expect(results.tests[index], 'to have property', 'fullTitle');
+ expect(results.tests[index], "to have property", "fullTitle");
titles.push(results.tests[index].fullTitle);
}
- expect(titles, 'to contain', 'esm written in esm should work')
+ expect(titles, "to contain", "esm written in esm should work")
.and(
- 'to contain',
- 'esm written in esm with top-level-await should work'
+ "to contain",
+ "esm written in esm with top-level-await should work",
)
- .and('to have length', 2);
+ .and("to have length", 2);
done();
- }
+ },
);
}
- it('should support ESM .js extension', function (done) {
- loadAndExpect('test/compiler-esm/*.js', done);
+ it("should support ESM .js extension", function (done) {
+ loadAndExpect("test/compiler-esm/*.js", done);
});
- it('should support ESM .ts extension', function (done) {
- loadAndExpect('test/compiler-esm/*.ts', done);
+ it("should support ESM .ts extension", function (done) {
+ loadAndExpect("test/compiler-esm/*.ts", done);
});
- it('should support ESM .mjs extension', function (done) {
- loadAndExpect('test/compiler-esm/*.mjs', done);
+ it("should support ESM .mjs extension", function (done) {
+ loadAndExpect("test/compiler-esm/*.mjs", done);
});
});
diff --git a/test/integration/compiler-esm.spec.js b/test/integration/compiler-esm.spec.js
index 8aca1ff2..3d6d6a1f 100644
--- a/test/integration/compiler-esm.spec.js
+++ b/test/integration/compiler-esm.spec.js
@@ -1,9 +1,9 @@
-'use strict';
+"use strict";
-var exec = require('node:child_process').exec;
-var path = require('node:path');
+var exec = require("node:child_process").exec;
+var path = require("node:path");
-describe('support ESM module loader compilers', function () {
+describe("support ESM module loader compilers", function () {
/**
* Runs `exec` on an ESM setup for the given file
* @param {string} filename Path to the file to load
@@ -14,40 +14,40 @@ describe('support ESM module loader compilers', function () {
'"' +
process.execPath +
'" "' +
- path.join('bin', 'mocha') +
+ path.join("bin", "mocha") +
`" -R json --require test/compiler-fixtures/esm.fixture "${filename}"`,
- {cwd: path.join(__dirname, '..', '..')},
+ { cwd: path.join(__dirname, "..", "..") },
function (error, stdout) {
if (error && !stdout) {
return done(error);
}
var results = JSON.parse(stdout);
- expect(results, 'to have property', 'tests');
+ expect(results, "to have property", "tests");
var titles = [];
for (var index = 0; index < results.tests.length; index += 1) {
- expect(results.tests[index], 'to have property', 'fullTitle');
+ expect(results.tests[index], "to have property", "fullTitle");
titles.push(results.tests[index].fullTitle);
}
- expect(titles, 'to contain', 'esm written in esm should work')
+ expect(titles, "to contain", "esm written in esm should work")
.and(
- 'to contain',
- 'esm written in esm with top-level-await should work'
+ "to contain",
+ "esm written in esm with top-level-await should work",
)
- .and('to have length', 2);
+ .and("to have length", 2);
done();
- }
+ },
);
}
- it('should support ESM .js extension', function (done) {
- loadAndExpect('test/compiler-esm/*.js', done);
+ it("should support ESM .js extension", function (done) {
+ loadAndExpect("test/compiler-esm/*.js", done);
});
- it('should support ESM .ts extension', function (done) {
- loadAndExpect('test/compiler-esm/*.ts', done);
+ it("should support ESM .ts extension", function (done) {
+ loadAndExpect("test/compiler-esm/*.ts", done);
});
- it('should support ESM .mjs extension', function (done) {
- loadAndExpect('test/compiler-esm/*.mjs', done);
+ it("should support ESM .mjs extension", function (done) {
+ loadAndExpect("test/compiler-esm/*.mjs", done);
});
});
diff --git a/test/integration/compiler-globbing.spec.js b/test/integration/compiler-globbing.spec.js
index 8d272b94..28d4a3c5 100644
--- a/test/integration/compiler-globbing.spec.js
+++ b/test/integration/compiler-globbing.spec.js
@@ -1,36 +1,36 @@
-'use strict';
+"use strict";
-var exec = require('node:child_process').exec;
-var path = require('node:path');
+var exec = require("node:child_process").exec;
+var path = require("node:path");
-describe('globbing like --compilers', function () {
- it('should find a file of each type', function (done) {
+describe("globbing like --compilers", function () {
+ it("should find a file of each type", function (done) {
exec(
'"' +
process.execPath +
'" "' +
- path.join('bin', 'mocha') +
+ path.join("bin", "mocha") +
'" -R json --require coffeescript/register --require test/compiler-fixtures/foo.fixture "test/compiler/*.@(coffee|foo)"',
- {cwd: path.join(__dirname, '..', '..')},
+ { cwd: path.join(__dirname, "..", "..") },
function (error, stdout) {
if (error && !stdout) {
return done(error);
}
var results = JSON.parse(stdout);
- expect(results, 'to have property', 'tests');
+ expect(results, "to have property", "tests");
var titles = [];
for (var index = 0; index < results.tests.length; index += 1) {
- expect(results.tests[index], 'to have property', 'fullTitle');
+ expect(results.tests[index], "to have property", "fullTitle");
titles.push(results.tests[index].fullTitle);
}
expect(
titles,
- 'to contain',
- 'coffeescript should work',
- 'custom compiler should work'
- ).and('to have length', 2);
+ "to contain",
+ "coffeescript should work",
+ "custom compiler should work",
+ ).and("to have length", 2);
done();
- }
+ },
);
});
});
diff --git a/test/integration/config.spec.js b/test/integration/config.spec.js
index 8f259059..7c1c8b5d 100644
--- a/test/integration/config.spec.js
+++ b/test/integration/config.spec.js
@@ -1,78 +1,78 @@
-'use strict';
+"use strict";
// This is not a "functional" test; we aren't invoking the mocha executable.
// Instead we just avoid test doubles.
-var fs = require('node:fs');
-var path = require('node:path');
-var loadConfig = require('../../lib/cli/config').loadConfig;
-
-describe('config', function () {
- it('should return the same values for all supported config types', function () {
- var configDir = path.join(__dirname, 'fixtures', 'config');
- var js = loadConfig(path.join(configDir, 'mocharc.js'));
- var cjs = loadConfig(path.join(configDir, 'mocharc.cjs'));
- var json = loadConfig(path.join(configDir, 'mocharc.json'));
- var yaml = loadConfig(path.join(configDir, 'mocharc.yaml'));
- expect(js, 'to equal', json);
- expect(js, 'to equal', cjs);
- expect(json, 'to equal', yaml);
+var fs = require("node:fs");
+var path = require("node:path");
+var loadConfig = require("../../lib/cli/config").loadConfig;
+
+describe("config", function () {
+ it("should return the same values for all supported config types", function () {
+ var configDir = path.join(__dirname, "fixtures", "config");
+ var js = loadConfig(path.join(configDir, "mocharc.js"));
+ var cjs = loadConfig(path.join(configDir, "mocharc.cjs"));
+ var json = loadConfig(path.join(configDir, "mocharc.json"));
+ var yaml = loadConfig(path.join(configDir, "mocharc.yaml"));
+ expect(js, "to equal", json);
+ expect(js, "to equal", cjs);
+ expect(json, "to equal", yaml);
});
describe('when configuring Mocha via a ".js" file', function () {
- var projRootDir = path.join(__dirname, '..', '..');
- var configDir = path.join(__dirname, 'fixtures', 'config');
- var json = loadConfig(path.join(configDir, 'mocharc.json'));
+ var projRootDir = path.join(__dirname, "..", "..");
+ var configDir = path.join(__dirname, "fixtures", "config");
+ var json = loadConfig(path.join(configDir, "mocharc.json"));
- it('should load configuration given absolute path', function () {
+ it("should load configuration given absolute path", function () {
var js;
function _loadConfig() {
- js = loadConfig(path.join(configDir, 'mocharc.js'));
+ js = loadConfig(path.join(configDir, "mocharc.js"));
}
- expect(_loadConfig, 'not to throw');
- expect(js, 'to equal', json);
+ expect(_loadConfig, "not to throw");
+ expect(js, "to equal", json);
});
- it('should load configuration given cwd-relative path', function () {
+ it("should load configuration given cwd-relative path", function () {
var relConfigDir = configDir.substring(projRootDir.length + 1);
var js;
function _loadConfig() {
- js = loadConfig(path.join('.', relConfigDir, 'mocharc.js'));
+ js = loadConfig(path.join(".", relConfigDir, "mocharc.js"));
}
- expect(_loadConfig, 'not to throw');
- expect(js, 'to equal', json);
+ expect(_loadConfig, "not to throw");
+ expect(js, "to equal", json);
});
- it('should rethrow error from absolute path configuration', function () {
+ it("should rethrow error from absolute path configuration", function () {
function _loadConfig() {
- loadConfig(path.join(configDir, 'mocharcWithThrowError.js'));
+ loadConfig(path.join(configDir, "mocharcWithThrowError.js"));
}
- expect(_loadConfig, 'to throw', {
- message: /Error from mocharcWithThrowError/
+ expect(_loadConfig, "to throw", {
+ message: /Error from mocharcWithThrowError/,
});
});
- it('should rethrow error from cwd-relative path configuration', function () {
+ it("should rethrow error from cwd-relative path configuration", function () {
var relConfigDir = configDir.substring(projRootDir.length + 1);
function _loadConfig() {
- loadConfig(path.join('.', relConfigDir, 'mocharcWithThrowError.js'));
+ loadConfig(path.join(".", relConfigDir, "mocharcWithThrowError.js"));
}
- expect(_loadConfig, 'to throw', {
- message: /Error from mocharcWithThrowError/
+ expect(_loadConfig, "to throw", {
+ message: /Error from mocharcWithThrowError/,
});
});
// In other words, path does not begin with '/', './', or '../'
- describe('when path is neither absolute or relative', function () {
- var nodeModulesDir = path.join(projRootDir, 'node_modules');
- var pkgName = 'mocha-config';
+ describe("when path is neither absolute or relative", function () {
+ var nodeModulesDir = path.join(projRootDir, "node_modules");
+ var pkgName = "mocha-config";
var installedLocally = false;
var symlinkedPkg = false;
@@ -80,20 +80,20 @@ describe('config', function () {
try {
var srcPath = path.join(configDir, pkgName);
var targetPath = path.join(nodeModulesDir, pkgName);
- fs.symlinkSync(srcPath, targetPath, 'dir');
+ fs.symlinkSync(srcPath, targetPath, "dir");
symlinkedPkg = true;
installedLocally = true;
} catch (err) {
- if (err.code === 'EEXIST') {
- console.log('setup:', 'package already exists in "node_modules"');
+ if (err.code === "EEXIST") {
+ console.log("setup:", 'package already exists in "node_modules"');
installedLocally = true;
} else {
- console.error('setup failed:', err);
+ console.error("setup failed:", err);
}
}
});
- it('should load configuration given module-relative path', function () {
+ it("should load configuration given module-relative path", function () {
var js;
if (!installedLocally) {
@@ -101,11 +101,11 @@ describe('config', function () {
}
function _loadConfig() {
- js = loadConfig(path.join(pkgName, 'index.js'));
+ js = loadConfig(path.join(pkgName, "index.js"));
}
- expect(_loadConfig, 'not to throw');
- expect(js, 'to equal', json);
+ expect(_loadConfig, "not to throw");
+ expect(js, "to equal", json);
});
after(function () {
@@ -113,7 +113,7 @@ describe('config', function () {
try {
fs.unlinkSync(path.join(nodeModulesDir, pkgName));
} catch (err) {
- console.error('teardown failed:', err);
+ console.error("teardown failed:", err);
}
}
});
diff --git a/test/integration/deprecate.spec.js b/test/integration/deprecate.spec.js
index 52e231ac..20345330 100644
--- a/test/integration/deprecate.spec.js
+++ b/test/integration/deprecate.spec.js
@@ -1,13 +1,13 @@
-'use strict';
+"use strict";
-var assert = require('node:assert');
-var run = require('./helpers').runMocha;
+var assert = require("node:assert");
+var run = require("./helpers").runMocha;
var args = [];
-describe('utils.deprecate test', function () {
- it('should print unique deprecation only once', function (done) {
+describe("utils.deprecate test", function () {
+ it("should print unique deprecation only once", function (done) {
run(
- 'deprecate.fixture.js',
+ "deprecate.fixture.js",
args,
function (err, res) {
if (err) {
@@ -17,7 +17,7 @@ describe('utils.deprecate test', function () {
assert.strictEqual(result.length, 2);
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
});
diff --git a/test/integration/diffs.spec.js b/test/integration/diffs.spec.js
index 0224715a..2b4b70a0 100644
--- a/test/integration/diffs.spec.js
+++ b/test/integration/diffs.spec.js
@@ -1,9 +1,9 @@
-'use strict';
+"use strict";
-var helpers = require('./helpers');
+var helpers = require("./helpers");
var run = helpers.runMocha;
-var fs = require('node:fs');
-var path = require('node:path');
+var fs = require("node:fs");
+var path = require("node:path");
/**
* Returns an array of diffs corresponding to exceptions thrown from specs,
@@ -16,7 +16,7 @@ function getDiffs(output) {
var diffs, i, inDiff, inStackTrace;
diffs = [];
- output.split('\n').forEach(function (line) {
+ output.split("\n").forEach(function (line) {
if (line.match(/^\s{2}\d+\)/)) {
// New spec, e.g. "1) spec title"
diffs.push([]);
@@ -26,7 +26,7 @@ function getDiffs(output) {
} else if (!diffs.length || inStackTrace) {
// Haven't encountered a spec yet
// or we're in the middle of a stack trace
- } else if (line.indexOf('+ expected - actual') !== -1) {
+ } else if (line.indexOf("+ expected - actual") !== -1) {
inDiff = true;
} else if (line.match(/at Context/)) {
// At the start of a stack trace
@@ -42,7 +42,7 @@ function getDiffs(output) {
.filter(function (line) {
return line.trim().length;
})
- .join('\n');
+ .join("\n");
});
}
@@ -53,48 +53,48 @@ function getDiffs(output) {
*/
function getExpectedOutput() {
var output = fs
- .readFileSync(path.join(__dirname, 'fixtures', 'diffs', 'output'), 'UTF8')
- .replace(/\r\n/g, '\n');
+ .readFileSync(path.join(__dirname, "fixtures", "diffs", "output"), "UTF8")
+ .replace(/\r\n/g, "\n");
// Diffs are delimited in file by "// DIFF"
return output
.split(/\s*\/\/ DIFF/)
.slice(1)
.map(function (diff) {
- return diff.split('\n').filter(Boolean).join('\n');
+ return diff.split("\n").filter(Boolean).join("\n");
});
}
-describe('diffs', function () {
+describe("diffs", function () {
var diffs, expected;
before(function (done) {
- run('diffs/diffs.fixture.js', [], function (err, res) {
+ run("diffs/diffs.fixture.js", [], function (err, res) {
if (err) {
done(err);
return;
}
expected = getExpectedOutput();
- diffs = getDiffs(res.output.replace(/\r\n/g, '\n'));
+ diffs = getDiffs(res.output.replace(/\r\n/g, "\n"));
done();
});
});
[
- 'should display a diff for small strings',
- 'should display a diff of canonicalized objects',
- 'should display a diff for medium strings',
- 'should display a diff for entire object dumps',
- 'should display a diff for multi-line strings',
- 'should display a diff for entire object dumps',
- 'should display a full-comparison with escaped special characters',
- 'should display a word diff for large strings',
- 'should work with objects',
- 'should show value diffs and not be affected by commas',
- 'should display diff by data and not like an objects'
+ "should display a diff for small strings",
+ "should display a diff of canonicalized objects",
+ "should display a diff for medium strings",
+ "should display a diff for entire object dumps",
+ "should display a diff for multi-line strings",
+ "should display a diff for entire object dumps",
+ "should display a full-comparison with escaped special characters",
+ "should display a word diff for large strings",
+ "should work with objects",
+ "should show value diffs and not be affected by commas",
+ "should display diff by data and not like an objects",
].forEach(function (title, i) {
it(title, function () {
- expect(diffs[i], 'to be', expected[i]);
+ expect(diffs[i], "to be", expected[i]);
});
});
});
diff --git a/test/integration/duplicate-arguments.spec.js b/test/integration/duplicate-arguments.spec.js
index 0e83e043..2107533f 100644
--- a/test/integration/duplicate-arguments.spec.js
+++ b/test/integration/duplicate-arguments.spec.js
@@ -1,36 +1,36 @@
-'use strict';
+"use strict";
-var runMochaJSON = require('./helpers').runMochaJSON;
+var runMochaJSON = require("./helpers").runMochaJSON;
-describe('when non-array argument is provided multiple times', function () {
- describe('when the same argument name is used', function () {
- it('should prefer the last value', function (done) {
+describe("when non-array argument is provided multiple times", function () {
+ describe("when the same argument name is used", function () {
+ it("should prefer the last value", function (done) {
runMochaJSON(
- 'passing-sync',
- ['--no-async-only', '--async-only', '--no-async-only'],
+ "passing-sync",
+ ["--no-async-only", "--async-only", "--no-async-only"],
function (err, result) {
if (err) {
return done(err);
}
- expect(result, 'to have passed');
+ expect(result, "to have passed");
done();
- }
+ },
);
});
});
- describe('when a different argument name is used', function () {
- it('should prefer the last value', function (done) {
+ describe("when a different argument name is used", function () {
+ it("should prefer the last value", function (done) {
runMochaJSON(
- 'passing-async',
- ['--timeout', '100', '-t', '10'],
+ "passing-async",
+ ["--timeout", "100", "-t", "10"],
function (err, result) {
if (err) {
return done(err);
}
- expect(result, 'to have failed');
+ expect(result, "to have failed");
done();
- }
+ },
);
});
});
diff --git a/test/integration/esm.spec.js b/test/integration/esm.spec.js
index ecce7033..3d8b143e 100644
--- a/test/integration/esm.spec.js
+++ b/test/integration/esm.spec.js
@@ -1,105 +1,105 @@
-'use strict';
-var path = require('node:path');
-const {runMochaJSON: run, runMochaAsync} = require('./helpers');
+"use strict";
+var path = require("node:path");
+const { runMochaJSON: run, runMochaAsync } = require("./helpers");
var args = [];
-describe('esm', function () {
- it('should pass a passing esm test that uses esm', function (done) {
- var fixture = 'esm/esm-success.fixture.mjs';
+describe("esm", function () {
+ it("should pass a passing esm test that uses esm", function (done) {
+ var fixture = "esm/esm-success.fixture.mjs";
run(fixture, args, function (err, result) {
if (err) {
done(err);
return;
}
- expect(result, 'to have passed test count', 1);
+ expect(result, "to have passed test count", 1);
done();
});
});
- it('should fail a failing esm test that uses esm', function (done) {
- var fixture = 'esm/esm-failure.fixture.mjs';
+ it("should fail a failing esm test that uses esm", function (done) {
+ var fixture = "esm/esm-failure.fixture.mjs";
run(fixture, args, function (err, result) {
if (err) {
done(err);
return;
}
- expect(result, 'to have failed test count', 1).and(
- 'to have failed test',
- 'should use a function from an esm, and fail'
+ expect(result, "to have failed test count", 1).and(
+ "to have failed test",
+ "should use a function from an esm, and fail",
);
done();
});
});
- it('should show file location when there is a syntax error in the test', async function () {
- var fixture = 'esm/syntax-error/esm-syntax-error.fixture.mjs';
- const err = await runMochaAsync(fixture, args, {stdio: 'pipe'}).catch(
- err => err
+ it("should show file location when there is a syntax error in the test", async function () {
+ var fixture = "esm/syntax-error/esm-syntax-error.fixture.mjs";
+ const err = await runMochaAsync(fixture, args, { stdio: "pipe" }).catch(
+ (err) => err,
);
- expect(err.output, 'to contain', 'SyntaxError').and(
- 'to contain',
- 'esm-syntax-error.fixture.mjs'
+ expect(err.output, "to contain", "SyntaxError").and(
+ "to contain",
+ "esm-syntax-error.fixture.mjs",
);
});
- it('should recognize esm files ending with .js due to package.json type flag', function (done) {
- var fixture = 'esm/js-folder/esm-in-js.fixture.js';
+ it("should recognize esm files ending with .js due to package.json type flag", function (done) {
+ var fixture = "esm/js-folder/esm-in-js.fixture.js";
run(fixture, args, function (err, result) {
if (err) {
done(err);
return;
}
- expect(result, 'to have passed test count', 1);
+ expect(result, "to have passed test count", 1);
done();
});
});
it('should enable requiring/loading a cjs module with "dir" as filename', async function () {
- var fixture = 'esm/test-that-uses-dir-cjs-require.fixture.js';
+ var fixture = "esm/test-that-uses-dir-cjs-require.fixture.js";
const result = await runMochaAsync(
fixture,
- ['--require', path.resolve(__dirname, './fixtures/esm/dir-cjs-require')],
- {stdio: 'pipe'}
+ ["--require", path.resolve(__dirname, "./fixtures/esm/dir-cjs-require")],
+ { stdio: "pipe" },
);
- expect(result, 'to have passed test count', 1);
+ expect(result, "to have passed test count", 1);
});
- it('should throw an ERR_MODULE_NOT_FOUND and not ERR_REQUIRE_ESM if file imports a non-existing module', async function () {
+ it("should throw an ERR_MODULE_NOT_FOUND and not ERR_REQUIRE_ESM if file imports a non-existing module", async function () {
const fixture =
- 'esm/type-module/test-that-imports-non-existing-module.fixture.js';
+ "esm/type-module/test-that-imports-non-existing-module.fixture.js";
- const err = await runMochaAsync(fixture, ['--unhandled-rejections=warn'], {
- stdio: 'pipe'
- }).catch(err => err);
+ const err = await runMochaAsync(fixture, ["--unhandled-rejections=warn"], {
+ stdio: "pipe",
+ }).catch((err) => err);
- expect(err.output, 'to contain', 'ERR_MODULE_NOT_FOUND').and(
- 'to contain',
- 'test-that-imports-non-existing-module'
+ expect(err.output, "to contain", "ERR_MODULE_NOT_FOUND").and(
+ "to contain",
+ "test-that-imports-non-existing-module",
);
});
- it('should throw an ERR_MODULE_NOT_FOUND and not ERR_REQUIRE_ESM if file imports a non-existing module with a loader', async function () {
+ it("should throw an ERR_MODULE_NOT_FOUND and not ERR_REQUIRE_ESM if file imports a non-existing module with a loader", async function () {
const fixture =
- 'esm/loader-with-module-not-found/test-that-imports-non-existing-module.fixture.ts';
+ "esm/loader-with-module-not-found/test-that-imports-non-existing-module.fixture.ts";
const err = await runMochaAsync(
fixture,
[
- '--unhandled-rejections=warn',
- '--loader=./test/integration/fixtures/esm/loader-with-module-not-found/loader-that-recognizes-ts.mjs'
+ "--unhandled-rejections=warn",
+ "--loader=./test/integration/fixtures/esm/loader-with-module-not-found/loader-that-recognizes-ts.mjs",
],
{
- stdio: 'pipe'
- }
- ).catch(err => err);
+ stdio: "pipe",
+ },
+ ).catch((err) => err);
- expect(err.output, 'to contain', 'ERR_MODULE_NOT_FOUND').and(
- 'to contain',
- 'non-existent-package'
+ expect(err.output, "to contain", "ERR_MODULE_NOT_FOUND").and(
+ "to contain",
+ "non-existent-package",
);
});
});
diff --git a/test/integration/events.spec.js b/test/integration/events.spec.js
index b1ec4b5b..57264e36 100644
--- a/test/integration/events.spec.js
+++ b/test/integration/events.spec.js
@@ -1,98 +1,98 @@
-'use strict';
+"use strict";
-var helpers = require('./helpers');
+var helpers = require("./helpers");
var runMochaJSON = helpers.runMochaJSON;
-describe('event order', function () {
- describe('trivial test case', function () {
- it('should assert trivial event order', function (done) {
- runMochaJSON('runner/events-basic.fixture.js', [], function (err, res) {
+describe("event order", function () {
+ describe("trivial test case", function () {
+ it("should assert trivial event order", function (done) {
+ runMochaJSON("runner/events-basic.fixture.js", [], function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have passed')
- .and('to have passed test count', 2)
- .and('to have passed test order', 'test A', 'test B')
- .and('to have failed test count', 0);
+ expect(res, "to have passed")
+ .and("to have passed test count", 2)
+ .and("to have passed test order", "test A", "test B")
+ .and("to have failed test count", 0);
done();
});
});
});
- describe('--bail test case', function () {
- it('should assert --bail event order', function (done) {
+ describe("--bail test case", function () {
+ it("should assert --bail event order", function (done) {
runMochaJSON(
- 'runner/events-bail.fixture.js',
- ['--bail'],
+ "runner/events-bail.fixture.js",
+ ["--bail"],
function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have failed with error', 'error test A')
- .and('to have failed test count', 1)
- .and('to have passed test count', 0);
+ expect(res, "to have failed with error", "error test A")
+ .and("to have failed test count", 1)
+ .and("to have passed test count", 0);
done();
- }
+ },
);
});
});
- describe('--retries test case', function () {
- it('should assert --retries event order', function (done) {
+ describe("--retries test case", function () {
+ it("should assert --retries event order", function (done) {
runMochaJSON(
- 'runner/events-retries.fixture.js',
- ['--retries', '1'],
+ "runner/events-retries.fixture.js",
+ ["--retries", "1"],
function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have failed with error', 'error test A')
- .and('to have failed test count', 1)
- .and('to have passed test count', 0);
+ expect(res, "to have failed with error", "error test A")
+ .and("to have failed test count", 1)
+ .and("to have passed test count", 0);
done();
- }
+ },
);
});
});
- describe('--delay test case', function () {
- it('should assert --delay event order', function (done) {
+ describe("--delay test case", function () {
+ it("should assert --delay event order", function (done) {
runMochaJSON(
- 'runner/events-delay.fixture.js',
- ['--delay'],
+ "runner/events-delay.fixture.js",
+ ["--delay"],
function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have passed')
- .and('to have passed test count', 2)
- .and('to have passed test order', 'test A', 'test B')
- .and('to have failed test count', 0);
+ expect(res, "to have passed")
+ .and("to have passed test count", 2)
+ .and("to have passed test order", "test A", "test B")
+ .and("to have failed test count", 0);
done();
- }
+ },
);
});
});
- describe('--retries and --bail test case', function () {
- it('should assert --retries event order', function (done) {
+ describe("--retries and --bail test case", function () {
+ it("should assert --retries event order", function (done) {
runMochaJSON(
- 'runner/events-bail-retries.fixture.js',
- ['--retries', '1', '--bail'],
+ "runner/events-bail-retries.fixture.js",
+ ["--retries", "1", "--bail"],
function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have failed with error', 'error test A')
- .and('to have failed test count', 1)
- .and('to have passed test count', 0);
+ expect(res, "to have failed with error", "error test A")
+ .and("to have failed test count", 1)
+ .and("to have passed test count", 0);
done();
- }
+ },
);
});
});
diff --git a/test/integration/file-utils.spec.js b/test/integration/file-utils.spec.js
index 67ca1be4..41191e42 100644
--- a/test/integration/file-utils.spec.js
+++ b/test/integration/file-utils.spec.js
@@ -1,13 +1,13 @@
-'use strict';
+"use strict";
-const lookupFiles = require('../../lib/cli/lookup-files');
-const {existsSync, symlinkSync, renameSync} = require('node:fs');
-const path = require('node:path');
-const {touchFile, createTempDir} = require('./helpers');
+const lookupFiles = require("../../lib/cli/lookup-files");
+const { existsSync, symlinkSync, renameSync } = require("node:fs");
+const path = require("node:path");
+const { touchFile, createTempDir } = require("./helpers");
-const SYMLINK_SUPPORT = process.platform !== 'win32';
+const SYMLINK_SUPPORT = process.platform !== "win32";
-describe('file utils', function () {
+describe("file utils", function () {
let tmpDir;
let removeTempDir;
let tmpFile;
@@ -17,11 +17,11 @@ describe('file utils', function () {
tmpDir = result.dirpath;
removeTempDir = result.removeTempDir;
- tmpFile = filepath => path.join(tmpDir, filepath);
+ tmpFile = (filepath) => path.join(tmpDir, filepath);
- touchFile(tmpFile('mocha-utils.js'));
+ touchFile(tmpFile("mocha-utils.js"));
if (SYMLINK_SUPPORT) {
- symlinkSync(tmpFile('mocha-utils.js'), tmpFile('mocha-utils-link.js'));
+ symlinkSync(tmpFile("mocha-utils.js"), tmpFile("mocha-utils-link.js"));
}
});
@@ -29,126 +29,126 @@ describe('file utils', function () {
return removeTempDir();
});
- describe('lookupFiles()', function () {
- it('should not return broken symlink file path', function () {
+ describe("lookupFiles()", function () {
+ it("should not return broken symlink file path", function () {
if (!SYMLINK_SUPPORT) {
return this.skip();
}
expect(
- lookupFiles(tmpDir, ['js'], false),
- 'to contain',
- tmpFile('mocha-utils-link.js'),
- tmpFile('mocha-utils.js')
- ).and('to have length', 2);
- expect(existsSync(tmpFile('mocha-utils-link.js')), 'to be', true);
- renameSync(tmpFile('mocha-utils.js'), tmpFile('bob'));
- expect(existsSync(tmpFile('mocha-utils-link.js')), 'to be', false);
- expect(lookupFiles(tmpDir, ['js'], false), 'to equal', []);
+ lookupFiles(tmpDir, ["js"], false),
+ "to contain",
+ tmpFile("mocha-utils-link.js"),
+ tmpFile("mocha-utils.js"),
+ ).and("to have length", 2);
+ expect(existsSync(tmpFile("mocha-utils-link.js")), "to be", true);
+ renameSync(tmpFile("mocha-utils.js"), tmpFile("bob"));
+ expect(existsSync(tmpFile("mocha-utils-link.js")), "to be", false);
+ expect(lookupFiles(tmpDir, ["js"], false), "to equal", []);
});
it('should accept a glob "path" value', function () {
- const res = lookupFiles(tmpFile('mocha-utils*'), ['js'], false).map(
- foundFilepath => path.normalize(foundFilepath)
+ const res = lookupFiles(tmpFile("mocha-utils*"), ["js"], false).map(
+ (foundFilepath) => path.normalize(foundFilepath),
);
let expectedLength = 0;
- let ex = expect(res, 'to contain', tmpFile('mocha-utils.js'));
+ let ex = expect(res, "to contain", tmpFile("mocha-utils.js"));
expectedLength++;
if (SYMLINK_SUPPORT) {
- ex = ex.and('to contain', tmpFile('mocha-utils-link.js'));
+ ex = ex.and("to contain", tmpFile("mocha-utils-link.js"));
expectedLength++;
}
- ex.and('to have length', expectedLength);
+ ex.and("to have length", expectedLength);
});
- describe('when given `extension` option', function () {
- describe('when provided a directory for the filepath', function () {
+ describe("when given `extension` option", function () {
+ describe("when provided a directory for the filepath", function () {
let filepath;
beforeEach(async function () {
- filepath = tmpFile('mocha-utils-text.txt');
+ filepath = tmpFile("mocha-utils-text.txt");
touchFile(filepath);
});
- describe('when `extension` option has leading dot', function () {
- it('should find the file w/ the extension', function () {
- expect(lookupFiles(tmpDir, ['.txt']), 'to equal', [filepath]);
+ describe("when `extension` option has leading dot", function () {
+ it("should find the file w/ the extension", function () {
+ expect(lookupFiles(tmpDir, [".txt"]), "to equal", [filepath]);
});
});
- describe('when `extension` option has no leading dot', function () {
- it('should find the file w/ the extension', function () {
- expect(lookupFiles(tmpDir, ['txt']), 'to equal', [filepath]);
+ describe("when `extension` option has no leading dot", function () {
+ it("should find the file w/ the extension", function () {
+ expect(lookupFiles(tmpDir, ["txt"]), "to equal", [filepath]);
});
});
- describe('when directory contains file without multipart extension', function () {
+ describe("when directory contains file without multipart extension", function () {
let filepath;
beforeEach(function () {
- filepath = tmpFile('mocha-utils-test.js');
+ filepath = tmpFile("mocha-utils-test.js");
touchFile(filepath);
});
- describe('when provided multipart `extension` option', function () {
- describe('when `extension` option has no leading dot', function () {
- it('should not match the filepath', function () {
+ describe("when provided multipart `extension` option", function () {
+ describe("when `extension` option has no leading dot", function () {
+ it("should not match the filepath", function () {
expect(
- lookupFiles(tmpDir, ['test.js']).map(filepath =>
- path.normalize(filepath)
+ lookupFiles(tmpDir, ["test.js"]).map((filepath) =>
+ path.normalize(filepath),
),
- 'to equal',
- []
+ "to equal",
+ [],
);
});
});
- describe('when `extension` option has a leading dot', function () {
- it('should not match the filepath', function () {
+ describe("when `extension` option has a leading dot", function () {
+ it("should not match the filepath", function () {
expect(
- lookupFiles(tmpDir, ['.test.js']).map(filepath =>
- path.normalize(filepath)
+ lookupFiles(tmpDir, [".test.js"]).map((filepath) =>
+ path.normalize(filepath),
),
- 'to equal',
- []
+ "to equal",
+ [],
);
});
});
});
});
- describe('when directory contains matching file having a multipart extension', function () {
+ describe("when directory contains matching file having a multipart extension", function () {
let filepath;
beforeEach(function () {
- filepath = tmpFile('mocha-utils.test.js');
+ filepath = tmpFile("mocha-utils.test.js");
touchFile(filepath);
});
- describe('when provided multipart `extension` option', function () {
- describe('when `extension` option has no leading dot', function () {
- it('should find the matching file', function () {
+ describe("when provided multipart `extension` option", function () {
+ describe("when `extension` option has no leading dot", function () {
+ it("should find the matching file", function () {
expect(
- lookupFiles(tmpDir, ['test.js']).map(filepath =>
- path.normalize(filepath)
+ lookupFiles(tmpDir, ["test.js"]).map((filepath) =>
+ path.normalize(filepath),
),
- 'to equal',
- [filepath]
+ "to equal",
+ [filepath],
);
});
});
- describe('when `extension` option has a leading dot', function () {
- it('should find the matching file', function () {
+ describe("when `extension` option has a leading dot", function () {
+ it("should find the matching file", function () {
expect(
- lookupFiles(tmpDir, ['.test.js']).map(filepath =>
- path.normalize(filepath)
+ lookupFiles(tmpDir, [".test.js"]).map((filepath) =>
+ path.normalize(filepath),
),
- 'to equal',
- [filepath]
+ "to equal",
+ [filepath],
);
});
});
@@ -157,117 +157,117 @@ describe('file utils', function () {
});
});
- describe('when provided a filepath with no extension', function () {
+ describe("when provided a filepath with no extension", function () {
let filepath;
beforeEach(async function () {
- filepath = tmpFile('mocha-utils.ts');
+ filepath = tmpFile("mocha-utils.ts");
touchFile(filepath);
});
- describe('when `extension` option has a leading dot', function () {
- describe('when only provided a single extension', function () {
- it('should append provided extensions and find only the matching file', function () {
+ describe("when `extension` option has a leading dot", function () {
+ describe("when only provided a single extension", function () {
+ it("should append provided extensions and find only the matching file", function () {
expect(
- lookupFiles(tmpFile('mocha-utils'), ['.js']).map(foundFilepath =>
- path.normalize(foundFilepath)
+ lookupFiles(tmpFile("mocha-utils"), [".js"]).map(
+ (foundFilepath) => path.normalize(foundFilepath),
),
- 'to equal',
- [tmpFile('mocha-utils.js')]
+ "to equal",
+ [tmpFile("mocha-utils.js")],
);
});
});
- describe('when provided multiple extensions', function () {
- it('should append provided extensions and find all matching files', function () {
+ describe("when provided multiple extensions", function () {
+ it("should append provided extensions and find all matching files", function () {
expect(
- lookupFiles(tmpFile('mocha-utils'), ['.js', '.ts']).map(
- foundFilepath => path.normalize(foundFilepath)
+ lookupFiles(tmpFile("mocha-utils"), [".js", ".ts"]).map(
+ (foundFilepath) => path.normalize(foundFilepath),
),
- 'to contain',
- tmpFile('mocha-utils.js'),
- filepath
- ).and('to have length', 2);
+ "to contain",
+ tmpFile("mocha-utils.js"),
+ filepath,
+ ).and("to have length", 2);
});
});
});
- describe('when `extension` option has no leading dot', function () {
- describe('when only provided a single extension', function () {
- it('should append provided extensions and find only the matching file', function () {
+ describe("when `extension` option has no leading dot", function () {
+ describe("when only provided a single extension", function () {
+ it("should append provided extensions and find only the matching file", function () {
expect(
- lookupFiles(tmpFile('mocha-utils'), ['js']).map(foundFilepath =>
- path.normalize(foundFilepath)
+ lookupFiles(tmpFile("mocha-utils"), ["js"]).map((foundFilepath) =>
+ path.normalize(foundFilepath),
),
- 'to equal',
- [tmpFile('mocha-utils.js')]
+ "to equal",
+ [tmpFile("mocha-utils.js")],
);
});
});
- describe('when provided multiple extensions', function () {
- it('should append provided extensions and find all matching files', function () {
+ describe("when provided multiple extensions", function () {
+ it("should append provided extensions and find all matching files", function () {
expect(
- lookupFiles(tmpFile('mocha-utils'), ['js', 'ts']).map(
- foundFilepath => path.normalize(foundFilepath)
+ lookupFiles(tmpFile("mocha-utils"), ["js", "ts"]).map(
+ (foundFilepath) => path.normalize(foundFilepath),
),
- 'to contain',
- tmpFile('mocha-utils.js'),
- filepath
- ).and('to have length', 2);
+ "to contain",
+ tmpFile("mocha-utils.js"),
+ filepath,
+ ).and("to have length", 2);
});
});
});
- describe('when `extension` option is multipart', function () {
+ describe("when `extension` option is multipart", function () {
let filepath;
beforeEach(function () {
- filepath = tmpFile('mocha-utils.test.js');
+ filepath = tmpFile("mocha-utils.test.js");
touchFile(filepath);
});
- describe('when `extension` option has no leading dot', function () {
- it('should append provided extension and find only the matching file', function () {
+ describe("when `extension` option has no leading dot", function () {
+ it("should append provided extension and find only the matching file", function () {
expect(
- lookupFiles(tmpFile('mocha-utils'), ['test.js']).map(
- foundFilepath => path.normalize(foundFilepath)
+ lookupFiles(tmpFile("mocha-utils"), ["test.js"]).map(
+ (foundFilepath) => path.normalize(foundFilepath),
),
- 'to equal',
- [filepath]
+ "to equal",
+ [filepath],
);
});
});
- describe('when `extension` option has leading dot', function () {
- it('should append provided extension and find only the matching file', function () {
+ describe("when `extension` option has leading dot", function () {
+ it("should append provided extension and find only the matching file", function () {
expect(
- lookupFiles(tmpFile('mocha-utils'), ['.test.js']).map(
- foundFilepath => path.normalize(foundFilepath)
+ lookupFiles(tmpFile("mocha-utils"), [".test.js"]).map(
+ (foundFilepath) => path.normalize(foundFilepath),
),
- 'to equal',
- [filepath]
+ "to equal",
+ [filepath],
);
});
});
});
});
- describe('when no files match', function () {
- it('should throw an exception', function () {
- expect(() => lookupFiles(tmpFile('mocha-utils')), 'to throw', {
- name: 'Error',
- code: 'ERR_MOCHA_NO_FILES_MATCH_PATTERN'
+ describe("when no files match", function () {
+ it("should throw an exception", function () {
+ expect(() => lookupFiles(tmpFile("mocha-utils")), "to throw", {
+ name: "Error",
+ code: "ERR_MOCHA_NO_FILES_MATCH_PATTERN",
});
});
});
- describe('when looking up a directory and no extensions provided', function () {
- it('should throw', function () {
- expect(() => lookupFiles(tmpDir), 'to throw', {
- name: 'TypeError',
- code: 'ERR_MOCHA_INVALID_ARG_TYPE',
- argument: 'extensions'
+ describe("when looking up a directory and no extensions provided", function () {
+ it("should throw", function () {
+ expect(() => lookupFiles(tmpDir), "to throw", {
+ name: "TypeError",
+ code: "ERR_MOCHA_INVALID_ARG_TYPE",
+ argument: "extensions",
});
});
});
diff --git a/test/integration/glob.spec.js b/test/integration/glob.spec.js
index f3fdedcd..a6ccbe47 100644
--- a/test/integration/glob.spec.js
+++ b/test/integration/glob.spec.js
@@ -1,174 +1,174 @@
-'use strict';
+"use strict";
-var exec = require('node:child_process').exec;
-var path = require('node:path');
+var exec = require("node:child_process").exec;
+var path = require("node:path");
var node = '"' + process.execPath + '"';
-describe('globbing', function () {
- describe('by the shell', function () {
- it('should find the first level test', function (done) {
+describe("globbing", function () {
+ describe("by the shell", function () {
+ it("should find the first level test", function (done) {
testGlob.shouldSucceed(
- './*.js',
+ "./*.js",
function (results) {
expect(
results.stdout,
- 'to contain',
- '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,'
+ "to contain",
+ '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,',
);
},
- done
+ done,
);
});
- it('should not find a non-matching pattern', function (done) {
+ it("should not find a non-matching pattern", function (done) {
testGlob.shouldFail(
- './*-none.js',
+ "./*-none.js",
function (results) {
expect(
results.stderr,
- 'to contain',
- 'Error: No test files found: "./*-none.js"'
+ "to contain",
+ 'Error: No test files found: "./*-none.js"',
);
},
- done
+ done,
);
});
- it('should handle multiple non-matching patterns', function (done) {
+ it("should handle multiple non-matching patterns", function (done) {
testGlob.shouldFail(
- './*-none.js ./*-none-twice.js',
+ "./*-none.js ./*-none-twice.js",
function (results) {
- expect(results.stderr, 'to contain', 'Error: No test files found');
- expect(results.stderr, 'not to contain', '*-none');
+ expect(results.stderr, "to contain", "Error: No test files found");
+ expect(results.stderr, "not to contain", "*-none");
},
- done
+ done,
);
});
- it('should handle both matching and non-matching patterns in the same command', function (done) {
+ it("should handle both matching and non-matching patterns in the same command", function (done) {
testGlob.shouldSucceed(
- './*.js ./*-none.js',
+ "./*.js ./*-none.js",
function (results) {
expect(
results.stdout,
- 'to contain',
- '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,'
+ "to contain",
+ '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,',
);
expect(
results.stderr,
- 'to contain',
- 'Warning: Cannot find any files matching pattern'
+ "to contain",
+ "Warning: Cannot find any files matching pattern",
);
},
- done
+ done,
);
});
});
- describe('by Mocha', function () {
- it('should find the first level test', function (done) {
+ describe("by Mocha", function () {
+ it("should find the first level test", function (done) {
testGlob.shouldSucceed(
'"./*.js"',
function (results) {
expect(
results.stdout,
- 'to contain',
- '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,'
+ "to contain",
+ '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,',
);
},
- done
+ done,
);
});
- it('should not find a non-matching pattern', function (done) {
+ it("should not find a non-matching pattern", function (done) {
testGlob.shouldFail(
'"./*-none.js"',
function (results) {
expect(
results.stderr,
- 'to contain',
- 'Error: No test files found: "./*-none.js"'
+ "to contain",
+ 'Error: No test files found: "./*-none.js"',
);
},
- done
+ done,
);
});
- it('should handle multiple non-matching patterns', function (done) {
+ it("should handle multiple non-matching patterns", function (done) {
testGlob.shouldFail(
'"./*-none.js" "./*-none-twice.js"',
function (results) {
- expect(results.stderr, 'to contain', 'Error: No test files found');
+ expect(results.stderr, "to contain", "Error: No test files found");
},
- done
+ done,
);
});
- it('should handle both matching and non-matching patterns in the same command', function (done) {
+ it("should handle both matching and non-matching patterns in the same command", function (done) {
testGlob.shouldSucceed(
'"./*.js" "./*-none.js"',
function (results) {
expect(
results.stdout,
- 'to contain',
- '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,'
+ "to contain",
+ '["end",{"suites":1,"tests":1,"passes":1,"pending":0,"failures":0,',
);
expect(
results.stderr,
- 'to contain',
- 'Warning: Cannot find any files matching pattern'
+ "to contain",
+ "Warning: Cannot find any files matching pattern",
);
},
- done
+ done,
);
});
- describe('double-starred', function () {
- it('should find the tests on multiple levels', function (done) {
+ describe("double-starred", function () {
+ it("should find the tests on multiple levels", function (done) {
testGlob.shouldSucceed(
'"./**/*.js"',
function (results) {
expect(
results.stdout,
- 'to contain',
- '["end",{"suites":2,"tests":2,"passes":2,"pending":0,"failures":0,'
+ "to contain",
+ '["end",{"suites":2,"tests":2,"passes":2,"pending":0,"failures":0,',
);
},
- done
+ done,
);
});
- it('should not find a non-matching pattern', function (done) {
+ it("should not find a non-matching pattern", function (done) {
testGlob.shouldFail(
'"./**/*-none.js"',
function (results) {
expect(
results.stderr,
- 'to contain',
- 'Error: No test files found: "./**/*-none.js"'
+ "to contain",
+ 'Error: No test files found: "./**/*-none.js"',
);
},
- done
+ done,
);
});
- it('should handle both matching and non-matching patterns in the same command', function (done) {
+ it("should handle both matching and non-matching patterns in the same command", function (done) {
testGlob.shouldSucceed(
'"./**/*.js" "./**/*-none.js"',
function (results) {
expect(
results.stdout,
- 'to contain',
- '["end",{"suites":2,"tests":2,"passes":2,"pending":0,"failures":0,'
+ "to contain",
+ '["end",{"suites":2,"tests":2,"passes":2,"pending":0,"failures":0,',
);
expect(
results.stderr,
- 'to contain',
- 'Warning: Cannot find any files matching pattern'
+ "to contain",
+ "Warning: Cannot find any files matching pattern",
);
},
- done
+ done,
);
});
});
@@ -183,8 +183,8 @@ var testGlob = {
}),
shouldFail: execMochaWith(function shouldFailWithStderr(error, stderr) {
- expect(error && error.message, 'to contain', stderr);
- })
+ expect(error && error.message, "to contain", stderr);
+ }),
};
function execMochaWith(validate) {
@@ -192,19 +192,19 @@ function execMochaWith(validate) {
exec(
node +
' "' +
- path.join('..', '..', '..', '..', 'bin', 'mocha') +
+ path.join("..", "..", "..", "..", "bin", "mocha") +
'" -R json-stream --no-config ' +
glob,
- {cwd: path.join(__dirname, 'fixtures', 'glob')},
+ { cwd: path.join(__dirname, "fixtures", "glob") },
function (error, stdout, stderr) {
try {
validate(error, stderr);
- assertOn({stdout, stderr});
+ assertOn({ stdout, stderr });
done();
} catch (assertion) {
done(assertion);
}
- }
+ },
);
};
}
diff --git a/test/integration/helpers.js b/test/integration/helpers.js
index 43f924e1..59a2d9f1 100644
--- a/test/integration/helpers.js
+++ b/test/integration/helpers.js
@@ -1,29 +1,29 @@
-'use strict';
-
-const escapeRegExp = require('escape-string-regexp');
-const os = require('node:os');
-const fs = require('node:fs');
-const fsP = require('node:fs/promises');
-const {format} = require('node:util');
-const path = require('node:path');
-const Base = require('../../lib/reporters/base');
-const debug = require('debug')('mocha:test:integration:helpers');
+"use strict";
+
+const escapeRegExp = require("escape-string-regexp");
+const os = require("node:os");
+const fs = require("node:fs");
+const fsP = require("node:fs/promises");
+const { format } = require("node:util");
+const path = require("node:path");
+const Base = require("../../lib/reporters/base");
+const debug = require("debug")("mocha:test:integration:helpers");
const SIGNAL_OFFSET = 128;
/**
* Path to `mocha` executable
*/
-const MOCHA_EXECUTABLE = require.resolve('../../bin/mocha');
+const MOCHA_EXECUTABLE = require.resolve("../../bin/mocha");
/**
* regular expression used for splitting lines based on new line / dot symbol.
*/
-const SPLIT_DOT_REPORTER_REGEXP = new RegExp('[\\n' + Base.symbols.dot + ']+');
+const SPLIT_DOT_REPORTER_REGEXP = new RegExp("[\\n" + Base.symbols.dot + "]+");
/**
* Name of "default" fixture file.
*/
-const DEFAULT_FIXTURE = '__default__';
+const DEFAULT_FIXTURE = "__default__";
/**
* Path to "default" fixture file
@@ -55,7 +55,7 @@ const DEFAULT_FIXTURE_PATH = resolveFixturePath(DEFAULT_FIXTURE);
* @returns {ChildProcess} Subprocess process
*/
function runMocha(fixturePath, args, done, opts = {}) {
- if (typeof args === 'function') {
+ if (typeof args === "function") {
opts = done;
done = args;
args = [];
@@ -70,7 +70,7 @@ function runMocha(fixturePath, args, done, opts = {}) {
done(null, getSummary(res));
},
- opts
+ opts,
);
}
@@ -90,14 +90,14 @@ function runMocha(fixturePath, args, done, opts = {}) {
* @returns {ChildProcess} Subprocess instance
*/
function runMochaJSON(fixturePath, args, done, opts) {
- if (typeof args === 'function') {
+ if (typeof args === "function") {
opts = done;
done = args;
args = [];
}
return invokeMocha(
- [...args, '--reporter', 'json', resolveFixturePath(fixturePath)],
+ [...args, "--reporter", "json", resolveFixturePath(fixturePath)],
(err, res) => {
if (err) {
return done(err);
@@ -110,16 +110,16 @@ function runMochaJSON(fixturePath, args, done, opts) {
return done(
new Error(
format(
- 'Failed to parse JSON reporter output. Error:\n%O\nResult:\n%O',
+ "Failed to parse JSON reporter output. Error:\n%O\nResult:\n%O",
err,
- res
- )
- )
+ res,
+ ),
+ ),
);
}
done(null, result);
},
- opts
+ opts,
);
}
@@ -144,7 +144,7 @@ function runMochaAsync(fixturePath, args, opts) {
}
resolve(result);
},
- opts
+ opts,
);
});
}
@@ -167,7 +167,7 @@ function runMochaJSONAsync(fixturePath, args = [], opts = {}) {
}
resolve(result);
},
- opts
+ opts,
);
});
}
@@ -180,10 +180,10 @@ function runMochaJSONAsync(fixturePath, args = [], opts = {}) {
*/
function toJSONResult(result) {
try {
- return {...JSON.parse(result.output), ...result};
+ return { ...JSON.parse(result.output), ...result };
} catch (err) {
throw new Error(
- `Couldn't parse JSON: ${err.message}\n\nOriginal result output: ${result.output}`
+ `Couldn't parse JSON: ${err.message}\n\nOriginal result output: ${result.output}`,
);
}
}
@@ -206,13 +206,13 @@ function toJSONResult(result) {
function defaultArgs(args = [DEFAULT_FIXTURE_PATH]) {
const newArgs = [
...(!args.length ? [DEFAULT_FIXTURE_PATH] : args),
- '--no-color'
+ "--no-color",
];
- if (!newArgs.some(arg => /--(no-)?bail/.test(arg))) {
- newArgs.push('--no-bail');
+ if (!newArgs.some((arg) => /--(no-)?bail/.test(arg))) {
+ newArgs.push("--no-bail");
}
- if (!newArgs.some(arg => /--(no-)?parallel/.test(arg))) {
- newArgs.push('--no-parallel');
+ if (!newArgs.some((arg) => /--(no-)?parallel/.test(arg))) {
+ newArgs.push("--no-parallel");
}
return newArgs;
}
@@ -229,7 +229,7 @@ function defaultArgs(args = [DEFAULT_FIXTURE_PATH]) {
* @returns {ChildProcess}
*/
function invokeMocha(args, done, opts = {}) {
- if (typeof args === 'function') {
+ if (typeof args === "function") {
opts = done;
done = args;
args = [];
@@ -237,7 +237,7 @@ function invokeMocha(args, done, opts = {}) {
return createSubprocess(
defaultArgs([MOCHA_EXECUTABLE].concat(args)),
done,
- opts
+ opts,
);
}
@@ -266,7 +266,7 @@ function invokeMochaAsync(args, opts = {}) {
resolve(result);
}
},
- opts
+ opts,
);
});
return [mochaProcess, resultPromise];
@@ -283,7 +283,7 @@ function invokeMochaAsync(args, opts = {}) {
* @returns {ChildProcess}
*/
function invokeNode(args, done, opts = {}) {
- if (typeof args === 'function') {
+ if (typeof args === "function") {
opts = done;
done = args;
args = [];
@@ -303,21 +303,21 @@ function invokeNode(args, done, opts = {}) {
* @returns {import('child_process').ChildProcess}
*/
function createSubprocess(args, done, opts = {}) {
- let output = '';
+ let output = "";
- if (opts === 'pipe') {
- opts = {stdio: ['inherit', 'pipe', 'pipe']};
+ if (opts === "pipe") {
+ opts = { stdio: ["inherit", "pipe", "pipe"] };
}
- const env = {...process.env};
+ const env = { ...process.env };
// prevent DEBUG from borking STDERR when piping, unless explicitly set via `opts`
delete env.DEBUG;
opts = {
cwd: process.cwd(),
- stdio: ['inherit', 'pipe', 'inherit'],
+ stdio: ["inherit", "pipe", "inherit"],
env,
- ...opts
+ ...opts,
};
/**
@@ -325,37 +325,37 @@ function createSubprocess(args, done, opts = {}) {
*/
let mocha;
if (opts.fork) {
- const {fork} = require('node:child_process');
+ const { fork } = require("node:child_process");
// to use ipc, we need a fourth item in `stdio` array.
// opts.stdio is usually an array of length 3, but it could be smaller
// (pad with `null`)
for (let i = opts.stdio.length; i < 4; i++) {
- opts.stdio.push(i === 3 ? 'ipc' : null);
+ opts.stdio.push(i === 3 ? "ipc" : null);
}
- debug('forking: %s', args.join(' '));
+ debug("forking: %s", args.join(" "));
mocha = fork(args[0], args.slice(1), opts);
} else {
- const {spawn} = require('node:child_process');
- debug('spawning: %s', [process.execPath].concat(args).join(' '));
+ const { spawn } = require("node:child_process");
+ debug("spawning: %s", [process.execPath].concat(args).join(" "));
mocha = spawn(process.execPath, args, opts);
}
- const listener = data => {
+ const listener = (data) => {
output += data;
};
- mocha.stdout.on('data', listener);
+ mocha.stdout.on("data", listener);
if (mocha.stderr) {
- mocha.stderr.on('data', listener);
+ mocha.stderr.on("data", listener);
}
- mocha.on('error', done);
+ mocha.on("error", done);
- mocha.on('close', code => {
+ mocha.on("close", (code) => {
done(null, {
output,
code,
args,
- command: args.join(' ')
+ command: args.join(" "),
});
});
@@ -363,11 +363,11 @@ function createSubprocess(args, done, opts = {}) {
* Emulate node's exit code for fatal signal. Allows tests to see the same
* exit code as the mocha cli.
*/
- mocha.on('exit', (code, signal) => {
+ mocha.on("exit", (code, signal) => {
if (signal) {
mocha.exitCode =
SIGNAL_OFFSET +
- (typeof signal == 'string' ? os.constants.signals[signal] : signal);
+ (typeof signal == "string" ? os.constants.signals[signal] : signal);
}
});
@@ -382,15 +382,15 @@ function createSubprocess(args, done, opts = {}) {
*/
function resolveFixturePath(fixture) {
if (
- path.extname(fixture) !== '.js' &&
- path.extname(fixture) !== '.mjs' &&
- path.extname(fixture) !== '.ts'
+ path.extname(fixture) !== ".js" &&
+ path.extname(fixture) !== ".mjs" &&
+ path.extname(fixture) !== ".ts"
) {
- fixture += '.fixture.js';
+ fixture += ".fixture.js";
}
return path.isAbsolute(fixture)
? fixture
- : path.resolve(__dirname, 'fixtures', fixture);
+ : path.resolve(__dirname, "fixtures", fixture);
}
/**
@@ -399,7 +399,7 @@ function resolveFixturePath(fixture) {
* @returns {Summary}
*/
function getSummary(res) {
- return ['passing', 'pending', 'failing'].reduce((summary, type) => {
+ return ["passing", "pending", "failing"].reduce((summary, type) => {
const pattern = new RegExp(` (\\d+) ${type}\\s`);
const match = pattern.exec(res.output);
summary[type] = match ? parseInt(match, 10) : 0;
@@ -426,18 +426,18 @@ function getSummary(res) {
* @returns {Promise<RawResult>}
*/
async function runMochaWatchAsync(args, opts, change) {
- if (typeof opts === 'string') {
- opts = {cwd: opts};
+ if (typeof opts === "string") {
+ opts = { cwd: opts };
}
opts = {
sleepMs: 2000,
- stdio: ['pipe', 'pipe', 'inherit'],
+ stdio: ["pipe", "pipe", "inherit"],
...opts,
- fork: process.platform === 'win32'
+ fork: process.platform === "win32",
};
const [mochaProcess, resultPromise] = invokeMochaAsync(
- [...args, '--watch'],
- opts
+ [...args, "--watch"],
+ opts,
);
await sleep(opts.sleepMs);
await change(mochaProcess);
@@ -445,10 +445,10 @@ async function runMochaWatchAsync(args, opts, change) {
if (
!(mochaProcess.connected
- ? mochaProcess.send('SIGINT')
- : mochaProcess.kill('SIGINT'))
+ ? mochaProcess.send("SIGINT")
+ : mochaProcess.kill("SIGINT"))
) {
- throw new Error('failed to send signal to subprocess');
+ throw new Error("failed to send signal to subprocess");
}
const res = await resultPromise;
@@ -478,17 +478,17 @@ async function runMochaWatchAsync(args, opts, change) {
*/
async function runMochaWatchJSONAsync(args, opts, change) {
const res = await runMochaWatchAsync(
- [...args, '--reporter', 'json'],
+ [...args, "--reporter", "json"],
opts,
- change
+ change,
);
return (
res.output
// eslint-disable-next-line no-control-regex
- .replace(/\u001b\[\?25./g, '')
- .split('\u001b[2K')
- .filter(x => x)
- .map(x => JSON.parse(x))
+ .replace(/\u001b\[\?25./g, "")
+ .split("\u001b[2K")
+ .filter((x) => x)
+ .map((x) => JSON.parse(x))
);
}
@@ -505,7 +505,7 @@ function touchFile(filepath) {
try {
fs.utimesSync(filepath, touchRef, touchRef);
} catch (err) {
- const fd = fs.openSync(filepath, 'a');
+ const fd = fs.openSync(filepath, "a");
fs.closeSync(fd);
}
}
@@ -519,9 +519,9 @@ function touchFile(filepath) {
* @param {string} replacement - Replacement
*/
function replaceFileContents(filepath, pattern, replacement) {
- const contents = fs.readFileSync(filepath, 'utf-8');
+ const contents = fs.readFileSync(filepath, "utf-8");
const newContents = contents.replace(pattern, replacement);
- fs.writeFileSync(filepath, newContents, 'utf-8');
+ fs.writeFileSync(filepath, newContents, "utf-8");
}
/**
@@ -542,14 +542,14 @@ function copyFixture(fixtureName, dest) {
* @returns {Promise<CreateTempDirResult>} Temp dir path and cleanup function
*/
const createTempDir = async () => {
- const dirpath = await fsP.mkdtemp(path.join(os.tmpdir(), 'mocha-'));
+ const dirpath = await fsP.mkdtemp(path.join(os.tmpdir(), "mocha-"));
return {
dirpath,
removeTempDir: async () => {
if (!process.env.MOCHA_TEST_KEEP_TEMP_DIRS) {
return fs.rmSync(dirpath, { recursive: true, force: true });
}
- }
+ },
};
};
@@ -559,7 +559,7 @@ const createTempDir = async () => {
* @returns {Promise<void>}
*/
function sleep(time) {
- return new Promise(resolve => {
+ return new Promise((resolve) => {
setTimeout(resolve, time);
});
}
@@ -585,7 +585,7 @@ module.exports = {
runMochaWatchJSONAsync,
sleep,
toJSONResult,
- touchFile
+ touchFile,
};
/**
diff --git a/test/integration/hook-err.spec.js b/test/integration/hook-err.spec.js
index eee7d980..1e895912 100644
--- a/test/integration/hook-err.spec.js
+++ b/test/integration/hook-err.spec.js
@@ -1,280 +1,280 @@
-'use strict';
+"use strict";
const {
runMocha,
runMochaJSON,
runMochaJSONAsync,
- SPLIT_DOT_REPORTER_REGEXP
-} = require('./helpers');
-const {bang} = require('../../lib/reporters/base').symbols;
+ SPLIT_DOT_REPORTER_REGEXP,
+} = require("./helpers");
+const { bang } = require("../../lib/reporters/base").symbols;
-describe('hook error handling', function () {
+describe("hook error handling", function () {
let lines;
- describe('before hook error', function () {
- before(run('hooks/before-hook-error.fixture.js'));
- it('should verify results', function () {
- expect(lines, 'to equal', ['before', bang + 'test 3']);
+ describe("before hook error", function () {
+ before(run("hooks/before-hook-error.fixture.js"));
+ it("should verify results", function () {
+ expect(lines, "to equal", ["before", bang + "test 3"]);
});
});
- describe('before hook error tip', function () {
- before(run('hooks/before-hook-error-tip.fixture.js', onlyErrorTitle()));
- it('should verify results', function () {
- expect(lines, 'to equal', [
- '1) spec 2',
- '"before all" hook for "skipped":'
+ describe("before hook error tip", function () {
+ before(run("hooks/before-hook-error-tip.fixture.js", onlyErrorTitle()));
+ it("should verify results", function () {
+ expect(lines, "to equal", [
+ "1) spec 2",
+ '"before all" hook for "skipped":',
]);
});
});
- describe('before hook root error', function () {
- it('should verify results', function (done) {
- runMochaJSON('hooks/before-hook-root-error', [], (err, res) => {
+ describe("before hook root error", function () {
+ it("should verify results", function (done) {
+ runMochaJSON("hooks/before-hook-root-error", [], (err, res) => {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'before hook root error')
- .and('to have failed test', '"before all" hook in "{root}"')
- .and('to have passed test count', 0);
+ expect(res, "to have failed with error", "before hook root error")
+ .and("to have failed test", '"before all" hook in "{root}"')
+ .and("to have passed test count", 0);
done();
});
});
});
- describe('before hook nested error', function () {
- it('should verify results', function (done) {
- runMochaJSON('hooks/before-hook-nested-error', [], (err, res) => {
+ describe("before hook nested error", function () {
+ it("should verify results", function (done) {
+ runMochaJSON("hooks/before-hook-nested-error", [], (err, res) => {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'before hook nested error')
+ expect(res, "to have failed with error", "before hook nested error")
.and(
- 'to have failed test',
- '"before all" hook for "it nested - this title should be used"'
+ "to have failed test",
+ '"before all" hook for "it nested - this title should be used"',
)
- .and('to have passed test count', 1)
- .and('to have passed test', 'should pass');
+ .and("to have passed test count", 1)
+ .and("to have passed test", "should pass");
done();
});
});
});
- describe('before hook deepnested error', function () {
- it('should verify results', function (done) {
- runMochaJSON('hooks/before-hook-deepnested-error', [], (err, res) => {
+ describe("before hook deepnested error", function () {
+ it("should verify results", function (done) {
+ runMochaJSON("hooks/before-hook-deepnested-error", [], (err, res) => {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'before hook nested error')
+ expect(res, "to have failed with error", "before hook nested error")
.and(
- 'to have failed test',
- '"before all" hook in "spec 2 nested - this title should be used"'
+ "to have failed test",
+ '"before all" hook in "spec 2 nested - this title should be used"',
)
- .and('to have passed test count', 1)
- .and('to have passed test', 'should pass');
+ .and("to have passed test count", 1)
+ .and("to have passed test", "should pass");
done();
});
});
});
- describe('before each hook error', function () {
- before(run('hooks/before-each-hook-error.fixture.js'));
- it('should verify results', function () {
- expect(lines, 'to equal', ['before', bang + 'test 3']);
+ describe("before each hook error", function () {
+ before(run("hooks/before-each-hook-error.fixture.js"));
+ it("should verify results", function () {
+ expect(lines, "to equal", ["before", bang + "test 3"]);
});
});
- describe('after hook error', function () {
- before(run('hooks/after-hook-error.fixture.js'));
- it('should verify results', function () {
- expect(lines, 'to equal', ['test 1', 'test 2', 'after', bang + 'test 3']);
+ describe("after hook error", function () {
+ before(run("hooks/after-hook-error.fixture.js"));
+ it("should verify results", function () {
+ expect(lines, "to equal", ["test 1", "test 2", "after", bang + "test 3"]);
});
});
- describe('after hook nested error', function () {
- it('should verify results', function (done) {
- runMochaJSON('hooks/after-hook-nested-error', [], (err, res) => {
+ describe("after hook nested error", function () {
+ it("should verify results", function (done) {
+ runMochaJSON("hooks/after-hook-nested-error", [], (err, res) => {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'after hook nested error')
+ expect(res, "to have failed with error", "after hook nested error")
.and(
- 'to have failed test',
- '"after all" hook for "it nested - this title should be used"'
+ "to have failed test",
+ '"after all" hook for "it nested - this title should be used"',
)
- .and('to have passed test count', 3)
+ .and("to have passed test count", 3)
.and(
- 'to have passed test order',
- 'should pass',
- 'it nested - this title should be used',
- 'it nested - not this title'
+ "to have passed test order",
+ "should pass",
+ "it nested - this title should be used",
+ "it nested - not this title",
);
done();
});
});
});
- describe('after hook deepnested error', function () {
- it('should verify results', function (done) {
- runMochaJSON('hooks/after-hook-deepnested-error', [], (err, res) => {
+ describe("after hook deepnested error", function () {
+ it("should verify results", function (done) {
+ runMochaJSON("hooks/after-hook-deepnested-error", [], (err, res) => {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'after hook nested error')
+ expect(res, "to have failed with error", "after hook nested error")
.and(
- 'to have failed test',
- '"after all" hook in "spec 2 nested - this title should be used"'
+ "to have failed test",
+ '"after all" hook in "spec 2 nested - this title should be used"',
)
- .and('to have passed test count', 2)
+ .and("to have passed test count", 2)
.and(
- 'to have passed test order',
- 'should pass',
- 'it nested - this title should not be used'
+ "to have passed test order",
+ "should pass",
+ "it nested - this title should not be used",
);
done();
});
});
});
- describe('after each hook error', function () {
- before(run('hooks/after-each-hook-error.fixture.js'));
- it('should verify results', function () {
- expect(lines, 'to equal', ['test 1', 'after', bang + 'test 3']);
+ describe("after each hook error", function () {
+ before(run("hooks/after-each-hook-error.fixture.js"));
+ it("should verify results", function () {
+ expect(lines, "to equal", ["test 1", "after", bang + "test 3"]);
});
});
- describe('multiple hook errors', function () {
- before(run('hooks/multiple-hook-error.fixture.js'));
- it('should verify results', function () {
- expect(lines, 'to equal', [
- 'root before',
- '1-1 before',
- 'root before each',
- '1 before each',
- '1-1 before each',
- bang + '1-1 after each',
- '1 after each',
- 'root after each',
- '1-1 after',
- bang + '1-2 before',
- 'root before each',
- '1 before each',
- '1-2 before each',
- '1-2 test 1',
- '1-2 after each',
- bang + '1 after each',
- 'root after each',
- '1-2 after',
- '1 after',
- '2-1 before',
- 'root before each',
- '2 before each',
- bang + '2 after each',
- bang + 'root after each',
- '2-1 after',
- '2 after',
- 'root after'
+ describe("multiple hook errors", function () {
+ before(run("hooks/multiple-hook-error.fixture.js"));
+ it("should verify results", function () {
+ expect(lines, "to equal", [
+ "root before",
+ "1-1 before",
+ "root before each",
+ "1 before each",
+ "1-1 before each",
+ bang + "1-1 after each",
+ "1 after each",
+ "root after each",
+ "1-1 after",
+ bang + "1-2 before",
+ "root before each",
+ "1 before each",
+ "1-2 before each",
+ "1-2 test 1",
+ "1-2 after each",
+ bang + "1 after each",
+ "root after each",
+ "1-2 after",
+ "1 after",
+ "2-1 before",
+ "root before each",
+ "2 before each",
+ bang + "2 after each",
+ bang + "root after each",
+ "2-1 after",
+ "2 after",
+ "root after",
]);
});
});
- describe('async - before hook error', function () {
- before(run('hooks/before-hook-async-error.fixture.js'));
- it('should verify results', function () {
- expect(lines, 'to equal', ['before', bang + 'test 3']);
+ describe("async - before hook error", function () {
+ before(run("hooks/before-hook-async-error.fixture.js"));
+ it("should verify results", function () {
+ expect(lines, "to equal", ["before", bang + "test 3"]);
});
});
- describe('async - before hook error tip', function () {
+ describe("async - before hook error tip", function () {
before(
- run('hooks/before-hook-async-error-tip.fixture.js', onlyErrorTitle())
+ run("hooks/before-hook-async-error-tip.fixture.js", onlyErrorTitle()),
);
- it('should verify results', function () {
- expect(lines, 'to equal', [
- '1) spec 2',
- '"before all" hook for "skipped":'
+ it("should verify results", function () {
+ expect(lines, "to equal", [
+ "1) spec 2",
+ '"before all" hook for "skipped":',
]);
});
});
- describe('async - before each hook error', function () {
- before(run('hooks/before-each-hook-async-error.fixture.js'));
- it('should verify results', function () {
- expect(lines, 'to equal', ['before', bang + 'test 3']);
+ describe("async - before each hook error", function () {
+ before(run("hooks/before-each-hook-async-error.fixture.js"));
+ it("should verify results", function () {
+ expect(lines, "to equal", ["before", bang + "test 3"]);
});
});
- describe('async - after hook error', function () {
- before(run('hooks/after-hook-async-error.fixture.js'));
- it('should verify results', function () {
- expect(lines, 'to equal', ['test 1', 'test 2', 'after', bang + 'test 3']);
+ describe("async - after hook error", function () {
+ before(run("hooks/after-hook-async-error.fixture.js"));
+ it("should verify results", function () {
+ expect(lines, "to equal", ["test 1", "test 2", "after", bang + "test 3"]);
});
});
- describe('async - after each hook error', function () {
- before(run('hooks/after-each-hook-async-error.fixture.js'));
- it('should verify results', function () {
- expect(lines, 'to equal', ['test 1', 'after', bang + 'test 3']);
+ describe("async - after each hook error", function () {
+ before(run("hooks/after-each-hook-async-error.fixture.js"));
+ it("should verify results", function () {
+ expect(lines, "to equal", ["test 1", "after", bang + "test 3"]);
});
});
- describe('async - multiple hook errors', function () {
- before(run('hooks/multiple-hook-async-error.fixture.js'));
- it('should verify results', function () {
- expect(lines, 'to equal', [
- 'root before',
- '1-1 before',
- 'root before each',
- '1 before each',
- '1-1 before each',
- bang + '1-1 after each',
- '1 after each',
- 'root after each',
- '1-1 after',
- bang + '1-2 before',
- 'root before each',
- '1 before each',
- '1-2 before each',
- '1-2 test 1',
- '1-2 after each',
- bang + '1 after each',
- 'root after each',
- '1-2 after',
- '1 after',
- '2-1 before',
- 'root before each',
- '2 before each',
- bang + '2 after each',
- bang + 'root after each',
- '2-1 after',
- '2 after',
- 'root after'
+ describe("async - multiple hook errors", function () {
+ before(run("hooks/multiple-hook-async-error.fixture.js"));
+ it("should verify results", function () {
+ expect(lines, "to equal", [
+ "root before",
+ "1-1 before",
+ "root before each",
+ "1 before each",
+ "1-1 before each",
+ bang + "1-1 after each",
+ "1 after each",
+ "root after each",
+ "1-1 after",
+ bang + "1-2 before",
+ "root before each",
+ "1 before each",
+ "1-2 before each",
+ "1-2 test 1",
+ "1-2 after each",
+ bang + "1 after each",
+ "root after each",
+ "1-2 after",
+ "1 after",
+ "2-1 before",
+ "root before each",
+ "2 before each",
+ bang + "2 after each",
+ bang + "root after each",
+ "2-1 after",
+ "2 after",
+ "root after",
]);
});
});
describe('"this.test.error()-style failure', function () {
- it('should fail the associated test', async function () {
+ it("should fail the associated test", async function () {
return expect(
- runMochaJSONAsync('hooks/after-each-this-test-error'),
- 'when fulfilled',
- 'to have failed'
+ runMochaJSONAsync("hooks/after-each-this-test-error"),
+ "when fulfilled",
+ "to have failed",
).and(
- 'when fulfilled',
- 'to have failed test',
- 'fail the test from the "after each" hook should fail'
+ "when fulfilled",
+ "to have failed test",
+ 'fail the test from the "after each" hook should fail',
);
});
});
function run(fnPath, outputFilter) {
- return done =>
- runMocha(fnPath, ['--reporter', 'dot'], (err, res) => {
- expect(err, 'to be falsy');
+ return (done) =>
+ runMocha(fnPath, ["--reporter", "dot"], (err, res) => {
+ expect(err, "to be falsy");
lines = res.output
.split(SPLIT_DOT_REPORTER_REGEXP)
- .map(line => line.trim())
+ .map((line) => line.trim())
.filter(outputFilter || onlyConsoleOutput());
done();
@@ -284,7 +284,7 @@ describe('hook error handling', function () {
function onlyConsoleOutput() {
let foundSummary = false;
- return line => {
+ return (line) => {
if (!foundSummary) {
foundSummary = !!/\(\d+ms\)/.exec(line);
}
@@ -295,7 +295,7 @@ function onlyConsoleOutput() {
function onlyErrorTitle() {
let foundErrorTitle = false;
let foundError = false;
- return line => {
+ return (line) => {
if (!foundErrorTitle) {
foundErrorTitle = !!/^1\)/.exec(line);
}
diff --git a/test/integration/hooks.spec.js b/test/integration/hooks.spec.js
index af01093d..7139a4b8 100644
--- a/test/integration/hooks.spec.js
+++ b/test/integration/hooks.spec.js
@@ -1,14 +1,14 @@
-'use strict';
+"use strict";
-var assert = require('node:assert');
-var runMocha = require('./helpers').runMocha;
-var runMochaJSON = require('./helpers').runMochaJSON;
-var SPLIT_DOT_REPORTER_REGEXP = require('./helpers').SPLIT_DOT_REPORTER_REGEXP;
-var args = ['--reporter', 'dot'];
+var assert = require("node:assert");
+var runMocha = require("./helpers").runMocha;
+var runMochaJSON = require("./helpers").runMochaJSON;
+var SPLIT_DOT_REPORTER_REGEXP = require("./helpers").SPLIT_DOT_REPORTER_REGEXP;
+var args = ["--reporter", "dot"];
-describe('hooks', function () {
- it('are ran in correct order', function (done) {
- runMocha('cascade.fixture.js', args, function (err, res) {
+describe("hooks", function () {
+ it("are ran in correct order", function (done) {
+ runMocha("cascade.fixture.js", args, function (err, res) {
var lines, expected;
if (err) {
@@ -27,19 +27,19 @@ describe('hooks', function () {
.slice(0, -1);
expected = [
- 'before one',
- 'before two',
- 'before three',
- 'before each one',
- 'before each two',
- 'before each three',
- 'TEST three',
- 'after each three',
- 'after each two',
- 'after each one',
- 'after three',
- 'after two',
- 'after one'
+ "before one",
+ "before two",
+ "before three",
+ "before each one",
+ "before each two",
+ "before each three",
+ "TEST three",
+ "after each three",
+ "after each two",
+ "after each one",
+ "after three",
+ "after two",
+ "after one",
];
expected.forEach(function (line, i) {
@@ -51,14 +51,14 @@ describe('hooks', function () {
});
});
- it('current test title of all hooks', function (done) {
- runMochaJSON('current-test-title.fixture.js', [], function (err, res) {
+ it("current test title of all hooks", function (done) {
+ runMochaJSON("current-test-title.fixture.js", [], function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed')
- .and('to have passed test count', 3)
- .and('to have passed test order', 'test1 B', 'test1 C', 'test2 C');
+ expect(res, "to have passed")
+ .and("to have passed test count", 3)
+ .and("to have passed test order", "test1 B", "test1 C", "test2 C");
done();
});
});
diff --git a/test/integration/init.spec.js b/test/integration/init.spec.js
index 68361b35..938987b5 100644
--- a/test/integration/init.spec.js
+++ b/test/integration/init.spec.js
@@ -1,20 +1,20 @@
-'use strict';
+"use strict";
-var fs = require('node:fs');
-var rimraf = require('rimraf');
-var invokeMocha = require('./helpers').invokeMocha;
-var path = require('node:path');
-var os = require('node:os');
+var fs = require("node:fs");
+var rimraf = require("rimraf");
+var invokeMocha = require("./helpers").invokeMocha;
+var path = require("node:path");
+var os = require("node:os");
-describe('init command', function () {
+describe("init command", function () {
var tmpdir;
beforeEach(function () {
- tmpdir = path.join(os.tmpdir(), 'mocha-init');
+ tmpdir = path.join(os.tmpdir(), "mocha-init");
try {
fs.mkdirSync(tmpdir);
} catch (ignored) {}
- expect(fs.existsSync(tmpdir), 'to be true');
+ expect(fs.existsSync(tmpdir), "to be true");
});
afterEach(function () {
@@ -23,56 +23,56 @@ describe('init command', function () {
} catch (ignored) {}
});
- describe('when no path is supplied', function () {
- it('should fail', function (done) {
+ describe("when no path is supplied", function () {
+ it("should fail", function (done) {
invokeMocha(
- ['init'],
+ ["init"],
function (err, result) {
if (err) {
return done(err);
}
expect(
result,
- 'to have failed with output',
- /not enough non-option arguments/i
+ "to have failed with output",
+ /not enough non-option arguments/i,
);
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
- it('should not throw', function (done) {
+ it("should not throw", function (done) {
invokeMocha(
- ['init'],
+ ["init"],
function (err, result) {
if (err) {
return done(err);
}
- expect(result, 'to have failed').and('not to satisfy', {
- output: /throw/i
+ expect(result, "to have failed").and("not to satisfy", {
+ output: /throw/i,
});
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
});
- it('should create some files in the dest dir', function (done) {
+ it("should create some files in the dest dir", function (done) {
invokeMocha(
- ['init', tmpdir],
+ ["init", tmpdir],
function (err, result) {
if (err) {
return done(err);
}
- expect(result, 'to have succeeded');
- expect(fs.existsSync(path.join(tmpdir, 'mocha.css')), 'to be true');
- expect(fs.existsSync(path.join(tmpdir, 'mocha.js')), 'to be true');
- expect(fs.existsSync(path.join(tmpdir, 'tests.spec.js')), 'to be true');
- expect(fs.existsSync(path.join(tmpdir, 'index.html')), 'to be true');
+ expect(result, "to have succeeded");
+ expect(fs.existsSync(path.join(tmpdir, "mocha.css")), "to be true");
+ expect(fs.existsSync(path.join(tmpdir, "mocha.js")), "to be true");
+ expect(fs.existsSync(path.join(tmpdir, "tests.spec.js")), "to be true");
+ expect(fs.existsSync(path.join(tmpdir, "index.html")), "to be true");
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
});
diff --git a/test/integration/invalid-arguments.spec.js b/test/integration/invalid-arguments.spec.js
index bc39cd2c..bee66ac1 100644
--- a/test/integration/invalid-arguments.spec.js
+++ b/test/integration/invalid-arguments.spec.js
@@ -1,21 +1,21 @@
-'use strict';
+"use strict";
-var invokeMocha = require('./helpers').invokeMocha;
+var invokeMocha = require("./helpers").invokeMocha;
-describe('invalid arguments', function () {
- describe('when argument is missing required value', function () {
- it('should exit with failure', function (done) {
+describe("invalid arguments", function () {
+ describe("when argument is missing required value", function () {
+ it("should exit with failure", function (done) {
invokeMocha(
- ['--ui'],
+ ["--ui"],
function (err, result) {
if (err) {
return done(err);
}
- expect(result, 'to have failed');
- expect(result.output, 'to match', /not enough arguments/i);
+ expect(result, "to have failed");
+ expect(result.output, "to match", /not enough arguments/i);
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
});
diff --git a/test/integration/multiple-done.spec.js b/test/integration/multiple-done.spec.js
index d6056530..bdb8907e 100644
--- a/test/integration/multiple-done.spec.js
+++ b/test/integration/multiple-done.spec.js
@@ -1,162 +1,163 @@
-'use strict';
+"use strict";
-var runMochaJSON = require('./helpers').runMochaJSON;
-var invokeMocha = require('./helpers').invokeMocha;
-var MULTIPLE_DONE = require('../../lib/error-constants').constants.MULTIPLE_DONE;
+var runMochaJSON = require("./helpers").runMochaJSON;
+var invokeMocha = require("./helpers").invokeMocha;
+var MULTIPLE_DONE = require("../../lib/error-constants").constants
+ .MULTIPLE_DONE;
-describe('multiple calls to done()', function () {
+describe("multiple calls to done()", function () {
var res;
- describe('from a spec', function () {
+ describe("from a spec", function () {
before(function (done) {
- runMochaJSON('multiple-done', function (err, result) {
+ runMochaJSON("multiple-done", function (err, result) {
res = result;
done(err);
});
});
- it('results in failure', function () {
- expect(res, 'to have failed test count', 1)
- .and('to have passed test count', 1)
- .and('to have pending test count', 0)
- .and('to have failed');
+ it("results in failure", function () {
+ expect(res, "to have failed test count", 1)
+ .and("to have passed test count", 1)
+ .and("to have pending test count", 0)
+ .and("to have failed");
});
- it('throws a descriptive error', function () {
- expect(res, 'to have failed with error', {
+ it("throws a descriptive error", function () {
+ expect(res, "to have failed with error", {
message:
/done\(\) called multiple times in test <should fail in a test-case> \(of root suite\) of file.+multiple-done\.fixture\.js/,
- code: MULTIPLE_DONE
+ code: MULTIPLE_DONE,
});
});
});
- describe('with error passed on second call', function () {
+ describe("with error passed on second call", function () {
before(function (done) {
- runMochaJSON('multiple-done-with-error', function (err, result) {
+ runMochaJSON("multiple-done-with-error", function (err, result) {
res = result;
done(err);
});
});
- it('results in failure', function () {
- expect(res, 'to have failed test count', 1)
- .and('to have passed test count', 1)
- .and('to have pending test count', 0)
- .and('to have failed');
+ it("results in failure", function () {
+ expect(res, "to have failed test count", 1)
+ .and("to have passed test count", 1)
+ .and("to have pending test count", 0)
+ .and("to have failed");
});
- it('should throw a descriptive error', function () {
- expect(res, 'to have failed with error', {
+ it("should throw a descriptive error", function () {
+ expect(res, "to have failed with error", {
message:
/done\(\) called multiple times in test <should fail in a test-case> \(of root suite\) of file.+multiple-done-with-error\.fixture\.js; in addition, done\(\) received error: Error: second error/,
- code: MULTIPLE_DONE
+ code: MULTIPLE_DONE,
});
});
});
- describe('with multiple specs', function () {
+ describe("with multiple specs", function () {
before(function (done) {
- runMochaJSON('multiple-done-specs', function (err, result) {
+ runMochaJSON("multiple-done-specs", function (err, result) {
res = result;
done(err);
});
});
- it('results in failure', function () {
- expect(res, 'to have failed test count', 1)
- .and('to have passed test count', 2)
- .and('to have pending test count', 0)
- .and('to have failed');
+ it("results in failure", function () {
+ expect(res, "to have failed test count", 1)
+ .and("to have passed test count", 2)
+ .and("to have pending test count", 0)
+ .and("to have failed");
});
- it('correctly attributes the error', function () {
- expect(res.failures[0], 'to satisfy', {
- fullTitle: 'suite test1',
+ it("correctly attributes the error", function () {
+ expect(res.failures[0], "to satisfy", {
+ fullTitle: "suite test1",
err: {
message:
/done\(\) called multiple times in test <suite test1> of file.+multiple-done-specs\.fixture\.js/,
- code: MULTIPLE_DONE
- }
+ code: MULTIPLE_DONE,
+ },
});
});
});
- describe('from a before hook', function () {
+ describe("from a before hook", function () {
before(function (done) {
- runMochaJSON('multiple-done-before', function (err, result) {
+ runMochaJSON("multiple-done-before", function (err, result) {
res = result;
done(err);
});
});
- it('results in failure', function () {
- expect(res, 'to have failed test count', 1)
- .and('to have passed test count', 1)
- .and('to have pending test count', 0)
- .and('to have failed');
+ it("results in failure", function () {
+ expect(res, "to have failed test count", 1)
+ .and("to have passed test count", 1)
+ .and("to have pending test count", 0)
+ .and("to have failed");
});
- it('correctly attributes the error', function () {
- expect(res.failures[0], 'to satisfy', {
+ it("correctly attributes the error", function () {
+ expect(res.failures[0], "to satisfy", {
fullTitle: 'suite1 "before all" hook in "suite1"',
err: {
message:
- /done\(\) called multiple times in hook <suite1 "before all" hook in "suite1"> of file.+multiple-done-before\.fixture\.js/
- }
+ /done\(\) called multiple times in hook <suite1 "before all" hook in "suite1"> of file.+multiple-done-before\.fixture\.js/,
+ },
});
});
});
describe('from a "before each" hook', function () {
before(function (done) {
- runMochaJSON('multiple-done-before-each', function (err, result) {
+ runMochaJSON("multiple-done-before-each", function (err, result) {
res = result;
done(err);
});
});
- it('results in a failure', function () {
- expect(res, 'to have failed test count', 2)
- .and('to have passed test count', 2)
- .and('to have pending test count', 0)
- .and('to have exit code', 2);
+ it("results in a failure", function () {
+ expect(res, "to have failed test count", 2)
+ .and("to have passed test count", 2)
+ .and("to have pending test count", 0)
+ .and("to have exit code", 2);
});
- it('correctly attributes the errors', function () {
- expect(res.failures[0], 'to equal', res.failures[1]).and('to satisfy', {
+ it("correctly attributes the errors", function () {
+ expect(res.failures[0], "to equal", res.failures[1]).and("to satisfy", {
fullTitle: 'suite1 "before each" hook in "suite1"',
err: {
message:
/done\(\) called multiple times in hook <suite1 "before each" hook in "suite1"> of file.+multiple-done-before-each\.fixture\.js/,
multiple: [
{
- code: 'ERR_MOCHA_MULTIPLE_DONE'
- }
- ]
- }
+ code: "ERR_MOCHA_MULTIPLE_DONE",
+ },
+ ],
+ },
});
});
});
- describe('when done() called asynchronously', function () {
+ describe("when done() called asynchronously", function () {
before(function (done) {
// we can't be sure that mocha won't fail with an uncaught exception here, which would cause any JSON
// output to be befouled; we need to run "raw" and capture STDERR
invokeMocha(
- require.resolve('./fixtures/multiple-done-async.fixture.js'),
+ require.resolve("./fixtures/multiple-done-async.fixture.js"),
function (err, result) {
res = result;
done(err);
},
- 'pipe'
+ "pipe",
);
});
- it('results in error', function () {
- expect(res, 'to satisfy', {
- code: expect.it('to be greater than', 0),
+ it("results in error", function () {
+ expect(res, "to satisfy", {
+ code: expect.it("to be greater than", 0),
output:
- /done\(\) called multiple times in test <should fail in an async test case> \(of root suite\) of file.+multiple-done-async\.fixture\.js/
+ /done\(\) called multiple times in test <should fail in an async test case> \(of root suite\) of file.+multiple-done-async\.fixture\.js/,
});
});
});
diff --git a/test/integration/multiple-runs.spec.js b/test/integration/multiple-runs.spec.js
index af65b4e8..cfaa4182 100644
--- a/test/integration/multiple-runs.spec.js
+++ b/test/integration/multiple-runs.spec.js
@@ -1,36 +1,36 @@
-'use strict';
+"use strict";
-const {invokeNode} = require('./helpers');
+const { invokeNode } = require("./helpers");
-describe('multiple runs', function () {
- it('should be allowed to run multiple times if cleanReferences is turned off', function (done) {
+describe("multiple runs", function () {
+ it("should be allowed to run multiple times if cleanReferences is turned off", function (done) {
var path = require.resolve(
- './fixtures/multiple-runs/run-thrice.fixture.js'
+ "./fixtures/multiple-runs/run-thrice.fixture.js",
);
invokeNode([path], function (err, res) {
if (err) {
done(err);
return;
}
- expect(res.code, 'to be', 0);
+ expect(res.code, "to be", 0);
var results = JSON.parse(res.output);
- expect(results, 'to have length', 3);
- expect(results[0].pending, 'to have length', 1);
- expect(results[0].failures, 'to have length', 0);
- expect(results[0].passes, 'to have length', 0);
- expect(results[1].pending, 'to have length', 0);
- expect(results[1].failures, 'to have length', 1);
- expect(results[1].passes, 'to have length', 0);
- expect(results[2].pending, 'to have length', 0);
- expect(results[2].failures, 'to have length', 0);
- expect(results[2].passes, 'to have length', 1);
+ expect(results, "to have length", 3);
+ expect(results[0].pending, "to have length", 1);
+ expect(results[0].failures, "to have length", 0);
+ expect(results[0].passes, "to have length", 0);
+ expect(results[1].pending, "to have length", 0);
+ expect(results[1].failures, "to have length", 1);
+ expect(results[1].passes, "to have length", 0);
+ expect(results[2].pending, "to have length", 0);
+ expect(results[2].failures, "to have length", 0);
+ expect(results[2].passes, "to have length", 1);
done();
});
});
- it('should not be allowed if cleanReferences is true', function (done) {
+ it("should not be allowed if cleanReferences is true", function (done) {
var path = require.resolve(
- './fixtures/multiple-runs/clean-references.fixture.js'
+ "./fixtures/multiple-runs/clean-references.fixture.js",
);
invokeNode(
[path],
@@ -39,37 +39,37 @@ describe('multiple runs', function () {
done(err);
return;
}
- expect(res, 'to have failed').and(
- 'to contain output',
- /ERR_MOCHA_INSTANCE_ALREADY_DISPOSED/
+ expect(res, "to have failed").and(
+ "to contain output",
+ /ERR_MOCHA_INSTANCE_ALREADY_DISPOSED/,
);
done();
},
- {stdio: ['ignore', 'pipe', 'pipe']}
+ { stdio: ["ignore", "pipe", "pipe"] },
);
});
- it('should not be allowed if the instance is disposed', function (done) {
- var path = require.resolve('./fixtures/multiple-runs/dispose.fixture.js');
+ it("should not be allowed if the instance is disposed", function (done) {
+ var path = require.resolve("./fixtures/multiple-runs/dispose.fixture.js");
invokeNode(
- [path, '--directly-dispose'],
+ [path, "--directly-dispose"],
function (err, res) {
if (err) {
done(err);
return;
}
- expect(res.code, 'not to be', 0);
- expect(res.output, 'to contain', 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED');
+ expect(res.code, "not to be", 0);
+ expect(res.output, "to contain", "ERR_MOCHA_INSTANCE_ALREADY_DISPOSED");
done();
},
- {stdio: ['ignore', 'pipe', 'pipe']}
+ { stdio: ["ignore", "pipe", "pipe"] },
);
});
- it('should not be allowed to run while a previous run is in progress', function (done) {
+ it("should not be allowed to run while a previous run is in progress", function (done) {
var path = require.resolve(
- './fixtures/multiple-runs/start-second-run-if-previous-is-still-running.fixture'
+ "./fixtures/multiple-runs/start-second-run-if-previous-is-still-running.fixture",
);
invokeNode(
[path],
@@ -78,26 +78,26 @@ describe('multiple runs', function () {
done(err);
return;
}
- expect(res.output, 'to contain', 'ERR_MOCHA_INSTANCE_ALREADY_RUNNING');
+ expect(res.output, "to contain", "ERR_MOCHA_INSTANCE_ALREADY_RUNNING");
done();
},
- {stdio: ['ignore', 'pipe', 'pipe']}
+ { stdio: ["ignore", "pipe", "pipe"] },
);
});
- it('should reset the hooks between runs', function (done) {
+ it("should reset the hooks between runs", function (done) {
var path = require.resolve(
- './fixtures/multiple-runs/multiple-runs-with-flaky-before-each.fixture'
+ "./fixtures/multiple-runs/multiple-runs-with-flaky-before-each.fixture",
);
invokeNode([path], function (err, res) {
- expect(err, 'to be null');
- expect(res.code, 'to be', 0);
+ expect(err, "to be null");
+ expect(res.code, "to be", 0);
var results = JSON.parse(res.output);
- expect(results, 'to have length', 2);
- expect(results[0].failures, 'to have length', 1);
- expect(results[0].passes, 'to have length', 0);
- expect(results[1].passes, 'to have length', 1);
- expect(results[1].failures, 'to have length', 0);
+ expect(results, "to have length", 2);
+ expect(results[0].failures, "to have length", 1);
+ expect(results[0].passes, "to have length", 0);
+ expect(results[1].passes, "to have length", 1);
+ expect(results[1].failures, "to have length", 0);
done();
});
});
diff --git a/test/integration/no-diff.spec.js b/test/integration/no-diff.spec.js
index d7eeb9ea..294d6dd5 100644
--- a/test/integration/no-diff.spec.js
+++ b/test/integration/no-diff.spec.js
@@ -1,32 +1,32 @@
-'use strict';
+"use strict";
-var helpers = require('./helpers');
+var helpers = require("./helpers");
var run = helpers.runMocha;
-describe('no-diff', function () {
- describe('when enabled', function () {
- it('should not display a diff', function (done) {
- run('no-diff.fixture.js', ['--no-diff'], function (err, res) {
+describe("no-diff", function () {
+ describe("when enabled", function () {
+ it("should not display a diff", function (done) {
+ run("no-diff.fixture.js", ["--no-diff"], function (err, res) {
if (err) {
done(err);
return;
}
- expect(res.output, 'not to match', /\+ expected/);
- expect(res.output, 'not to match', /- actual/);
+ expect(res.output, "not to match", /\+ expected/);
+ expect(res.output, "not to match", /- actual/);
done();
});
});
});
- describe('when disabled', function () {
- it('should display a diff', function (done) {
- run('no-diff.fixture.js', ['--diff'], function (err, res) {
+ describe("when disabled", function () {
+ it("should display a diff", function (done) {
+ run("no-diff.fixture.js", ["--diff"], function (err, res) {
if (err) {
done(err);
return;
}
- expect(res.output, 'to match', /\+ expected/);
- expect(res.output, 'to match', /- actual/);
+ expect(res.output, "to match", /\+ expected/);
+ expect(res.output, "to match", /- actual/);
done();
});
});
diff --git a/test/integration/only.spec.js b/test/integration/only.spec.js
index f7a317a0..db0b53ac 100644
--- a/test/integration/only.spec.js
+++ b/test/integration/only.spec.js
@@ -1,12 +1,12 @@
-'use strict';
+"use strict";
-var run = require('./helpers').runMochaJSON;
-var assert = require('node:assert');
+var run = require("./helpers").runMochaJSON;
+var assert = require("node:assert");
-describe('.only()', function () {
- describe('bdd', function () {
- it('should run only tests that marked as `only`', function (done) {
- run('options/only/bdd.fixture.js', ['--ui', 'bdd'], function (err, res) {
+describe(".only()", function () {
+ describe("bdd", function () {
+ it("should run only tests that marked as `only`", function (done) {
+ run("options/only/bdd.fixture.js", ["--ui", "bdd"], function (err, res) {
if (err) {
done(err);
return;
@@ -20,9 +20,9 @@ describe('.only()', function () {
});
});
- describe('tdd', function () {
- it('should run only tests that marked as `only`', function (done) {
- run('options/only/tdd.fixture.js', ['--ui', 'tdd'], function (err, res) {
+ describe("tdd", function () {
+ it("should run only tests that marked as `only`", function (done) {
+ run("options/only/tdd.fixture.js", ["--ui", "tdd"], function (err, res) {
if (err) {
done(err);
return;
@@ -36,11 +36,11 @@ describe('.only()', function () {
});
});
- describe('qunit', function () {
- it('should run only tests that marked as `only`', function (done) {
+ describe("qunit", function () {
+ it("should run only tests that marked as `only`", function (done) {
run(
- 'options/only/qunit.fixture.js',
- ['--ui', 'qunit'],
+ "options/only/qunit.fixture.js",
+ ["--ui", "qunit"],
function (err, res) {
if (err) {
done(err);
@@ -51,7 +51,7 @@ describe('.only()', function () {
assert.strictEqual(res.stats.failures, 0);
assert.strictEqual(res.code, 0);
done();
- }
+ },
);
});
});
diff --git a/test/integration/options/allowUncaught.spec.js b/test/integration/options/allowUncaught.spec.js
index 782355f4..e911dec2 100644
--- a/test/integration/options/allowUncaught.spec.js
+++ b/test/integration/options/allowUncaught.spec.js
@@ -1,15 +1,15 @@
-'use strict';
+"use strict";
-var path = require('node:path').posix;
-var helpers = require('../helpers');
+var path = require("node:path").posix;
+var helpers = require("../helpers");
var runMocha = helpers.runMocha;
var runMochaJSON = helpers.runMochaJSON;
-describe('--allow-uncaught', function () {
- var args = ['--allow-uncaught'];
+describe("--allow-uncaught", function () {
+ var args = ["--allow-uncaught"];
- it('should throw an uncaught error and exit process', function (done) {
- var fixture = path.join('options', 'allow-uncaught', 'propagate');
+ it("should throw an uncaught error and exit process", function (done) {
+ var fixture = path.join("options", "allow-uncaught", "propagate");
runMocha(
fixture,
args,
@@ -18,28 +18,28 @@ describe('--allow-uncaught', function () {
return done(err);
}
- expect(res.code, 'to be greater than', 0);
- expect(res.output, 'to contain', 'Error: Uncaught error after test1');
- expect(res.passing, 'to be', 0);
- expect(res.failing, 'to be', 0);
+ expect(res.code, "to be greater than", 0);
+ expect(res.output, "to contain", "Error: Uncaught error after test1");
+ expect(res.passing, "to be", 0);
+ expect(res.failing, "to be", 0);
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
- it('should run with conditional `this.skip()`', function (done) {
- var fixture = path.join('options', 'allow-uncaught', 'this-skip-it');
+ it("should run with conditional `this.skip()`", function (done) {
+ var fixture = path.join("options", "allow-uncaught", "this-skip-it");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed')
- .and('to have passed test count', 2)
- .and('to have pending test count', 3)
- .and('to have passed test', 'test1', 'test4')
- .and('to have pending test order', 'test2', 'test3', 'test5');
+ expect(res, "to have passed")
+ .and("to have passed test count", 2)
+ .and("to have pending test count", 3)
+ .and("to have passed test", "test1", "test4")
+ .and("to have pending test order", "test2", "test3", "test5");
done();
});
});
diff --git a/test/integration/options/asyncOnly.spec.js b/test/integration/options/asyncOnly.spec.js
index e9b8dab3..64bd55f8 100644
--- a/test/integration/options/asyncOnly.spec.js
+++ b/test/integration/options/asyncOnly.spec.js
@@ -1,36 +1,36 @@
-'use strict';
+"use strict";
-var path = require('node:path').posix;
-var helpers = require('../helpers');
+var path = require("node:path").posix;
+var helpers = require("../helpers");
var runMochaJSON = helpers.runMochaJSON;
-describe('--async-only', function () {
+describe("--async-only", function () {
var args = [];
before(function () {
- args = ['--async-only'];
+ args = ["--async-only"];
});
- it('should fail synchronous specs', function (done) {
- var fixture = path.join('options', 'async-only-sync');
+ it("should fail synchronous specs", function (done) {
+ var fixture = path.join("options", "async-only-sync");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed');
+ expect(res, "to have failed");
done();
});
});
- it('should allow asynchronous specs', function (done) {
- var fixture = path.join('options', 'async-only-async');
+ it("should allow asynchronous specs", function (done) {
+ var fixture = path.join("options", "async-only-async");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed');
+ expect(res, "to have passed");
done();
});
});
diff --git a/test/integration/options/bail.spec.js b/test/integration/options/bail.spec.js
index 9d1ae490..836f7ba7 100644
--- a/test/integration/options/bail.spec.js
+++ b/test/integration/options/bail.spec.js
@@ -1,133 +1,133 @@
-'use strict';
+"use strict";
-var path = require('node:path').posix;
-var helpers = require('../helpers');
+var path = require("node:path").posix;
+var helpers = require("../helpers");
var runMochaJSON = helpers.runMochaJSON;
-describe('--bail', function () {
+describe("--bail", function () {
var args = [];
before(function () {
- args = ['--bail'];
+ args = ["--bail"];
});
- it('should stop after the first error', function (done) {
- var fixture = path.join('options', 'bail');
+ it("should stop after the first error", function (done) {
+ var fixture = path.join("options", "bail");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed')
- .and('to have passed test', 'should display this spec')
- .and('to have failed test', 'should only display this error')
- .and('to have passed test count', 1)
- .and('to have failed test count', 1);
+ expect(res, "to have failed")
+ .and("to have passed test", "should display this spec")
+ .and("to have failed test", "should only display this error")
+ .and("to have passed test count", 1)
+ .and("to have failed test count", 1);
done();
});
});
- it('should stop after the first error - async', function (done) {
- var fixture = path.join('options', 'bail-async');
+ it("should stop after the first error - async", function (done) {
+ var fixture = path.join("options", "bail-async");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed')
- .and('to have passed test', 'should display this spec')
- .and('to have failed test', 'should only display this error')
- .and('to have passed test count', 1)
- .and('to have failed test count', 1);
+ expect(res, "to have failed")
+ .and("to have passed test", "should display this spec")
+ .and("to have failed test", "should only display this error")
+ .and("to have passed test count", 1)
+ .and("to have failed test count", 1);
done();
});
});
it('should stop all tests after failing "before" hook', function (done) {
- var fixture = path.join('options', 'bail-with-before');
+ var fixture = path.join("options", "bail-with-before");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed')
- .and('to have failed test count', 1)
+ expect(res, "to have failed")
+ .and("to have failed test count", 1)
.and(
- 'to have failed test',
- '"before all" hook: before suite1 for "test suite1"'
+ "to have failed test",
+ '"before all" hook: before suite1 for "test suite1"',
)
- .and('to have passed test count', 0);
+ .and("to have passed test count", 0);
done();
});
});
it('should stop all tests after failing "beforeEach" hook', function (done) {
- var fixture = path.join('options', 'bail-with-beforeEach');
+ var fixture = path.join("options", "bail-with-beforeEach");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed')
- .and('to have failed test count', 1)
+ expect(res, "to have failed")
+ .and("to have failed test count", 1)
.and(
- 'to have failed test',
- '"before each" hook: beforeEach suite1 for "test suite1"'
+ "to have failed test",
+ '"before each" hook: beforeEach suite1 for "test suite1"',
)
- .and('to have passed test count', 0);
+ .and("to have passed test count", 0);
done();
});
});
- it('should stop all tests after failing test', function (done) {
- var fixture = path.join('options', 'bail-with-test');
+ it("should stop all tests after failing test", function (done) {
+ var fixture = path.join("options", "bail-with-test");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed')
- .and('to have failed test count', 1)
- .and('to have failed test', 'test suite1')
- .and('to have passed test count', 0);
+ expect(res, "to have failed")
+ .and("to have failed test count", 1)
+ .and("to have failed test", "test suite1")
+ .and("to have passed test count", 0);
done();
});
});
it('should stop all tests after failing "after" hook', function (done) {
- var fixture = path.join('options', 'bail-with-after');
+ var fixture = path.join("options", "bail-with-after");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed')
- .and('to have failed test count', 1)
+ expect(res, "to have failed")
+ .and("to have failed test count", 1)
.and(
- 'to have failed test',
- '"after all" hook: after suite1A for "test suite1A"'
+ "to have failed test",
+ '"after all" hook: after suite1A for "test suite1A"',
)
- .and('to have passed test count', 2)
- .and('to have passed test order', 'test suite1', 'test suite1A');
+ .and("to have passed test count", 2)
+ .and("to have passed test order", "test suite1", "test suite1A");
done();
});
});
it('should stop all tests after failing "afterEach" hook', function (done) {
- var fixture = path.join('options', 'bail-with-afterEach');
+ var fixture = path.join("options", "bail-with-afterEach");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed')
- .and('to have failed test count', 1)
+ expect(res, "to have failed")
+ .and("to have failed test count", 1)
.and(
- 'to have failed test',
- '"after each" hook: afterEach suite1A for "test suite1A"'
+ "to have failed test",
+ '"after each" hook: afterEach suite1A for "test suite1A"',
)
- .and('to have passed test count', 2)
- .and('to have passed test order', 'test suite1', 'test suite1A');
+ .and("to have passed test count", 2)
+ .and("to have passed test order", "test suite1", "test suite1A");
done();
});
});
diff --git a/test/integration/options/compilers.spec.js b/test/integration/options/compilers.spec.js
index c2f070a6..93354b57 100644
--- a/test/integration/options/compilers.spec.js
+++ b/test/integration/options/compilers.spec.js
@@ -1,21 +1,21 @@
-'use strict';
+"use strict";
-var helpers = require('../helpers');
+var helpers = require("../helpers");
var invokeMocha = helpers.invokeMocha;
-describe('--compilers', function () {
- it('should report deprecation', function (done) {
+describe("--compilers", function () {
+ it("should report deprecation", function (done) {
invokeMocha(
- ['--compilers', 'coffee:coffeescript/register'],
+ ["--compilers", "coffee:coffeescript/register"],
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with output', /compilers is deprecated/i);
+ expect(res, "to have failed with output", /compilers is deprecated/i);
done();
},
- 'pipe'
+ "pipe",
);
});
});
diff --git a/test/integration/options/delay.spec.js b/test/integration/options/delay.spec.js
index c1da3afa..48e8e2d6 100644
--- a/test/integration/options/delay.spec.js
+++ b/test/integration/options/delay.spec.js
@@ -1,56 +1,56 @@
-'use strict';
+"use strict";
-var path = require('node:path').posix;
-var helpers = require('../helpers');
+var path = require("node:path").posix;
+var helpers = require("../helpers");
var runMochaJSON = helpers.runMochaJSON;
-describe('--delay', function () {
+describe("--delay", function () {
var args = [];
before(function () {
- args = ['--delay'];
+ args = ["--delay"];
});
- it('should run the generated test suite', function (done) {
- var fixture = path.join('options', 'delay');
+ it("should run the generated test suite", function (done) {
+ var fixture = path.join("options", "delay");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed').and('to have passed test count', 1);
+ expect(res, "to have passed").and("to have passed test count", 1);
done();
});
});
- it('should execute exclusive tests only', function (done) {
- var fixture = path.join('options', 'delay-only');
+ it("should execute exclusive tests only", function (done) {
+ var fixture = path.join("options", "delay-only");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed')
- .and('to have passed test count', 2)
+ expect(res, "to have passed")
+ .and("to have passed test count", 2)
.and(
- 'to have passed test order',
- 'should run this',
- 'should run this, too'
+ "to have passed test order",
+ "should run this",
+ "should run this, too",
);
done();
});
});
- it('should throw an error if the test suite failed to run', function (done) {
- var fixture = path.join('options', 'delay-fail');
+ it("should throw an error if the test suite failed to run", function (done) {
+ var fixture = path.join("options", "delay-fail");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed').and(
- 'to have failed test',
- 'Uncaught error outside test suite'
+ expect(res, "to have failed").and(
+ "to have failed test",
+ "Uncaught error outside test suite",
);
done();
});
diff --git a/test/integration/options/dryRun.spec.js b/test/integration/options/dryRun.spec.js
index 759cc0bc..e1eebc05 100644
--- a/test/integration/options/dryRun.spec.js
+++ b/test/integration/options/dryRun.spec.js
@@ -1,41 +1,41 @@
-'use strict';
+"use strict";
-var path = require('node:path').posix;
-var helpers = require('../helpers');
+var path = require("node:path").posix;
+var helpers = require("../helpers");
var runMochaJSON = helpers.runMochaJSON;
-describe('--dry-run', function () {
- var args = ['--dry-run'];
+describe("--dry-run", function () {
+ var args = ["--dry-run"];
- it('should only report, but not execute any test', function (done) {
- var fixture = path.join('options/dry-run', 'dry-run');
+ it("should only report, but not execute any test", function (done) {
+ var fixture = path.join("options/dry-run", "dry-run");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed')
+ expect(res, "to have passed")
.and(
- 'to have passed tests',
- 'test2 - report as passed',
- 'test3 - report as passed',
- 'test4 - report as passed'
+ "to have passed tests",
+ "test2 - report as passed",
+ "test3 - report as passed",
+ "test4 - report as passed",
)
- .and('to have passed test count', 3)
- .and('to have pending test count', 1)
- .and('to have failed test count', 0);
+ .and("to have passed test count", 3)
+ .and("to have pending test count", 1)
+ .and("to have failed test count", 0);
done();
});
});
it('should pass without "RangeError: maximum call stack size exceeded"', function (done) {
- var fixture = path.join('options/dry-run', 'stack-size');
+ var fixture = path.join("options/dry-run", "stack-size");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed test count', 400);
+ expect(res, "to have passed test count", 400);
done();
});
});
diff --git a/test/integration/options/exit.spec.js b/test/integration/options/exit.spec.js
index d467249f..e86748fd 100644
--- a/test/integration/options/exit.spec.js
+++ b/test/integration/options/exit.spec.js
@@ -1,27 +1,27 @@
-'use strict';
+"use strict";
-var runMocha = require('../helpers').runMocha;
+var runMocha = require("../helpers").runMocha;
-describe('--exit', function () {
+describe("--exit", function () {
var behaviors = {
- enabled: '--exit',
- disabled: '--no-exit'
+ enabled: "--exit",
+ disabled: "--no-exit",
};
// subprocess
var mocha;
function killSubprocess() {
- mocha.kill('SIGKILL');
+ mocha.kill("SIGKILL");
}
// these two handlers deal with a ctrl-c on command-line
before(function () {
- process.on('SIGINT', killSubprocess);
+ process.on("SIGINT", killSubprocess);
});
after(function () {
- process.removeListener('SIGINT', killSubprocess);
+ process.removeListener("SIGINT", killSubprocess);
});
/**
@@ -41,14 +41,14 @@ describe('--exit', function () {
var didExit = true;
var timeoutObj;
- var fixture = 'exit.fixture.js';
+ var fixture = "exit.fixture.js";
var args = behaviors[behavior] ? [behaviors[behavior]] : [];
mocha = runMocha(fixture, args, function postmortem(err) {
clearTimeout(timeoutObj);
if (err) {
return done(err);
}
- expect(didExit, 'to be', shouldExit);
+ expect(didExit, "to be", shouldExit);
done();
});
@@ -60,21 +60,21 @@ describe('--exit', function () {
};
};
- describe('default behavior', function () {
- it('should not force exit after root suite completion', runExit(false));
+ describe("default behavior", function () {
+ it("should not force exit after root suite completion", runExit(false));
});
- describe('when enabled', function () {
+ describe("when enabled", function () {
it(
- 'should force exit after root suite completion',
- runExit(true, 'enabled')
+ "should force exit after root suite completion",
+ runExit(true, "enabled"),
);
});
- describe('when disabled', function () {
+ describe("when disabled", function () {
it(
- 'should not force exit after root suite completion',
- runExit(false, 'disabled')
+ "should not force exit after root suite completion",
+ runExit(false, "disabled"),
);
});
});
diff --git a/test/integration/options/extension.spec.js b/test/integration/options/extension.spec.js
index 7896b177..62347932 100644
--- a/test/integration/options/extension.spec.js
+++ b/test/integration/options/extension.spec.js
@@ -1,53 +1,53 @@
-'use strict';
+"use strict";
-var helpers = require('../helpers');
+var helpers = require("../helpers");
var invokeMocha = helpers.invokeMocha;
var toJSONResult = helpers.toJSONResult;
-describe('--extension', function () {
- it('should allow comma-separated variables', function (done) {
+describe("--extension", function () {
+ it("should allow comma-separated variables", function (done) {
var args = [
- '--require',
- 'coffeescript/register',
- '--require',
- './test/setup',
- '--reporter',
- 'json',
- '--extension',
- 'js,coffee',
- 'test/integration/fixtures/options/extension'
+ "--require",
+ "coffeescript/register",
+ "--require",
+ "./test/setup",
+ "--reporter",
+ "json",
+ "--extension",
+ "js,coffee",
+ "test/integration/fixtures/options/extension",
];
invokeMocha(args, function (err, res) {
if (err) {
return done(err);
}
- expect(toJSONResult(res), 'to have passed').and(
- 'to have passed test count',
- 2
+ expect(toJSONResult(res), "to have passed").and(
+ "to have passed test count",
+ 2,
);
done();
});
});
- it('should allow extensions beginning with a dot', function (done) {
+ it("should allow extensions beginning with a dot", function (done) {
var args = [
- '--require',
- 'coffeescript/register',
- '--require',
- './test/setup',
- '--reporter',
- 'json',
- '--extension',
- '.js',
- 'test/integration/fixtures/options/extension'
+ "--require",
+ "coffeescript/register",
+ "--require",
+ "./test/setup",
+ "--reporter",
+ "json",
+ "--extension",
+ ".js",
+ "test/integration/fixtures/options/extension",
];
invokeMocha(args, function (err, res) {
if (err) {
return done(err);
}
- expect(toJSONResult(res), 'to have passed').and(
- 'to have passed test count',
- 1
+ expect(toJSONResult(res), "to have passed").and(
+ "to have passed test count",
+ 1,
);
done();
});
diff --git a/test/integration/options/failZero.spec.js b/test/integration/options/failZero.spec.js
index c0ef4924..16156b4b 100644
--- a/test/integration/options/failZero.spec.js
+++ b/test/integration/options/failZero.spec.js
@@ -1,21 +1,21 @@
-'use strict';
+"use strict";
-var helpers = require('../helpers');
+var helpers = require("../helpers");
var runMochaJSON = helpers.runMochaJSON;
-describe('--fail-zero', function () {
- var args = ['--fail-zero', '--grep', 'yyyyyy'];
+describe("--fail-zero", function () {
+ var args = ["--fail-zero", "--grep", "yyyyyy"];
- it('should fail since no tests are encountered', function (done) {
- var fixture = '__default__.fixture.js';
+ it("should fail since no tests are encountered", function (done) {
+ var fixture = "__default__.fixture.js";
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed test count', 0)
- .and('to have test count', 0)
- .and('to have exit code', 1);
+ expect(res, "to have passed test count", 0)
+ .and("to have test count", 0)
+ .and("to have exit code", 1);
done();
});
});
diff --git a/test/integration/options/file.spec.js b/test/integration/options/file.spec.js
index 77b1b09d..2dc0756c 100644
--- a/test/integration/options/file.spec.js
+++ b/test/integration/options/file.spec.js
@@ -1,41 +1,41 @@
-'use strict';
+"use strict";
-var path = require('node:path').posix;
+var path = require("node:path").posix;
const {
runMochaJSON,
resolveFixturePath: resolvePath,
- runMocha
-} = require('../helpers');
+ runMocha,
+} = require("../helpers");
-describe('--file', function () {
+describe("--file", function () {
var args = [];
var fixtures = {
- alpha: path.join('options', 'file-alpha'),
- beta: path.join('options', 'file-beta'),
- theta: path.join('options', 'file-theta')
+ alpha: path.join("options", "file-alpha"),
+ beta: path.join("options", "file-beta"),
+ theta: path.join("options", "file-theta"),
};
- it('should run tests passed via file first', function (done) {
- args = ['--file', resolvePath(fixtures.alpha)];
+ it("should run tests passed via file first", function (done) {
+ args = ["--file", resolvePath(fixtures.alpha)];
var fixture = fixtures.beta;
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed')
- .and('to have passed test count', 2)
- .and('to have passed test order', 'should be executed first');
+ expect(res, "to have passed")
+ .and("to have passed test count", 2)
+ .and("to have passed test order", "should be executed first");
done();
});
});
- it('should run multiple tests passed via file first', function (done) {
+ it("should run multiple tests passed via file first", function (done) {
args = [
- '--file',
+ "--file",
resolvePath(fixtures.alpha),
- '--file',
- resolvePath(fixtures.beta)
+ "--file",
+ resolvePath(fixtures.beta),
];
var fixture = fixtures.theta;
@@ -43,48 +43,48 @@ describe('--file', function () {
if (err) {
return done(err);
}
- expect(res, 'to have passed')
- .and('to have passed test count', 3)
+ expect(res, "to have passed")
+ .and("to have passed test count", 3)
.and(
- 'to have passed test order',
- 'should be executed first',
- 'should be executed second',
- 'should be executed third'
+ "to have passed test order",
+ "should be executed first",
+ "should be executed second",
+ "should be executed third",
);
done();
});
});
- it('should support having no other test files', function (done) {
- args = ['--file', resolvePath(fixtures.alpha)];
+ it("should support having no other test files", function (done) {
+ args = ["--file", resolvePath(fixtures.alpha)];
- runMochaJSON('filethatdoesnotexist.js', args, function (err, res) {
+ runMochaJSON("filethatdoesnotexist.js", args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed').and('to have passed test count', 1);
+ expect(res, "to have passed").and("to have passed test count", 1);
done();
});
});
- it('should run esm tests passed via file', function (done) {
- const esmFile = 'collect-files.fixture.mjs';
- const testArgs = ['--file', resolvePath(esmFile)];
+ it("should run esm tests passed via file", function (done) {
+ const esmFile = "collect-files.fixture.mjs";
+ const testArgs = ["--file", resolvePath(esmFile)];
runMochaJSON(esmFile, testArgs, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed');
+ expect(res, "to have passed");
done();
});
});
- it('should log a warning if a nonexistent file with an unknown extension is specified', function (done) {
- const nonexistentTestFileArg = 'nonexistent.test.ts';
+ it("should log a warning if a nonexistent file with an unknown extension is specified", function (done) {
+ const nonexistentTestFileArg = "nonexistent.test.ts";
runMocha(
nonexistentTestFileArg,
- ['--file'],
+ ["--file"],
function (err, res) {
if (err) {
return done(err);
@@ -92,21 +92,21 @@ describe('--file', function () {
expect(
res.output,
- 'to contain',
- `Warning: Cannot find any files matching pattern`
- ).and('to contain', nonexistentTestFileArg);
+ "to contain",
+ `Warning: Cannot find any files matching pattern`,
+ ).and("to contain", nonexistentTestFileArg);
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
- it('should provide warning for nonexistent js file extensions', function (done) {
- const nonexistentCjsArg = 'nonexistent.test.js';
+ it("should provide warning for nonexistent js file extensions", function (done) {
+ const nonexistentCjsArg = "nonexistent.test.js";
runMocha(
nonexistentCjsArg,
- ['--file'],
+ ["--file"],
function (err, res) {
if (err) {
return done(err);
@@ -114,21 +114,21 @@ describe('--file', function () {
expect(
res.output,
- 'to contain',
- `Warning: Cannot find any files matching pattern`
- ).and('to contain', nonexistentCjsArg);
+ "to contain",
+ `Warning: Cannot find any files matching pattern`,
+ ).and("to contain", nonexistentCjsArg);
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
- it('should provide warning for nonexistent esm file extensions', function (done) {
- const nonexistentEsmArg = 'nonexistent.test.mjs';
+ it("should provide warning for nonexistent esm file extensions", function (done) {
+ const nonexistentEsmArg = "nonexistent.test.mjs";
runMocha(
nonexistentEsmArg,
- ['--file'],
+ ["--file"],
function (err, res) {
if (err) {
return done(err);
@@ -136,12 +136,12 @@ describe('--file', function () {
expect(
res.output,
- 'to contain',
- `Warning: Cannot find any files matching pattern`
- ).and('to contain', nonexistentEsmArg);
+ "to contain",
+ `Warning: Cannot find any files matching pattern`,
+ ).and("to contain", nonexistentEsmArg);
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
});
diff --git a/test/integration/options/forbidOnly.spec.js b/test/integration/options/forbidOnly.spec.js
index 7f988c14..6d28906a 100644
--- a/test/integration/options/forbidOnly.spec.js
+++ b/test/integration/options/forbidOnly.spec.js
@@ -1,32 +1,32 @@
-'use strict';
+"use strict";
-var path = require('node:path').posix;
-var helpers = require('../helpers');
+var path = require("node:path").posix;
+var helpers = require("../helpers");
var runMocha = helpers.runMocha;
var runMochaJSON = helpers.runMochaJSON;
-describe('--forbid-only', function () {
+describe("--forbid-only", function () {
var args = [];
- var onlyErrorMessage = '`.only` forbidden';
+ var onlyErrorMessage = "`.only` forbidden";
beforeEach(function () {
- args = ['--forbid-only'];
+ args = ["--forbid-only"];
});
- it('should succeed if there are only passed tests', function (done) {
- var fixture = path.join('options', 'forbid-only', 'passed');
+ it("should succeed if there are only passed tests", function (done) {
+ var fixture = path.join("options", "forbid-only", "passed");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed');
+ expect(res, "to have passed");
done();
});
});
- it('should fail if there are tests marked only', function (done) {
- var fixture = path.join('options', 'forbid-only', 'only');
- var spawnOpts = {stdio: 'pipe'};
+ it("should fail if there are tests marked only", function (done) {
+ var fixture = path.join("options", "forbid-only", "only");
+ var spawnOpts = { stdio: "pipe" };
runMocha(
fixture,
args,
@@ -34,16 +34,16 @@ describe('--forbid-only', function () {
if (err) {
return done(err);
}
- expect(res, 'to have failed with output', new RegExp(onlyErrorMessage));
+ expect(res, "to have failed with output", new RegExp(onlyErrorMessage));
done();
},
- spawnOpts
+ spawnOpts,
);
});
- it('should fail if there are tests in suites marked only', function (done) {
- var fixture = path.join('options', 'forbid-only', 'only-suite');
- var spawnOpts = {stdio: 'pipe'};
+ it("should fail if there are tests in suites marked only", function (done) {
+ var fixture = path.join("options", "forbid-only", "only-suite");
+ var spawnOpts = { stdio: "pipe" };
runMocha(
fixture,
args,
@@ -51,16 +51,16 @@ describe('--forbid-only', function () {
if (err) {
return done(err);
}
- expect(res, 'to have failed with output', new RegExp(onlyErrorMessage));
+ expect(res, "to have failed with output", new RegExp(onlyErrorMessage));
done();
},
- spawnOpts
+ spawnOpts,
);
});
- it('should fail if there is empty suite marked only', function (done) {
- var fixture = path.join('options', 'forbid-only', 'only-empty-suite');
- var spawnOpts = {stdio: 'pipe'};
+ it("should fail if there is empty suite marked only", function (done) {
+ var fixture = path.join("options", "forbid-only", "only-empty-suite");
+ var spawnOpts = { stdio: "pipe" };
runMocha(
fixture,
args,
@@ -68,67 +68,67 @@ describe('--forbid-only', function () {
if (err) {
return done(err);
}
- expect(res, 'to have failed with output', new RegExp(onlyErrorMessage));
+ expect(res, "to have failed with output", new RegExp(onlyErrorMessage));
done();
},
- spawnOpts
+ spawnOpts,
);
});
- it('should fail if there is suite marked only which matches grep', function (done) {
- var fixture = path.join('options', 'forbid-only', 'only-suite');
- var spawnOpts = {stdio: 'pipe'};
+ it("should fail if there is suite marked only which matches grep", function (done) {
+ var fixture = path.join("options", "forbid-only", "only-suite");
+ var spawnOpts = { stdio: "pipe" };
runMocha(
fixture,
- args.concat('--fgrep', 'suite marked with only'),
+ args.concat("--fgrep", "suite marked with only"),
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with output', new RegExp(onlyErrorMessage));
+ expect(res, "to have failed with output", new RegExp(onlyErrorMessage));
done();
},
- spawnOpts
+ spawnOpts,
);
});
- it('should fail if suite marked only does not match grep', function (done) {
- var fixture = path.join('options', 'forbid-only', 'only-suite');
- var spawnOpts = {stdio: 'pipe'};
+ it("should fail if suite marked only does not match grep", function (done) {
+ var fixture = path.join("options", "forbid-only", "only-suite");
+ var spawnOpts = { stdio: "pipe" };
runMocha(
fixture,
- args.concat('--fgrep', 'bumble bees'),
+ args.concat("--fgrep", "bumble bees"),
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with output', new RegExp(onlyErrorMessage));
+ expect(res, "to have failed with output", new RegExp(onlyErrorMessage));
done();
},
- spawnOpts
+ spawnOpts,
);
});
- it('should fail if suite marked only does not match inverted grep', function (done) {
- var fixture = path.join('options', 'forbid-only', 'only-suite');
- var spawnOpts = {stdio: 'pipe'};
+ it("should fail if suite marked only does not match inverted grep", function (done) {
+ var fixture = path.join("options", "forbid-only", "only-suite");
+ var spawnOpts = { stdio: "pipe" };
runMocha(
fixture,
- args.concat('--fgrep', 'suite marked with only', '--invert'),
+ args.concat("--fgrep", "suite marked with only", "--invert"),
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with output', new RegExp(onlyErrorMessage));
+ expect(res, "to have failed with output", new RegExp(onlyErrorMessage));
done();
},
- spawnOpts
+ spawnOpts,
);
});
it('should fail even if before has "skip"', function (done) {
- var fixture = path.join('options', 'forbid-only', 'only-before');
- var spawnOpts = {stdio: 'pipe'};
+ var fixture = path.join("options", "forbid-only", "only-before");
+ var spawnOpts = { stdio: "pipe" };
runMocha(
fixture,
args,
@@ -136,16 +136,16 @@ describe('--forbid-only', function () {
if (err) {
return done(err);
}
- expect(res, 'to have failed with output', new RegExp(onlyErrorMessage));
+ expect(res, "to have failed with output", new RegExp(onlyErrorMessage));
done();
},
- spawnOpts
+ spawnOpts,
);
});
it('should fail even if beforeEach has "skip"', function (done) {
- var fixture = path.join('options', 'forbid-only', 'only-before-each');
- var spawnOpts = {stdio: 'pipe'};
+ var fixture = path.join("options", "forbid-only", "only-before-each");
+ var spawnOpts = { stdio: "pipe" };
runMocha(
fixture,
args,
@@ -153,10 +153,10 @@ describe('--forbid-only', function () {
if (err) {
return done(err);
}
- expect(res, 'to have failed with output', new RegExp(onlyErrorMessage));
+ expect(res, "to have failed with output", new RegExp(onlyErrorMessage));
done();
},
- spawnOpts
+ spawnOpts,
);
});
});
diff --git a/test/integration/options/forbidPending.spec.js b/test/integration/options/forbidPending.spec.js
index dbe9848a..f16e329a 100644
--- a/test/integration/options/forbidPending.spec.js
+++ b/test/integration/options/forbidPending.spec.js
@@ -1,32 +1,32 @@
-'use strict';
+"use strict";
-var path = require('node:path').posix;
-var helpers = require('../helpers');
+var path = require("node:path").posix;
+var helpers = require("../helpers");
var runMocha = helpers.runMocha;
var runMochaJSON = helpers.runMochaJSON;
-describe('--forbid-pending', function () {
+describe("--forbid-pending", function () {
var args = [];
- var pendingErrorMessage = 'Pending test forbidden';
+ var pendingErrorMessage = "Pending test forbidden";
before(function () {
- args = ['--forbid-pending'];
+ args = ["--forbid-pending"];
});
- it('should succeed if there are only passed tests', function (done) {
- var fixture = path.join('options', 'forbid-pending', 'passed');
+ it("should succeed if there are only passed tests", function (done) {
+ var fixture = path.join("options", "forbid-pending", "passed");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed');
+ expect(res, "to have passed");
done();
});
});
- it('should fail if there are tests in suites marked skip', function (done) {
- var fixture = path.join('options', 'forbid-pending', 'skip-suite');
- var spawnOpts = {stdio: 'pipe'};
+ it("should fail if there are tests in suites marked skip", function (done) {
+ var fixture = path.join("options", "forbid-pending", "skip-suite");
+ var spawnOpts = { stdio: "pipe" };
runMocha(
fixture,
args,
@@ -34,19 +34,19 @@ describe('--forbid-pending', function () {
if (err) {
return done(err);
}
- expect(res, 'to satisfy', {
+ expect(res, "to satisfy", {
code: 1,
- output: new RegExp(pendingErrorMessage)
+ output: new RegExp(pendingErrorMessage),
});
done();
},
- spawnOpts
+ spawnOpts,
);
});
- it('should fail if there is empty suite marked pending', function (done) {
- var fixture = path.join('options', 'forbid-pending', 'skip-empty-suite');
- var spawnOpts = {stdio: 'pipe'};
+ it("should fail if there is empty suite marked pending", function (done) {
+ var fixture = path.join("options", "forbid-pending", "skip-empty-suite");
+ var spawnOpts = { stdio: "pipe" };
runMocha(
fixture,
args,
@@ -54,36 +54,36 @@ describe('--forbid-pending', function () {
if (err) {
return done(err);
}
- expect(res, 'to satisfy', {
+ expect(res, "to satisfy", {
code: 1,
- output: new RegExp(pendingErrorMessage)
+ output: new RegExp(pendingErrorMessage),
});
done();
},
- spawnOpts
+ spawnOpts,
);
});
var forbidPendingFailureTests = {
- 'should fail if there are tests marked skip': 'skip',
- 'should fail if there are pending tests': 'pending',
- 'should fail if tests call `skip()`': 'this-skip',
- 'should fail if beforeEach calls `skip()`': 'beforeEach-this-skip',
- 'should fail if before calls `skip()`': 'before-this-skip'
+ "should fail if there are tests marked skip": "skip",
+ "should fail if there are pending tests": "pending",
+ "should fail if tests call `skip()`": "this-skip",
+ "should fail if beforeEach calls `skip()`": "beforeEach-this-skip",
+ "should fail if before calls `skip()`": "before-this-skip",
};
Object.keys(forbidPendingFailureTests).forEach(function (title) {
it(title, function (done) {
var fixture = path.join(
- 'options',
- 'forbid-pending',
- forbidPendingFailureTests[title]
+ "options",
+ "forbid-pending",
+ forbidPendingFailureTests[title],
);
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', pendingErrorMessage);
+ expect(res, "to have failed with error", pendingErrorMessage);
done();
});
});
diff --git a/test/integration/options/grep.spec.js b/test/integration/options/grep.spec.js
index ac573274..950ecd61 100644
--- a/test/integration/options/grep.spec.js
+++ b/test/integration/options/grep.spec.js
@@ -1,82 +1,82 @@
-'use strict';
+"use strict";
-var helpers = require('../helpers');
+var helpers = require("../helpers");
var runMocha = helpers.runMocha;
var runMochaJSON = helpers.runMochaJSON;
-var FIXTURE = 'options/grep';
+var FIXTURE = "options/grep";
-describe('--grep', function () {
- it('should run specs matching a string', function (done) {
- runMochaJSON(FIXTURE, ['--grep', 'match'], function (err, res) {
+describe("--grep", function () {
+ it("should run specs matching a string", function (done) {
+ runMochaJSON(FIXTURE, ["--grep", "match"], function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed')
- .and('to have passed test count', 2)
- .and('not to have pending tests');
+ expect(res, "to have passed")
+ .and("to have passed test count", 2)
+ .and("not to have pending tests");
done();
});
});
- describe('should run specs matching a RegExp', function () {
- it('with RegExp-like strings (pattern followed by flag)', function (done) {
- runMochaJSON(FIXTURE, ['--grep', '/match/i'], function (err, res) {
+ describe("should run specs matching a RegExp", function () {
+ it("with RegExp-like strings (pattern followed by flag)", function (done) {
+ runMochaJSON(FIXTURE, ["--grep", "/match/i"], function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed')
- .and('to have passed test count', 4)
- .and('not to have pending tests');
+ expect(res, "to have passed")
+ .and("to have passed test count", 4)
+ .and("not to have pending tests");
done();
});
});
- it('with string as pattern', function (done) {
- runMochaJSON(FIXTURE, ['--grep', '.*'], function (err, res) {
+ it("with string as pattern", function (done) {
+ runMochaJSON(FIXTURE, ["--grep", ".*"], function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed')
- .and('to have passed test count', 4)
- .and('to have failed test count', 1)
- .and('not to have pending tests');
+ expect(res, "to have failed")
+ .and("to have passed test count", 4)
+ .and("to have failed test count", 1)
+ .and("not to have pending tests");
done();
});
});
});
- describe('when used with --invert', function () {
- it('should run specs that do not match the pattern', function (done) {
+ describe("when used with --invert", function () {
+ it("should run specs that do not match the pattern", function (done) {
runMochaJSON(
FIXTURE,
- ['--grep', 'fail', '--invert'],
+ ["--grep", "fail", "--invert"],
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed')
- .and('to have passed test count', 4)
- .and('not to have pending tests');
+ expect(res, "to have passed")
+ .and("to have passed test count", 4)
+ .and("not to have pending tests");
done();
- }
+ },
);
});
});
- describe('when both --fgrep and --grep used together', function () {
- it('should report an error', function (done) {
+ describe("when both --fgrep and --grep used together", function () {
+ it("should report an error", function (done) {
runMocha(
FIXTURE,
- ['--fgrep', 'first', '--grep', 'second'],
+ ["--fgrep", "first", "--grep", "second"],
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with output', /mutually exclusive/i);
+ expect(res, "to have failed with output", /mutually exclusive/i);
done();
},
- 'pipe'
+ "pipe",
);
});
});
diff --git a/test/integration/options/ignore.spec.js b/test/integration/options/ignore.spec.js
index 9c982f60..0414c11b 100644
--- a/test/integration/options/ignore.spec.js
+++ b/test/integration/options/ignore.spec.js
@@ -1,11 +1,11 @@
-'use strict';
+"use strict";
-var path = require('node:path').posix;
-var helpers = require('../helpers');
+var path = require("node:path").posix;
+var helpers = require("../helpers");
var runMochaJSON = helpers.runMochaJSON;
var resolvePath = helpers.resolveFixturePath;
-describe('--ignore', function () {
+describe("--ignore", function () {
/*
* Runs mocha in {path} with the given args.
* Calls handleResult with the result.
@@ -26,56 +26,56 @@ describe('--ignore', function () {
});
}
- it('should ignore specific files', function (done) {
- var fixtures = path.join('options', 'ignore', '*');
+ it("should ignore specific files", function (done) {
+ var fixtures = path.join("options", "ignore", "*");
runMochaTest(
fixtures,
[
- '--ignore',
- resolvePath(path.join('options', 'ignore', 'fail')).replace(/\\/g, '/')
+ "--ignore",
+ resolvePath(path.join("options", "ignore", "fail")).replace(/\\/g, "/"),
],
function (res) {
- expect(res, 'to have passed')
- .and('to have run test', 'should find this test')
- .and('not to have pending tests');
+ expect(res, "to have passed")
+ .and("to have run test", "should find this test")
+ .and("not to have pending tests");
},
- done
+ done,
);
});
- it('should ignore globbed files', function (done) {
- var fixtures = path.join('options', 'ignore', '**', '*');
+ it("should ignore globbed files", function (done) {
+ var fixtures = path.join("options", "ignore", "**", "*");
runMochaTest(
fixtures,
- ['--ignore', '**/fail.fixture.js'],
+ ["--ignore", "**/fail.fixture.js"],
function (res) {
- expect(res, 'to have passed')
- .and('not to have pending tests')
- .and('to have passed test count', 2);
+ expect(res, "to have passed")
+ .and("not to have pending tests")
+ .and("to have passed test count", 2);
},
- done
+ done,
);
});
- it('should ignore multiple patterns', function (done) {
- var fixtures = path.join('options', 'ignore', '**', '*');
+ it("should ignore multiple patterns", function (done) {
+ var fixtures = path.join("options", "ignore", "**", "*");
runMochaTest(
fixtures,
[
- '--ignore',
- resolvePath(path.join('options', 'ignore', 'fail')).replace(/\\/g, '/'),
- '--ignore',
- resolvePath(path.join('options', 'ignore', 'nested', 'fail')).replace(
+ "--ignore",
+ resolvePath(path.join("options", "ignore", "fail")).replace(/\\/g, "/"),
+ "--ignore",
+ resolvePath(path.join("options", "ignore", "nested", "fail")).replace(
/\\/g,
- '/'
- )
+ "/",
+ ),
],
function (res) {
- expect(res, 'to have passed')
- .and('not to have pending tests')
- .and('to have passed test count', 2);
+ expect(res, "to have passed")
+ .and("not to have pending tests")
+ .and("to have passed test count", 2);
},
- done
+ done,
);
});
});
diff --git a/test/integration/options/invert.spec.js b/test/integration/options/invert.spec.js
index 9c8b93f2..20f1e164 100644
--- a/test/integration/options/invert.spec.js
+++ b/test/integration/options/invert.spec.js
@@ -1,25 +1,25 @@
-'use strict';
+"use strict";
-var runMocha = require('../helpers').runMocha;
+var runMocha = require("../helpers").runMocha;
-describe('--invert', function () {
- describe('when used without --fgrep or --grep', function () {
- it('it should report an error', function (done) {
+describe("--invert", function () {
+ describe("when used without --fgrep or --grep", function () {
+ it("it should report an error", function (done) {
runMocha(
- 'options/grep',
- ['--invert'],
+ "options/grep",
+ ["--invert"],
function (err, res) {
if (err) {
return done(err);
}
expect(
res,
- 'to have failed with output',
- /--invert.*--grep <regexp>/
+ "to have failed with output",
+ /--invert.*--grep <regexp>/,
);
done();
},
- 'pipe'
+ "pipe",
);
});
});
diff --git a/test/integration/options/jobs.spec.js b/test/integration/options/jobs.spec.js
index 060bef7d..964c4b47 100644
--- a/test/integration/options/jobs.spec.js
+++ b/test/integration/options/jobs.spec.js
@@ -1,33 +1,33 @@
-'use strict';
+"use strict";
-var helpers = require('../helpers');
+var helpers = require("../helpers");
var runMochaAsync = helpers.runMochaAsync;
-describe('--jobs', function () {
- describe('when set to a number less than 2', function () {
- it('should run tests in serial', function () {
+describe("--jobs", function () {
+ describe("when set to a number less than 2", function () {
+ it("should run tests in serial", function () {
return expect(
runMochaAsync(
- 'options/jobs/fail-in-parallel',
- ['--parallel', '--jobs', '1'],
- 'pipe'
+ "options/jobs/fail-in-parallel",
+ ["--parallel", "--jobs", "1"],
+ "pipe",
),
- 'when fulfilled',
- 'to have passed'
+ "when fulfilled",
+ "to have passed",
);
});
});
- describe('when set to a number greater than 1', function () {
- it('should run tests in parallel', function () {
+ describe("when set to a number greater than 1", function () {
+ it("should run tests in parallel", function () {
return expect(
runMochaAsync(
- 'options/jobs/fail-in-parallel',
- ['--parallel', '--jobs', '2'],
- 'pipe'
+ "options/jobs/fail-in-parallel",
+ ["--parallel", "--jobs", "2"],
+ "pipe",
),
- 'when fulfilled',
- 'to have failed'
+ "when fulfilled",
+ "to have failed",
);
});
});
diff --git a/test/integration/options/listInterfaces.spec.js b/test/integration/options/listInterfaces.spec.js
index 025fc5f8..3502b22a 100644
--- a/test/integration/options/listInterfaces.spec.js
+++ b/test/integration/options/listInterfaces.spec.js
@@ -1,12 +1,12 @@
-'use strict';
+"use strict";
-var helpers = require('../helpers');
+var helpers = require("../helpers");
var invokeMocha = helpers.invokeMocha;
var escapeRegExp = helpers.escapeRegExp;
-var interfaces = require('../../../lib/mocha').interfaces;
+var interfaces = require("../../../lib/mocha").interfaces;
-describe('--list-interfaces', function () {
- it('should dump a list of all interfaces with descriptions', function (done) {
+describe("--list-interfaces", function () {
+ it("should dump a list of all interfaces with descriptions", function (done) {
var expected = Object.keys(interfaces)
.filter(function (name) {
return /^[a-z]/.test(name);
@@ -14,21 +14,21 @@ describe('--list-interfaces', function () {
.map(function (name) {
return {
name: escapeRegExp(name),
- description: escapeRegExp(interfaces[name].description)
+ description: escapeRegExp(interfaces[name].description),
};
});
- invokeMocha(['--list-interfaces'], function (err, result) {
+ invokeMocha(["--list-interfaces"], function (err, result) {
if (err) {
return done(err);
}
- expect(result.code, 'to be', 0);
+ expect(result.code, "to be", 0);
expected.forEach(function (ui) {
expect(
result.output,
- 'to match',
- new RegExp(ui.name + '\\s*-\\s*' + ui.description)
+ "to match",
+ new RegExp(ui.name + "\\s*-\\s*" + ui.description),
);
});
done();
diff --git a/test/integration/options/listReporters.spec.js b/test/integration/options/listReporters.spec.js
index c7557f52..f9c4dec3 100644
--- a/test/integration/options/listReporters.spec.js
+++ b/test/integration/options/listReporters.spec.js
@@ -1,12 +1,12 @@
-'use strict';
+"use strict";
-var helpers = require('../helpers');
+var helpers = require("../helpers");
var invokeMocha = helpers.invokeMocha;
var escapeRegExp = helpers.escapeRegExp;
-var reporters = require('../../../lib/mocha').reporters;
+var reporters = require("../../../lib/mocha").reporters;
-describe('--list-reporters', function () {
- it('should dump a list of all reporters with descriptions', function (done) {
+describe("--list-reporters", function () {
+ it("should dump a list of all reporters with descriptions", function (done) {
var expected = Object.keys(reporters)
.filter(function (name) {
return (
@@ -17,21 +17,21 @@ describe('--list-reporters', function () {
.map(function (name) {
return {
name: escapeRegExp(name),
- description: escapeRegExp(reporters[name].description)
+ description: escapeRegExp(reporters[name].description),
};
});
- invokeMocha(['--list-reporters'], function (err, result) {
+ invokeMocha(["--list-reporters"], function (err, result) {
if (err) {
return done(err);
}
- expect(result.code, 'to be', 0);
+ expect(result.code, "to be", 0);
expected.forEach(function (reporter) {
expect(
result.output,
- 'to match',
- new RegExp(reporter.name + '\\s*-\\s*' + reporter.description)
+ "to match",
+ new RegExp(reporter.name + "\\s*-\\s*" + reporter.description),
);
});
done();
diff --git a/test/integration/options/node-flags.spec.js b/test/integration/options/node-flags.spec.js
index 53b902f8..92ce1a7d 100644
--- a/test/integration/options/node-flags.spec.js
+++ b/test/integration/options/node-flags.spec.js
@@ -1,35 +1,35 @@
-'use strict';
+"use strict";
-var invokeMocha = require('../helpers').invokeMocha;
+var invokeMocha = require("../helpers").invokeMocha;
-describe('node flags', function () {
- it('should not consider argument values to be node flags', function (done) {
+describe("node flags", function () {
+ it("should not consider argument values to be node flags", function (done) {
invokeMocha(
- ['--require', 'trace-dependency'],
+ ["--require", "trace-dependency"],
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'not to have failed with output', /bad option/i);
+ expect(res, "not to have failed with output", /bad option/i);
done();
},
- 'pipe'
+ "pipe",
);
});
});
describe('node flags using "--node-option"', function () {
- it('should pass fake option to node and fail with node exception', function (done) {
+ it("should pass fake option to node and fail with node exception", function (done) {
invokeMocha(
- ['--node-option', 'fake-flag'],
+ ["--node-option", "fake-flag"],
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with output', /bad option: --fake-flag/i);
+ expect(res, "to have failed with output", /bad option: --fake-flag/i);
done();
},
- 'pipe'
+ "pipe",
);
});
});
diff --git a/test/integration/options/parallel.spec.js b/test/integration/options/parallel.spec.js
index 66cfaa70..a0389030 100644
--- a/test/integration/options/parallel.spec.js
+++ b/test/integration/options/parallel.spec.js
@@ -1,14 +1,14 @@
-'use strict';
-const Mocha = require('../../../lib/mocha');
+"use strict";
+const Mocha = require("../../../lib/mocha");
const {
runMochaAsync,
invokeMochaAsync,
getSummary,
- resolveFixturePath
-} = require('../helpers');
-const psList = require('ps-list').default;
+ resolveFixturePath,
+} = require("../helpers");
+const psList = require("ps-list").default;
-const REPORTER_FIXTURE_PATH = resolveFixturePath('options/parallel/test-a');
+const REPORTER_FIXTURE_PATH = resolveFixturePath("options/parallel/test-a");
/**
* Get child processes of a given PID using ps-list
@@ -21,8 +21,8 @@ async function getChildPids(pid) {
return (
(await psList())
// ppid = parent process ID
- .filter(proc => proc.ppid === pid)
- .map(proc => proc.pid)
+ .filter((proc) => proc.ppid === pid)
+ .map((proc) => proc.pid)
);
}
@@ -34,7 +34,7 @@ async function getChildPids(pid) {
* @returns {Promise<boolean>} Array with the PID if exists, null otherwise
*/
async function checkProcessExists(pid) {
- return (await psList()).some(proc => proc.pid === pid);
+ return (await psList()).some((proc) => proc.pid === pid);
}
/**
@@ -46,17 +46,21 @@ async function checkProcessExists(pid) {
async function compareReporters(reporter) {
const [actual, expected] = await Promise.all([
runMochaAsync(REPORTER_FIXTURE_PATH, [
- '--reporter',
+ "--reporter",
reporter,
- '--no-parallel'
+ "--no-parallel",
+ ]),
+ runMochaAsync(REPORTER_FIXTURE_PATH, [
+ "--reporter",
+ reporter,
+ "--parallel",
]),
- runMochaAsync(REPORTER_FIXTURE_PATH, ['--reporter', reporter, '--parallel'])
]);
// the test duration is non-deterministic, so we just fudge it
- actual.output = expected.output = expected.output.replace(/\d+m?s/g, '100ms');
+ actual.output = expected.output = expected.output.replace(/\d+m?s/g, "100ms");
- return {actual, expected};
+ return { actual, expected };
}
/**
@@ -64,13 +68,13 @@ async function compareReporters(reporter) {
* @param {string} reporter - Reporter name
*/
async function assertReporterOutputEquality(reporter) {
- const {actual, expected} = await compareReporters(reporter);
- return expect(actual, 'to satisfy', {
+ const { actual, expected } = await compareReporters(reporter);
+ return expect(actual, "to satisfy", {
passing: expected.passing,
failing: expected.failing,
pending: expected.pending,
code: expected.code,
- output: expected.output
+ output: expected.output,
});
}
@@ -83,386 +87,386 @@ async function waitForChildPids(pid) {
let childPids = [];
while (!childPids.length) {
childPids = await getChildPids(pid);
- await new Promise(resolve => setTimeout(resolve, 100));
+ await new Promise((resolve) => setTimeout(resolve, 100));
}
return childPids;
}
-describe('--parallel', function () {
- describe('when a test has a syntax error', function () {
- describe('when there is only a single test file', function () {
- it('should fail gracefully', async function () {
+describe("--parallel", function () {
+ describe("when a test has a syntax error", function () {
+ describe("when there is only a single test file", function () {
+ it("should fail gracefully", async function () {
return expect(
- runMochaAsync('options/parallel/syntax-err', ['--parallel']),
- 'when fulfilled',
- 'to have failed with output',
- /SyntaxError/
+ runMochaAsync("options/parallel/syntax-err", ["--parallel"]),
+ "when fulfilled",
+ "to have failed with output",
+ /SyntaxError/,
);
});
});
- describe('when there are multiple test files', function () {
- it('should fail gracefully', async function () {
+ describe("when there are multiple test files", function () {
+ it("should fail gracefully", async function () {
return expect(
invokeMochaAsync(
- [resolveFixturePath('options/parallel/syntax-err'), '--parallel'],
- 'pipe'
+ [resolveFixturePath("options/parallel/syntax-err"), "--parallel"],
+ "pipe",
)[1],
- 'when fulfilled',
- 'to have failed'
+ "when fulfilled",
+ "to have failed",
);
});
});
});
- describe('when used with CJS tests', function () {
- it('should have the same result as with --no-parallel', async function () {
- const expected = await runMochaAsync('options/parallel/test-*', [
- '--no-parallel'
+ describe("when used with CJS tests", function () {
+ it("should have the same result as with --no-parallel", async function () {
+ const expected = await runMochaAsync("options/parallel/test-*", [
+ "--no-parallel",
]);
return expect(
- runMochaAsync('options/parallel/test-*', ['--parallel']),
- 'to be fulfilled with value satisfying',
+ runMochaAsync("options/parallel/test-*", ["--parallel"]),
+ "to be fulfilled with value satisfying",
{
passing: expected.passing,
failing: expected.failing,
pending: expected.pending,
- code: expected.code
- }
+ code: expected.code,
+ },
);
});
});
- describe('when used with ESM tests', function () {
- it('should have the same result as with --no-parallel', async function () {
+ describe("when used with ESM tests", function () {
+ it("should have the same result as with --no-parallel", async function () {
const expected = getSummary(
await invokeMochaAsync([
- '--no-parallel',
- resolveFixturePath('esm/*.fixture.mjs')
- ])[1]
+ "--no-parallel",
+ resolveFixturePath("esm/*.fixture.mjs"),
+ ])[1],
);
const actual = getSummary(
await invokeMochaAsync([
- '--parallel',
- resolveFixturePath('esm/*.fixture.mjs')
- ])[1]
+ "--parallel",
+ resolveFixturePath("esm/*.fixture.mjs"),
+ ])[1],
);
- return expect(actual, 'to satisfy', {
+ return expect(actual, "to satisfy", {
pending: expected.pending,
passing: expected.passing,
- failing: expected.failing
+ failing: expected.failing,
});
});
});
- describe('when used with --retries', function () {
- it('should retry tests appropriately', async function () {
+ describe("when used with --retries", function () {
+ it("should retry tests appropriately", async function () {
return expect(
- runMochaAsync('options/parallel/retries-*', ['--parallel']),
- 'when fulfilled',
- 'to satisfy',
+ runMochaAsync("options/parallel/retries-*", ["--parallel"]),
+ "when fulfilled",
+ "to satisfy",
expect
- .it('to have failed')
- .and('to have passed test count', 1)
- .and('to have pending test count', 0)
- .and('to have failed test count', 1)
- .and('to contain output', /count: 3/)
+ .it("to have failed")
+ .and("to have passed test count", 1)
+ .and("to have pending test count", 0)
+ .and("to have failed test count", 1)
+ .and("to contain output", /count: 3/),
);
});
});
- describe('when used with --allow-uncaught', function () {
- it('should bubble up an exception', async function () {
+ describe("when used with --allow-uncaught", function () {
+ it("should bubble up an exception", async function () {
return expect(
invokeMochaAsync(
[
- resolveFixturePath('options/parallel/uncaught'),
- '--parallel',
- '--allow-uncaught'
+ resolveFixturePath("options/parallel/uncaught"),
+ "--parallel",
+ "--allow-uncaught",
],
- 'pipe'
+ "pipe",
)[1],
- 'when fulfilled',
- 'to satisfy',
+ "when fulfilled",
+ "to satisfy",
expect
- .it('to contain output', /Error: existential isolation/i)
- .and('to have exit code', 1)
+ .it("to contain output", /Error: existential isolation/i)
+ .and("to have exit code", 1),
);
});
});
- describe('when used with --file', function () {
- it('should error out', async function () {
+ describe("when used with --file", function () {
+ it("should error out", async function () {
return expect(
invokeMochaAsync(
[
- '--file',
- resolveFixturePath('options/parallel/test-a'),
- '--parallel'
+ "--file",
+ resolveFixturePath("options/parallel/test-a"),
+ "--parallel",
],
- 'pipe'
+ "pipe",
)[1],
- 'when fulfilled',
- 'to contain output',
- /mutually exclusive with --file/
+ "when fulfilled",
+ "to contain output",
+ /mutually exclusive with --file/,
);
});
});
- describe('when used with --sort', function () {
- it('should error out', async function () {
+ describe("when used with --sort", function () {
+ it("should error out", async function () {
return expect(
invokeMochaAsync(
[
- '--sort',
- resolveFixturePath('options/parallel/test-*'),
- '--parallel'
+ "--sort",
+ resolveFixturePath("options/parallel/test-*"),
+ "--parallel",
],
- 'pipe'
+ "pipe",
)[1],
- 'when fulfilled',
- 'to contain output',
- /mutually exclusive with --sort/
+ "when fulfilled",
+ "to contain output",
+ /mutually exclusive with --sort/,
);
});
});
- describe('when used with exclusive tests', function () {
- it('should error out', async function () {
+ describe("when used with exclusive tests", function () {
+ it("should error out", async function () {
return expect(
invokeMochaAsync(
[
- resolveFixturePath('options/parallel/exclusive-test-*'),
- '--parallel'
+ resolveFixturePath("options/parallel/exclusive-test-*"),
+ "--parallel",
],
- 'pipe'
+ "pipe",
)[1],
- 'when fulfilled',
- 'to contain output',
- /`\.only` is not supported in parallel mode/
+ "when fulfilled",
+ "to contain output",
+ /`\.only` is not supported in parallel mode/,
);
});
});
- describe('when used with --bail', function () {
- it('should skip some tests', async function () {
- const result = await runMochaAsync('options/parallel/test-*', [
- '--parallel',
- '--bail'
+ describe("when used with --bail", function () {
+ it("should skip some tests", async function () {
+ const result = await runMochaAsync("options/parallel/test-*", [
+ "--parallel",
+ "--bail",
]);
// we don't know _exactly_ how many tests will be skipped here
// due to the --bail, but the number of tests completed should be
// less than the total, which is 5.
return expect(
result.passing + result.pending + result.failing,
- 'to be less than',
- 5
+ "to be less than",
+ 5,
);
});
- it('should fail', async function () {
+ it("should fail", async function () {
return expect(
- runMochaAsync('options/parallel/test-*', ['--parallel', '--bail']),
- 'when fulfilled',
- 'to have failed'
+ runMochaAsync("options/parallel/test-*", ["--parallel", "--bail"]),
+ "when fulfilled",
+ "to have failed",
);
});
});
describe('when encountering a "bail" in context', function () {
- it('should skip some tests', async function () {
- const result = await runMochaAsync('options/parallel/bail', [
- '--parallel'
+ it("should skip some tests", async function () {
+ const result = await runMochaAsync("options/parallel/bail", [
+ "--parallel",
]);
return expect(
result.passing + result.pending + result.failing,
- 'to be less than',
- 2
+ "to be less than",
+ 2,
);
});
- it('should fail', async function () {
+ it("should fail", async function () {
return expect(
- runMochaAsync('options/parallel/bail', ['--parallel', '--bail']),
- 'when fulfilled',
- 'to have failed'
+ runMochaAsync("options/parallel/bail", ["--parallel", "--bail"]),
+ "when fulfilled",
+ "to have failed",
);
});
});
describe('when used with "grep"', function () {
- it('should be equivalent to running in serial', async function () {
- const expected = await runMochaAsync('options/parallel/test-*', [
- '--no-parallel',
- '--grep="suite d"'
+ it("should be equivalent to running in serial", async function () {
+ const expected = await runMochaAsync("options/parallel/test-*", [
+ "--no-parallel",
+ '--grep="suite d"',
]);
return expect(
- runMochaAsync('options/parallel/test-*', [
- '--parallel',
- '--grep="suite d"'
+ runMochaAsync("options/parallel/test-*", [
+ "--parallel",
+ '--grep="suite d"',
]),
- 'to be fulfilled with value satisfying',
+ "to be fulfilled with value satisfying",
{
passing: expected.passing,
failing: expected.failing,
pending: expected.pending,
- code: expected.code
- }
+ code: expected.code,
+ },
);
});
});
- describe('reporter equivalence', function () {
+ describe("reporter equivalence", function () {
// each reporter name is duplicated; one is in all lower-case
// 'base' is abstract, 'html' is browser-only, others are incompatible
- const DENY = ['progress', 'base', 'html', 'markdown', 'json-stream'];
+ const DENY = ["progress", "base", "html", "markdown", "json-stream"];
Object.keys(Mocha.reporters)
- .filter(name => /^[a-z]/.test(name) && DENY.indexOf(name) === -1)
- .forEach(reporter => {
+ .filter((name) => /^[a-z]/.test(name) && DENY.indexOf(name) === -1)
+ .forEach((reporter) => {
describe(`when multiple test files run with --reporter=${reporter}`, function () {
- it('should have the same result as when run with --no-parallel', async function () {
+ it("should have the same result as when run with --no-parallel", async function () {
// note that the output may not be in the same order, as running file
// order is non-deterministic in parallel mode
- const expected = await runMochaAsync('options/parallel/test-*', [
- '--reporter',
+ const expected = await runMochaAsync("options/parallel/test-*", [
+ "--reporter",
reporter,
- '--no-parallel'
+ "--no-parallel",
]);
return expect(
- runMochaAsync('options/parallel/test-*', [
- '--reporter',
+ runMochaAsync("options/parallel/test-*", [
+ "--reporter",
reporter,
- '--parallel'
+ "--parallel",
]),
- 'to be fulfilled with value satisfying',
+ "to be fulfilled with value satisfying",
{
passing: expected.passing,
failing: expected.failing,
pending: expected.pending,
- code: expected.code
- }
+ code: expected.code,
+ },
);
});
});
});
- describe('when a single test file is run with --reporter=dot', function () {
- it('should have the same output as when run with --no-parallel', async function () {
- return assertReporterOutputEquality.call(this, 'dot');
+ describe("when a single test file is run with --reporter=dot", function () {
+ it("should have the same output as when run with --no-parallel", async function () {
+ return assertReporterOutputEquality.call(this, "dot");
});
});
- describe('when a single test file is run with --reporter=doc', function () {
- it('should have the same output as when run with --no-parallel', async function () {
- return assertReporterOutputEquality.call(this, 'doc');
+ describe("when a single test file is run with --reporter=doc", function () {
+ it("should have the same output as when run with --no-parallel", async function () {
+ return assertReporterOutputEquality.call(this, "doc");
});
});
- describe('when a single test file is run with --reporter=tap', function () {
- it('should have the same output as when run with --no-parallel', async function () {
- return assertReporterOutputEquality.call(this, 'tap');
+ describe("when a single test file is run with --reporter=tap", function () {
+ it("should have the same output as when run with --no-parallel", async function () {
+ return assertReporterOutputEquality.call(this, "tap");
});
});
- describe('when a single test file is run with --reporter=list', function () {
- it('should have the same output as when run with --no-parallel', async function () {
- return assertReporterOutputEquality.call(this, 'list');
+ describe("when a single test file is run with --reporter=list", function () {
+ it("should have the same output as when run with --no-parallel", async function () {
+ return assertReporterOutputEquality.call(this, "list");
});
});
- describe('when a single test file is run with --reporter=min', function () {
- it('should have the same output as when run with --no-parallel', async function () {
- return assertReporterOutputEquality.call(this, 'min');
+ describe("when a single test file is run with --reporter=min", function () {
+ it("should have the same output as when run with --no-parallel", async function () {
+ return assertReporterOutputEquality.call(this, "min");
});
});
- describe('when a single test file is run with --reporter=spec', function () {
- it('should have the same output as when run with --no-parallel', async function () {
- return assertReporterOutputEquality.call(this, 'spec');
+ describe("when a single test file is run with --reporter=spec", function () {
+ it("should have the same output as when run with --no-parallel", async function () {
+ return assertReporterOutputEquality.call(this, "spec");
});
});
- describe('when a single test file is run with --reporter=nyan', function () {
- it('should have the same output as when run with --no-parallel', async function () {
- return assertReporterOutputEquality.call(this, 'nyan');
+ describe("when a single test file is run with --reporter=nyan", function () {
+ it("should have the same output as when run with --no-parallel", async function () {
+ return assertReporterOutputEquality.call(this, "nyan");
});
});
- describe('when a single test file is run with --reporter=landing', function () {
- it('should have the same output as when run with --no-parallel', async function () {
- return assertReporterOutputEquality.call(this, 'landing');
+ describe("when a single test file is run with --reporter=landing", function () {
+ it("should have the same output as when run with --no-parallel", async function () {
+ return assertReporterOutputEquality.call(this, "landing");
});
});
- describe('when a single test file is run with --reporter=progress', function () {
- it('should fail due to incompatibility', async function () {
+ describe("when a single test file is run with --reporter=progress", function () {
+ it("should fail due to incompatibility", async function () {
return expect(
invokeMochaAsync(
[
- resolveFixturePath('options/parallel/test-a'),
- '--reporter=progress',
- '--parallel'
+ resolveFixturePath("options/parallel/test-a"),
+ "--reporter=progress",
+ "--parallel",
],
- 'pipe'
+ "pipe",
)[1],
- 'when fulfilled',
- 'to satisfy',
+ "when fulfilled",
+ "to satisfy",
expect
- .it('to have failed')
- .and('to contain output', /mutually exclusive/)
+ .it("to have failed")
+ .and("to contain output", /mutually exclusive/),
);
});
});
- describe('when a single test file is run with --reporter=markdown', function () {
- it('should fail due to incompatibility', async function () {
+ describe("when a single test file is run with --reporter=markdown", function () {
+ it("should fail due to incompatibility", async function () {
return expect(
invokeMochaAsync(
[
- resolveFixturePath('options/parallel/test-a'),
- '--reporter=markdown',
- '--parallel'
+ resolveFixturePath("options/parallel/test-a"),
+ "--reporter=markdown",
+ "--parallel",
],
- 'pipe'
+ "pipe",
)[1],
- 'when fulfilled',
- 'to satisfy',
+ "when fulfilled",
+ "to satisfy",
expect
- .it('to have failed')
- .and('to contain output', /mutually exclusive/)
+ .it("to have failed")
+ .and("to contain output", /mutually exclusive/),
);
});
});
- describe('when a single test file is run with --reporter=json-stream', function () {
- it('should fail due to incompatibility', async function () {
+ describe("when a single test file is run with --reporter=json-stream", function () {
+ it("should fail due to incompatibility", async function () {
return expect(
invokeMochaAsync(
[
- resolveFixturePath('options/parallel/test-a'),
- '--reporter=json-stream',
- '--parallel'
+ resolveFixturePath("options/parallel/test-a"),
+ "--reporter=json-stream",
+ "--parallel",
],
- 'pipe'
+ "pipe",
)[1],
- 'when fulfilled',
- 'to satisfy',
+ "when fulfilled",
+ "to satisfy",
expect
- .it('to have failed')
- .and('to contain output', /mutually exclusive/)
+ .it("to have failed")
+ .and("to contain output", /mutually exclusive/),
);
});
});
- describe('when a single test file is run with --reporter=json', function () {
- it('should have the same output as when run with --no-parallel', async function () {
+ describe("when a single test file is run with --reporter=json", function () {
+ it("should have the same output as when run with --no-parallel", async function () {
// this one has some timings/durations that we can safely ignore
- const {expected, actual} = await compareReporters('json');
+ const { expected, actual } = await compareReporters("json");
expected.output = JSON.parse(expected.output);
actual.output = JSON.parse(actual.output);
- return expect(actual, 'to satisfy', {
+ return expect(actual, "to satisfy", {
passing: expected.passing,
failing: expected.failing,
pending: expected.pending,
@@ -473,30 +477,30 @@ describe('--parallel', function () {
tests: expected.output.stats.tests,
passes: expected.output.stats.passes,
pending: expected.output.stats.pending,
- failures: expected.output.stats.failures
+ failures: expected.output.stats.failures,
},
- tests: expected.tests
- }
+ tests: expected.tests,
+ },
});
});
});
- describe('when a single test file is run with --reporter=xunit', function () {
- it('should have the same output as when run with --no-parallel', async function () {
+ describe("when a single test file is run with --reporter=xunit", function () {
+ it("should have the same output as when run with --no-parallel", async function () {
// durations need replacing
- const {expected, actual} = await compareReporters('xunit');
+ const { expected, actual } = await compareReporters("xunit");
expected.output = expected.output
.replace(/time=".+?"/g, 'time="0.5"')
.replace(/timestamp=".+?"/g, 'timestamp="some-timestamp');
actual.output = actual.output
.replace(/time=".+?"/g, 'time="0.5"')
.replace(/timestamp=".+?"/g, 'timestamp="some-timestamp');
- return expect(actual, 'to satisfy', {
+ return expect(actual, "to satisfy", {
passing: expected.passing,
failing: expected.failing,
pending: expected.pending,
code: expected.code,
- output: expected.output
+ output: expected.output,
});
});
});
@@ -507,46 +511,46 @@ describe('--parallel', function () {
// kill all children
// - `checkProcessExists` validates that each child was killed
// - if any weren't killed, the test fails
- describe('pool shutdown', function () {
- describe('during normal operation', function () {
- it('should not leave orphaned processes around', async function () {
- const [{pid}, promise] = invokeMochaAsync([
- resolveFixturePath('options/parallel/test-*'),
- '--parallel'
+ describe("pool shutdown", function () {
+ describe("during normal operation", function () {
+ it("should not leave orphaned processes around", async function () {
+ const [{ pid }, promise] = invokeMochaAsync([
+ resolveFixturePath("options/parallel/test-*"),
+ "--parallel",
]);
const childPids = await waitForChildPids(pid);
await promise;
return expect(
Promise.all(
[pid, ...childPids].map(
- async childPid => await checkProcessExists(childPid)
- )
+ async (childPid) => await checkProcessExists(childPid),
+ ),
),
- 'when fulfilled',
- 'to have items satisfying',
- false
+ "when fulfilled",
+ "to have items satisfying",
+ false,
);
});
});
- describe('during operation with --bail', function () {
- it('should not leave orphaned processes around', async function () {
- const [{pid}, promise] = invokeMochaAsync([
- resolveFixturePath('options/parallel/test-*'),
- '--bail',
- '--parallel'
+ describe("during operation with --bail", function () {
+ it("should not leave orphaned processes around", async function () {
+ const [{ pid }, promise] = invokeMochaAsync([
+ resolveFixturePath("options/parallel/test-*"),
+ "--bail",
+ "--parallel",
]);
const childPids = await waitForChildPids(pid);
await promise;
return expect(
Promise.all(
[pid, ...childPids].map(
- async childPid => await checkProcessExists(childPid)
- )
+ async (childPid) => await checkProcessExists(childPid),
+ ),
),
- 'when fulfilled',
- 'to have items satisfying',
- false
+ "when fulfilled",
+ "to have items satisfying",
+ false,
);
});
});
diff --git a/test/integration/options/passOnFailingTestSuite.spec.js b/test/integration/options/passOnFailingTestSuite.spec.js
index 9f902da7..ef2f977b 100644
--- a/test/integration/options/passOnFailingTestSuite.spec.js
+++ b/test/integration/options/passOnFailingTestSuite.spec.js
@@ -1,39 +1,39 @@
-'use strict';
+"use strict";
-var helpers = require('../helpers');
+var helpers = require("../helpers");
var runMochaJSON = helpers.runMochaJSON;
-describe('Enabled --pass-on-failing-test-suite', function() {
- var args = ['--pass-on-failing-test-suite=true'];
+describe("Enabled --pass-on-failing-test-suite", function () {
+ var args = ["--pass-on-failing-test-suite=true"];
- it('Test should finish with zero code with disabled option', function(done) {
- var fixture = 'failing-sync.fixture.js';
- runMochaJSON(fixture, args, function(err, res) {
+ it("Test should finish with zero code with disabled option", function (done) {
+ var fixture = "failing-sync.fixture.js";
+ runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed test count', 0)
- .and('to have test count', 1)
- .and('to have exit code', 0);
+ expect(res, "to have passed test count", 0)
+ .and("to have test count", 1)
+ .and("to have exit code", 0);
done();
});
});
});
-describe('Disabled --pass-on-failing-test-suite', function() {
- var args = ['--pass-on-failing-test-suite=false'];
+describe("Disabled --pass-on-failing-test-suite", function () {
+ var args = ["--pass-on-failing-test-suite=false"];
- it('Test should return non-zero code with enabled option', function(done) {
- var fixture = 'failing-sync.fixture.js';
- runMochaJSON(fixture, args, function(err, res) {
+ it("Test should return non-zero code with enabled option", function (done) {
+ var fixture = "failing-sync.fixture.js";
+ runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed test count', 0)
- .and('to have test count', 1)
- .and('to have exit code', 1);
+ expect(res, "to have passed test count", 0)
+ .and("to have test count", 1)
+ .and("to have exit code", 1);
done();
});
});
diff --git a/test/integration/options/posixExitCodes.spec.js b/test/integration/options/posixExitCodes.spec.js
index 65a5c9bb..f4d3a50d 100644
--- a/test/integration/options/posixExitCodes.spec.js
+++ b/test/integration/options/posixExitCodes.spec.js
@@ -1,46 +1,46 @@
-'use strict';
+"use strict";
-var helpers = require('../helpers');
+var helpers = require("../helpers");
var runMocha = helpers.runMocha;
-var os = require('node:os');
+var os = require("node:os");
const EXIT_FAILURE = 1;
const SIGNAL_OFFSET = 128;
-describe('--posix-exit-codes', function () {
- if (os.platform() !== 'win32') {
- describe('when enabled', function () {
- describe('when mocha is run as a child process', () => {
+describe("--posix-exit-codes", function () {
+ if (os.platform() !== "win32") {
+ describe("when enabled", function () {
+ describe("when mocha is run as a child process", () => {
// 'no-warnings' node option makes mocha run as a child process
- const args = ['--no-warnings', '--posix-exit-codes'];
+ const args = ["--no-warnings", "--posix-exit-codes"];
- it('should exit with correct POSIX shell code on SIGABRT', function (done) {
- var fixture = 'signals-sigabrt.fixture.js';
+ it("should exit with correct POSIX shell code on SIGABRT", function (done) {
+ var fixture = "signals-sigabrt.fixture.js";
runMocha(fixture, args, function postmortem(err, res) {
if (err) {
return done(err);
}
expect(
res.code,
- 'to be',
- SIGNAL_OFFSET + os.constants.signals.SIGABRT
+ "to be",
+ SIGNAL_OFFSET + os.constants.signals.SIGABRT,
);
done();
});
});
- it('should exit with correct POSIX shell code on SIGTERM', function (done) {
+ it("should exit with correct POSIX shell code on SIGTERM", function (done) {
// SIGTERM is not supported on Windows
- if (os.platform() !== 'win32') {
- var fixture = 'signals-sigterm.fixture.js';
+ if (os.platform() !== "win32") {
+ var fixture = "signals-sigterm.fixture.js";
runMocha(fixture, args, function postmortem(err, res) {
if (err) {
return done(err);
}
expect(
res.code,
- 'to be',
- SIGNAL_OFFSET + os.constants.signals.SIGTERM
+ "to be",
+ SIGNAL_OFFSET + os.constants.signals.SIGTERM,
);
done();
});
@@ -49,18 +49,18 @@ describe('--posix-exit-codes', function () {
}
});
- it('should exit with the correct POSIX shell code on numeric fatal signal', function (done) {
+ it("should exit with the correct POSIX shell code on numeric fatal signal", function (done) {
// not supported on Windows
- if (os.platform() !== 'win32') {
- var fixture = 'signals-sigterm-numeric.fixture.js';
+ if (os.platform() !== "win32") {
+ var fixture = "signals-sigterm-numeric.fixture.js";
runMocha(fixture, args, function postmortem(err, res) {
if (err) {
return done(err);
}
expect(
res.code,
- 'to be',
- SIGNAL_OFFSET + os.constants.signals.SIGTERM
+ "to be",
+ SIGNAL_OFFSET + os.constants.signals.SIGTERM,
);
done();
});
@@ -69,49 +69,49 @@ describe('--posix-exit-codes', function () {
}
});
- it('should exit with code 1 if there are test failures', function (done) {
- var fixture = 'failing.fixture.js';
+ it("should exit with code 1 if there are test failures", function (done) {
+ var fixture = "failing.fixture.js";
runMocha(fixture, args, function postmortem(err, res) {
if (err) {
return done(err);
}
- expect(res.code, 'to be', EXIT_FAILURE);
+ expect(res.code, "to be", EXIT_FAILURE);
done();
});
});
});
- describe('when mocha is run in-process', () => {
+ describe("when mocha is run in-process", () => {
// Without node-specific cli options, mocha runs in-process
- const args = ['--posix-exit-codes'];
+ const args = ["--posix-exit-codes"];
- it('should exit with the correct POSIX shell code on SIGABRT', function (done) {
- var fixture = 'signals-sigabrt.fixture.js';
+ it("should exit with the correct POSIX shell code on SIGABRT", function (done) {
+ var fixture = "signals-sigabrt.fixture.js";
runMocha(fixture, args, function postmortem(err, res) {
if (err) {
return done(err);
}
expect(
res.code,
- 'to be',
- SIGNAL_OFFSET + os.constants.signals.SIGABRT
+ "to be",
+ SIGNAL_OFFSET + os.constants.signals.SIGABRT,
);
done();
});
});
- it('should exit with the correct POSIX shell code on SIGTERM', function (done) {
+ it("should exit with the correct POSIX shell code on SIGTERM", function (done) {
// SIGTERM is not supported on Windows
- if (os.platform() !== 'win32') {
- var fixture = 'signals-sigterm.fixture.js';
+ if (os.platform() !== "win32") {
+ var fixture = "signals-sigterm.fixture.js";
runMocha(fixture, args, function postmortem(err, res) {
if (err) {
return done(err);
}
expect(
res.code,
- 'to be',
- SIGNAL_OFFSET + os.constants.signals.SIGTERM
+ "to be",
+ SIGNAL_OFFSET + os.constants.signals.SIGTERM,
);
done();
});
@@ -120,48 +120,48 @@ describe('--posix-exit-codes', function () {
}
});
- it('should exit with code 1 if there are test failures', function (done) {
- var fixture = 'failing.fixture.js';
+ it("should exit with code 1 if there are test failures", function (done) {
+ var fixture = "failing.fixture.js";
runMocha(fixture, args, function postmortem(err, res) {
if (err) {
return done(err);
}
- expect(res.code, 'to be', EXIT_FAILURE);
+ expect(res.code, "to be", EXIT_FAILURE);
done();
});
});
});
});
- describe('when not enabled', function () {
- describe('when mocha is run as a child process', () => {
+ describe("when not enabled", function () {
+ describe("when mocha is run as a child process", () => {
// any node-specific option makes mocha run as a child process
- var args = ['--no-warnings'];
+ var args = ["--no-warnings"];
- it('should exit with the number of failed tests', function (done) {
- var fixture = 'failing.fixture.js';
+ it("should exit with the number of failed tests", function (done) {
+ var fixture = "failing.fixture.js";
var numFailures = 3;
runMocha(fixture, args, function postmortem(err, res) {
if (err) {
return done(err);
}
- expect(res.code, 'to be', numFailures);
+ expect(res.code, "to be", numFailures);
done();
});
});
});
- describe('when mocha is run in-process', () => {
+ describe("when mocha is run in-process", () => {
var args = [];
- it('should exit with the number of failed tests', function (done) {
- var fixture = 'failing.fixture.js';
+ it("should exit with the number of failed tests", function (done) {
+ var fixture = "failing.fixture.js";
var numFailures = 3;
runMocha(fixture, args, function postmortem(err, res) {
if (err) {
return done(err);
}
- expect(res.code, 'to be', numFailures);
+ expect(res.code, "to be", numFailures);
done();
});
});
diff --git a/test/integration/options/reporter-option.spec.js b/test/integration/options/reporter-option.spec.js
index 513d8e03..9fbbdaee 100644
--- a/test/integration/options/reporter-option.spec.js
+++ b/test/integration/options/reporter-option.spec.js
@@ -1,85 +1,85 @@
-'use strict';
+"use strict";
-var runMocha = require('../helpers').runMocha;
-var path = require('node:path');
+var runMocha = require("../helpers").runMocha;
+var path = require("node:path");
-describe('--reporter-option', function () {
- describe('when given options w/ invalid format', function () {
- it('should display an error', function (done) {
+describe("--reporter-option", function () {
+ describe("when given options w/ invalid format", function () {
+ it("should display an error", function (done) {
runMocha(
- 'passing.fixture.js',
- ['--reporter-option', 'foo=bar=baz'],
+ "passing.fixture.js",
+ ["--reporter-option", "foo=bar=baz"],
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed').and(
- 'to contain output',
- /invalid reporter option/i
+ expect(res, "to have failed").and(
+ "to contain output",
+ /invalid reporter option/i,
);
done();
},
- 'pipe'
+ "pipe",
);
});
- it('should allow comma-separated values', function (done) {
+ it("should allow comma-separated values", function (done) {
runMocha(
- 'passing.fixture.js',
+ "passing.fixture.js",
[
- '--reporter',
+ "--reporter",
path.join(
__dirname,
- '..',
- 'fixtures',
- 'options',
- 'reporter-with-options.fixture.js'
+ "..",
+ "fixtures",
+ "options",
+ "reporter-with-options.fixture.js",
),
- '--reporter-option',
- 'foo=bar,baz=quux'
+ "--reporter-option",
+ "foo=bar,baz=quux",
],
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed').and(
- 'to contain output',
- /{"foo":"bar","baz":"quux"}/
+ expect(res, "to have passed").and(
+ "to contain output",
+ /{"foo":"bar","baz":"quux"}/,
);
done();
},
- 'pipe'
+ "pipe",
);
});
- it('should allow repeated options', function (done) {
+ it("should allow repeated options", function (done) {
runMocha(
- 'passing.fixture.js',
+ "passing.fixture.js",
[
- '--reporter',
+ "--reporter",
path.join(
__dirname,
- '..',
- 'fixtures',
- 'options',
- 'reporter-with-options.fixture.js'
+ "..",
+ "fixtures",
+ "options",
+ "reporter-with-options.fixture.js",
),
- '--reporter-option',
- 'foo=bar',
- '--reporter-option',
- 'baz=quux'
+ "--reporter-option",
+ "foo=bar",
+ "--reporter-option",
+ "baz=quux",
],
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed').and(
- 'to contain output',
- /{"foo":"bar","baz":"quux"}/
+ expect(res, "to have passed").and(
+ "to contain output",
+ /{"foo":"bar","baz":"quux"}/,
);
done();
},
- 'pipe'
+ "pipe",
);
});
});
diff --git a/test/integration/options/retries.spec.js b/test/integration/options/retries.spec.js
index c08d0c03..01385e1f 100644
--- a/test/integration/options/retries.spec.js
+++ b/test/integration/options/retries.spec.js
@@ -1,23 +1,23 @@
-'use strict';
+"use strict";
-var path = require('node:path').posix;
-var helpers = require('../helpers');
+var path = require("node:path").posix;
+var helpers = require("../helpers");
var runMochaJSON = helpers.runMochaJSON;
-describe('--retries', function () {
+describe("--retries", function () {
var args = [];
- it('should retry test failures after a certain threshold', function (done) {
- args = ['--retries', '3'];
- var fixture = path.join('options', 'retries');
+ it("should retry test failures after a certain threshold", function (done) {
+ args = ["--retries", "3"];
+ var fixture = path.join("options", "retries");
runMochaJSON(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed')
- .and('not to have pending tests')
- .and('not to have passed tests')
- .and('to have retried test', 'should fail', 3);
+ expect(res, "to have failed")
+ .and("not to have pending tests")
+ .and("not to have passed tests")
+ .and("to have retried test", "should fail", 3);
done();
});
});
diff --git a/test/integration/options/sort.spec.js b/test/integration/options/sort.spec.js
index 8e34f906..0ac3a9e8 100644
--- a/test/integration/options/sort.spec.js
+++ b/test/integration/options/sort.spec.js
@@ -1,26 +1,26 @@
-'use strict';
+"use strict";
-var path = require('node:path').posix;
-var helpers = require('../helpers');
+var path = require("node:path").posix;
+var helpers = require("../helpers");
var runMochaJSON = helpers.runMochaJSON;
-describe('--sort', function () {
+describe("--sort", function () {
var args = [];
before(function () {
- args = ['--sort'];
+ args = ["--sort"];
});
- it('should sort tests in alphabetical order', function (done) {
- var fixtures = path.join('options', 'sort*');
+ it("should sort tests in alphabetical order", function (done) {
+ var fixtures = path.join("options", "sort*");
runMochaJSON(fixtures, args, function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have passed test count', 2).and(
- 'to have passed test order',
- 'should be executed first'
+ expect(res, "to have passed test count", 2).and(
+ "to have passed test order",
+ "should be executed first",
);
done();
});
diff --git a/test/integration/options/timeout.spec.js b/test/integration/options/timeout.spec.js
index e3ac696e..8145579f 100644
--- a/test/integration/options/timeout.spec.js
+++ b/test/integration/options/timeout.spec.js
@@ -1,97 +1,101 @@
-'use strict';
+"use strict";
-var helpers = require('../helpers');
+var helpers = require("../helpers");
var runMochaJSON = helpers.runMochaJSON;
-describe('--timeout', function () {
- it('should allow human-readable string value', function (done) {
- runMochaJSON('options/slow-test', ['--timeout', '1s'], function (err, res) {
+describe("--timeout", function () {
+ it("should allow human-readable string value", function (done) {
+ runMochaJSON("options/slow-test", ["--timeout", "1s"], function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have failed')
- .and('to have passed test count', 1)
- .and('to have failed test count', 1);
+ expect(res, "to have failed")
+ .and("to have passed test count", 1)
+ .and("to have failed test count", 1);
done();
});
});
- it('should allow numeric value', function (done) {
+ it("should allow numeric value", function (done) {
runMochaJSON(
- 'options/slow-test',
- ['--timeout', '1000'],
+ "options/slow-test",
+ ["--timeout", "1000"],
function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have failed')
- .and('to have passed test count', 1)
- .and('to have failed test count', 1);
+ expect(res, "to have failed")
+ .and("to have passed test count", 1)
+ .and("to have failed test count", 1);
done();
- }
+ },
);
});
- it('should allow multiple values', function (done) {
- var fixture = 'options/slow-test';
+ it("should allow multiple values", function (done) {
+ var fixture = "options/slow-test";
runMochaJSON(
fixture,
- ['--timeout', '2s', '--timeout', '1000'],
+ ["--timeout", "2s", "--timeout", "1000"],
function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have failed')
- .and('to have passed test count', 1)
- .and('to have failed test count', 1);
+ expect(res, "to have failed")
+ .and("to have passed test count", 1)
+ .and("to have failed test count", 1);
done();
- }
+ },
);
});
it('should disable timeout with "--inspect"', function (done) {
- var fixture = 'options/slow-test';
+ var fixture = "options/slow-test";
runMochaJSON(
fixture,
- ['--inspect', '--timeout', '200'],
+ ["--inspect", "--timeout", "200"],
function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have passed').and('to have passed test count', 2);
+ expect(res, "to have passed").and("to have passed test count", 2);
done();
- }
+ },
);
});
it('should disable timeout with "-n inspect"', function (done) {
- var fixture = 'options/slow-test';
+ var fixture = "options/slow-test";
runMochaJSON(
fixture,
- ['-n', 'inspect', '--timeout', '200'],
+ ["-n", "inspect", "--timeout", "200"],
function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have passed').and('to have passed test count', 2);
+ expect(res, "to have passed").and("to have passed test count", 2);
done();
- }
+ },
);
});
- it("should complete tests having unref'd async behavior", function(done) {
- runMochaJSON('options/timeout-unref', ['--timeout', '0'], function(err, res) {
- if (err) {
- done(err);
- return;
- }
- expect(res, 'to have passed').and('to have passed test count', 1);
- done();
- });
+ it("should complete tests having unref'd async behavior", function (done) {
+ runMochaJSON(
+ "options/timeout-unref",
+ ["--timeout", "0"],
+ function (err, res) {
+ if (err) {
+ done(err);
+ return;
+ }
+ expect(res, "to have passed").and("to have passed test count", 1);
+ done();
+ },
+ );
});
});
diff --git a/test/integration/options/ui.spec.js b/test/integration/options/ui.spec.js
index 58f745cd..870ea4b5 100644
--- a/test/integration/options/ui.spec.js
+++ b/test/integration/options/ui.spec.js
@@ -1,38 +1,38 @@
-'use strict';
+"use strict";
-var helpers = require('../helpers');
+var helpers = require("../helpers");
var runMochaJSON = helpers.runMochaJSON;
-describe('--ui', function () {
- var simpleUiPath = require.resolve('../fixtures/simple-ui.fixture');
+describe("--ui", function () {
+ var simpleUiPath = require.resolve("../fixtures/simple-ui.fixture");
- it('should load interface and run it', function (done) {
+ it("should load interface and run it", function (done) {
runMochaJSON(
- 'test-for-simple-ui',
- ['--ui', simpleUiPath],
+ "test-for-simple-ui",
+ ["--ui", simpleUiPath],
function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have passed');
+ expect(res, "to have passed");
done();
- }
+ },
);
});
it("should work if required and name added to Mocha's `interfaces` prop", function (done) {
runMochaJSON(
- 'test-for-simple-ui',
- ['--require', simpleUiPath, '--ui', 'simple-ui'],
+ "test-for-simple-ui",
+ ["--require", simpleUiPath, "--ui", "simple-ui"],
function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have passed');
+ expect(res, "to have passed");
done();
- }
+ },
);
});
});
diff --git a/test/integration/options/watch.spec.js b/test/integration/options/watch.spec.js
index 7e3759d0..8729171a 100644
--- a/test/integration/options/watch.spec.js
+++ b/test/integration/options/watch.spec.js
@@ -1,7 +1,7 @@
-'use strict';
+"use strict";
-const fs = require('node:fs');
-const path = require('node:path');
+const fs = require("node:fs");
+const path = require("node:path");
const {
copyFixture,
runMochaWatchJSONAsync,
@@ -10,11 +10,11 @@ const {
touchFile,
replaceFileContents,
createTempDir,
- DEFAULT_FIXTURE
-} = require('../helpers');
+ DEFAULT_FIXTURE,
+} = require("../helpers");
-describe('--watch', function () {
- describe('when enabled', function () {
+describe("--watch", function () {
+ describe("when enabled", function () {
/**
* @type {string}
*/
@@ -27,7 +27,7 @@ describe('--watch', function () {
this.slow(5000);
beforeEach(async function () {
- const {dirpath, removeTempDir} = await createTempDir();
+ const { dirpath, removeTempDir } = await createTempDir();
tempDir = dirpath;
cleanup = removeTempDir;
});
@@ -36,101 +36,101 @@ describe('--watch', function () {
cleanup();
});
- it('reruns test when watched test file is touched', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when watched test file is touched", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
return runMochaWatchJSONAsync([testFile], tempDir, () => {
touchFile(testFile);
- }).then(results => {
- expect(results, 'to have length', 2);
+ }).then((results) => {
+ expect(results, "to have length", 2);
});
});
- it('reruns test when watched test file crashes', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when watched test file crashes", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- replaceFileContents(testFile, 'done();', 'done((;');
+ replaceFileContents(testFile, "done();", "done((;");
return runMochaWatchJSONAsync([testFile], tempDir, () => {
- replaceFileContents(testFile, 'done((;', 'done();');
- }).then(results => {
- expect(results, 'to have length', 1);
+ replaceFileContents(testFile, "done((;", "done();");
+ }).then((results) => {
+ expect(results, "to have length", 1);
});
});
- describe('when in parallel mode', function () {
- it('reruns test when watched test file is touched', function () {
- const testFile = path.join(tempDir, 'test.js');
+ describe("when in parallel mode", function () {
+ it("reruns test when watched test file is touched", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- return runMochaWatchJSONAsync(['--parallel', testFile], tempDir, () => {
+ return runMochaWatchJSONAsync(["--parallel", testFile], tempDir, () => {
touchFile(testFile);
- }).then(results => {
- expect(results, 'to have length', 2);
+ }).then((results) => {
+ expect(results, "to have length", 2);
});
});
- it('reruns test when watched test file is crashed', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when watched test file is crashed", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- replaceFileContents(testFile, 'done();', 'done((;');
+ replaceFileContents(testFile, "done();", "done((;");
return runMochaWatchJSONAsync([testFile], tempDir, () => {
- replaceFileContents(testFile, 'done((;', 'done();');
- }).then(results => {
- expect(results, 'to have length', 1);
+ replaceFileContents(testFile, "done((;", "done();");
+ }).then((results) => {
+ expect(results, "to have length", 1);
});
});
});
- it('reruns test when file matching --watch-files changes', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when file matching --watch-files changes", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'dir/file.xyz');
+ const watchedFile = path.join(tempDir, "dir/file.xyz");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', 'dir/*.xyz'],
+ [testFile, "--watch-files", "dir/*.xyz"],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results.length, 'to equal', 2);
+ },
+ ).then((results) => {
+ expect(results.length, "to equal", 2);
});
});
- it('reruns test when file matching --watch-files is added', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when file matching --watch-files is added", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'lib/file.xyz');
+ const watchedFile = path.join(tempDir, "lib/file.xyz");
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', '**/*.xyz'],
+ [testFile, "--watch-files", "**/*.xyz"],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
});
});
- it('reruns test when file and directory paths under --watch-files are added', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when file and directory paths under --watch-files are added", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
// only create 'lib', 'dir', and 'file.xyz' when watching
- const libPath = path.join(tempDir, 'lib');
- const dirPath = path.join(libPath, 'dir');
- const watchedFile = path.join(dirPath, 'file.xyz');
+ const libPath = path.join(tempDir, "lib");
+ const dirPath = path.join(libPath, "dir");
+ const watchedFile = path.join(dirPath, "file.xyz");
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', 'lib'],
+ [testFile, "--watch-files", "lib"],
tempDir,
async () => {
fs.mkdirSync(libPath);
@@ -140,365 +140,361 @@ describe('--watch', function () {
await sleep(1000);
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results, 'to have length', 4);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 4);
});
});
- it('reruns test when file matching --watch-files is removed', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when file matching --watch-files is removed", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'lib/file.xyz');
+ const watchedFile = path.join(tempDir, "lib/file.xyz");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', 'lib/**/*.xyz'],
+ [testFile, "--watch-files", "lib/**/*.xyz"],
tempDir,
() => {
fs.rmSync(watchedFile, { recursive: true, force: true });
- }
- ).then(results => {
- expect(results, 'to have length', 2);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
});
});
- it('reruns test when file matching exact --watch-files changes', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when file matching exact --watch-files changes", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'lib/file.xyz');
+ const watchedFile = path.join(tempDir, "lib/file.xyz");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', 'lib/file.xyz'],
+ [testFile, "--watch-files", "lib/file.xyz"],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
});
});
- it('reruns test when file under --watch-files changes', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when file under --watch-files changes", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'lib/dir/file.xyz');
+ const watchedFile = path.join(tempDir, "lib/dir/file.xyz");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', 'lib'],
+ [testFile, "--watch-files", "lib"],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
});
});
- it('reruns test when file matching --watch-files starting with a glob pattern changes', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when file matching --watch-files starting with a glob pattern changes", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'lib/dir/file.xyz');
+ const watchedFile = path.join(tempDir, "lib/dir/file.xyz");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', '**/lib'],
+ [testFile, "--watch-files", "**/lib"],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
});
});
- it('reruns test when file matching --watch-files ending with a glob pattern changes', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when file matching --watch-files ending with a glob pattern changes", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'lib/dir/file.xyz');
+ const watchedFile = path.join(tempDir, "lib/dir/file.xyz");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', 'lib/**/*'],
+ [testFile, "--watch-files", "lib/**/*"],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
});
});
- it('reruns test when file matching --watch-files with glob pattern in between changes', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when file matching --watch-files with glob pattern in between changes", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'lib/dir/file.xyz');
+ const watchedFile = path.join(tempDir, "lib/dir/file.xyz");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', 'lib/**/dir'],
+ [testFile, "--watch-files", "lib/**/dir"],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
});
});
- it('reruns test when file matching --watch-files outside the current working directory changes', function () {
+ it("reruns test when file matching --watch-files outside the current working directory changes", function () {
// create a subdirectory to watch as the current working directory
- const tempCwd = path.join(tempDir, 'dir');
- const testFile = path.join(tempCwd, 'test.js');
+ const tempCwd = path.join(tempDir, "dir");
+ const testFile = path.join(tempCwd, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'lib/file.xyz');
+ const watchedFile = path.join(tempDir, "lib/file.xyz");
touchFile(watchedFile);
// use an absolute path for the watch file pattern,
// otherwise it would be read relative to the current working directory
- const watchFilePattern = path.join(tempDir, 'lib/**/*.xyz');
+ const watchFilePattern = path.join(tempDir, "lib/**/*.xyz");
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', watchFilePattern],
+ [testFile, "--watch-files", watchFilePattern],
tempCwd,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
});
});
- it('does not rerun test when file not matching --watch-files is changed', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("does not rerun test when file not matching --watch-files is changed", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'dir/file.js');
+ const watchedFile = path.join(tempDir, "dir/file.js");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', 'dir/*.xyz'],
+ [testFile, "--watch-files", "dir/*.xyz"],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results.length, 'to equal', 1);
+ },
+ ).then((results) => {
+ expect(results.length, "to equal", 1);
});
});
- it('picks up new test files when they are added', function () {
- const testFile = path.join(tempDir, 'test/a.js');
+ it("picks up new test files when they are added", function () {
+ const testFile = path.join(tempDir, "test/a.js");
copyFixture(DEFAULT_FIXTURE, testFile);
return runMochaWatchJSONAsync(
- ['test/**/*.js', '--watch-files', 'test/**/*.js'],
+ ["test/**/*.js", "--watch-files", "test/**/*.js"],
tempDir,
() => {
- const addedTestFile = path.join(tempDir, 'test/b.js');
- copyFixture('passing', addedTestFile);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
- expect(results[0].passes, 'to have length', 1);
- expect(results[1].passes, 'to have length', 3);
+ const addedTestFile = path.join(tempDir, "test/b.js");
+ copyFixture("passing", addedTestFile);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
+ expect(results[0].passes, "to have length", 1);
+ expect(results[1].passes, "to have length", 3);
});
});
- it('reruns test when file matching --extension is changed', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when file matching --extension is changed", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'file.xyz');
+ const watchedFile = path.join(tempDir, "file.xyz");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
- [testFile, '--extension', 'xyz,js'],
+ [testFile, "--extension", "xyz,js"],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
});
});
it('reruns when "rs\\n" typed', function () {
- const testFile = path.join(tempDir, 'test.js');
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- return runMochaWatchJSONAsync([testFile], tempDir, mochaProcess => {
- mochaProcess.stdin.write('rs\n');
- }).then(results => {
- expect(results, 'to have length', 2);
+ return runMochaWatchJSONAsync([testFile], tempDir, (mochaProcess) => {
+ mochaProcess.stdin.write("rs\n");
+ }).then((results) => {
+ expect(results, "to have length", 2);
});
});
- it('reruns test when file starting with . and matching --extension is changed', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("reruns test when file starting with . and matching --extension is changed", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, '.file.xyz');
+ const watchedFile = path.join(tempDir, ".file.xyz");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
- [testFile, '--extension', 'xyz,js'],
+ [testFile, "--extension", "xyz,js"],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
});
});
it('ignores files in "node_modules" and ".git" by default', function () {
- const testFile = path.join(tempDir, 'test.js');
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const nodeModulesFile = path.join(tempDir, 'node_modules', 'file.xyz');
- const gitFile = path.join(tempDir, '.git', 'file.xyz');
+ const nodeModulesFile = path.join(tempDir, "node_modules", "file.xyz");
+ const gitFile = path.join(tempDir, ".git", "file.xyz");
touchFile(gitFile);
touchFile(nodeModulesFile);
return runMochaWatchJSONAsync(
- [testFile, '--extension', 'xyz,js'],
+ [testFile, "--extension", "xyz,js"],
tempDir,
() => {
touchFile(gitFile);
touchFile(nodeModulesFile);
- }
- ).then(results => {
- expect(results, 'to have length', 1);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 1);
});
});
- it('ignores files matching --watch-ignore', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("ignores files matching --watch-ignore", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'dir/file-to-ignore.xyz');
+ const watchedFile = path.join(tempDir, "dir/file-to-ignore.xyz");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
[
testFile,
- '--watch-files',
- 'dir/*.xyz',
- '--watch-ignore',
- 'dir/*ignore*'
+ "--watch-files",
+ "dir/*.xyz",
+ "--watch-ignore",
+ "dir/*ignore*",
],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results.length, 'to equal', 1);
+ },
+ ).then((results) => {
+ expect(results.length, "to equal", 1);
});
});
// Workaround: escape via e.g. `dir/[[]ab[]].js`
- it('ignores files whose name is the watch glob', function () {
- const testFile = path.join(tempDir, 'test.js');
+ it("ignores files whose name is the watch glob", function () {
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
- const watchedFile = path.join(tempDir, 'dir/[ab].js');
+ const watchedFile = path.join(tempDir, "dir/[ab].js");
touchFile(watchedFile);
return runMochaWatchJSONAsync(
- [
- testFile,
- '--watch-files',
- 'dir/[ab].js',
- ],
+ [testFile, "--watch-files", "dir/[ab].js"],
tempDir,
() => {
touchFile(watchedFile);
- }
- ).then(results => {
- expect(results.length, 'to equal', 1);
+ },
+ ).then((results) => {
+ expect(results.length, "to equal", 1);
});
});
- it('reloads test files when they change', function () {
- const testFile = path.join(tempDir, 'test.js');
- copyFixture('options/watch/test-file-change', testFile);
+ it("reloads test files when they change", function () {
+ const testFile = path.join(tempDir, "test.js");
+ copyFixture("options/watch/test-file-change", testFile);
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', '**/*.js'],
+ [testFile, "--watch-files", "**/*.js"],
tempDir,
() => {
replaceFileContents(
testFile,
- 'testShouldFail = true',
- 'testShouldFail = false'
+ "testShouldFail = true",
+ "testShouldFail = false",
);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
- expect(results[0].passes, 'to have length', 0);
- expect(results[0].failures, 'to have length', 1);
- expect(results[1].passes, 'to have length', 1);
- expect(results[1].failures, 'to have length', 0);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
+ expect(results[0].passes, "to have length", 0);
+ expect(results[0].failures, "to have length", 1);
+ expect(results[1].passes, "to have length", 1);
+ expect(results[1].failures, "to have length", 0);
});
});
- it('reloads test dependencies when they change', function () {
- const testFile = path.join(tempDir, 'test.js');
- copyFixture('options/watch/test-with-dependency', testFile);
+ it("reloads test dependencies when they change", function () {
+ const testFile = path.join(tempDir, "test.js");
+ copyFixture("options/watch/test-with-dependency", testFile);
- const dependency = path.join(tempDir, 'lib', 'dependency.js');
- copyFixture('options/watch/dependency', dependency);
+ const dependency = path.join(tempDir, "lib", "dependency.js");
+ copyFixture("options/watch/dependency", dependency);
return runMochaWatchJSONAsync(
- [testFile, '--watch-files', 'lib/**/*.js'],
+ [testFile, "--watch-files", "lib/**/*.js"],
tempDir,
() => {
replaceFileContents(
dependency,
- 'module.exports.testShouldFail = false',
- 'module.exports.testShouldFail = true'
+ "module.exports.testShouldFail = false",
+ "module.exports.testShouldFail = true",
);
- }
- ).then(results => {
- expect(results, 'to have length', 2);
- expect(results[0].passes, 'to have length', 1);
- expect(results[0].failures, 'to have length', 0);
- expect(results[1].passes, 'to have length', 0);
- expect(results[1].failures, 'to have length', 1);
+ },
+ ).then((results) => {
+ expect(results, "to have length", 2);
+ expect(results[0].passes, "to have length", 1);
+ expect(results[0].failures, "to have length", 0);
+ expect(results[1].passes, "to have length", 0);
+ expect(results[1].failures, "to have length", 1);
});
});
// Regression test for https://github.com/mochajs/mocha/issues/2027
- it('respects --fgrep on re-runs', async function () {
- const testFile = path.join(tempDir, 'test.js');
- copyFixture('options/grep', testFile);
+ it("respects --fgrep on re-runs", async function () {
+ const testFile = path.join(tempDir, "test.js");
+ copyFixture("options/grep", testFile);
return expect(
- runMochaWatchJSONAsync([testFile, '--fgrep', 'match'], tempDir, () => {
+ runMochaWatchJSONAsync([testFile, "--fgrep", "match"], tempDir, () => {
touchFile(testFile);
}),
- 'when fulfilled',
- 'to satisfy',
+ "when fulfilled",
+ "to satisfy",
{
length: 2,
- 0: {tests: expect.it('to have length', 2)},
- 1: {tests: expect.it('to have length', 2)}
- }
+ 0: { tests: expect.it("to have length", 2) },
+ 1: { tests: expect.it("to have length", 2) },
+ },
);
});
- describe('with required hooks', function () {
+ describe("with required hooks", function () {
/**
* Helper for setting up hook tests
*
@@ -507,43 +503,43 @@ describe('--watch', function () {
*/
function setupHookTest(hookName) {
return function () {
- const testFile = path.join(tempDir, 'test.js');
- const hookFile = path.join(tempDir, 'hook.js');
+ const testFile = path.join(tempDir, "test.js");
+ const hookFile = path.join(tempDir, "hook.js");
- copyFixture('__default__', testFile);
- copyFixture('options/watch/hook', hookFile);
+ copyFixture("__default__", testFile);
+ copyFixture("options/watch/hook", hookFile);
- replaceFileContents(hookFile, '<hook>', hookName);
+ replaceFileContents(hookFile, "<hook>", hookName);
return runMochaWatchJSONAsync(
- [testFile, '--require', hookFile],
+ [testFile, "--require", hookFile],
tempDir,
() => {
touchFile(testFile);
- }
- ).then(results => {
- expect(results.length, 'to equal', 2);
- expect(results[0].failures, 'to have length', 1);
- expect(results[1].failures, 'to have length', 1);
+ },
+ ).then((results) => {
+ expect(results.length, "to equal", 2);
+ expect(results[0].failures, "to have length", 1);
+ expect(results[1].failures, "to have length", 1);
});
};
}
- it('mochaHooks.beforeAll runs as expected', setupHookTest('beforeAll'));
- it('mochaHooks.beforeEach runs as expected', setupHookTest('beforeEach'));
- it('mochaHooks.afterAll runs as expected', setupHookTest('afterAll'));
- it('mochaHooks.afterEach runs as expected', setupHookTest('afterEach'));
+ it("mochaHooks.beforeAll runs as expected", setupHookTest("beforeAll"));
+ it("mochaHooks.beforeEach runs as expected", setupHookTest("beforeEach"));
+ it("mochaHooks.afterAll runs as expected", setupHookTest("afterAll"));
+ it("mochaHooks.afterEach runs as expected", setupHookTest("afterEach"));
});
- it('should not leak event listeners', function () {
+ it("should not leak event listeners", function () {
this.timeout(20000);
- const testFile = path.join(tempDir, 'test.js');
+ const testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
return expect(
runMochaWatchAsync(
[testFile],
- {cwd: tempDir, stdio: 'pipe'},
+ { cwd: tempDir, stdio: "pipe" },
async () => {
// we want to cause _n + 1_ reruns, which should cause the warning
// to occur if the listeners aren't properly destroyed
@@ -553,13 +549,13 @@ describe('--watch', function () {
touchFile(testFile);
await sleep(1000);
}
- }
+ },
),
- 'when fulfilled',
- 'to satisfy',
+ "when fulfilled",
+ "to satisfy",
{
- output: expect.it('not to match', /MaxListenersExceededWarning/)
- }
+ output: expect.it("not to match", /MaxListenersExceededWarning/),
+ },
);
});
});
diff --git a/test/integration/parallel.spec.js b/test/integration/parallel.spec.js
index 51cde34a..c6b46b29 100644
--- a/test/integration/parallel.spec.js
+++ b/test/integration/parallel.spec.js
@@ -1,86 +1,97 @@
-'use strict';
+"use strict";
-const assert = require('node:assert');
-const {runMochaJSONAsync} = require('./helpers');
+const assert = require("node:assert");
+const { runMochaJSONAsync } = require("./helpers");
-describe('parallel run', () => {
+describe("parallel run", () => {
/**
* @see https://github.com/mochajs/mocha/issues/4559
*/
it('should allow `import {it} from "mocha"` module syntax', async () => {
- const result = await runMochaJSONAsync('parallel/test3.mjs', [
- '--parallel',
- '--jobs',
- '2',
- require.resolve('./fixtures/parallel/test1.mjs'),
- require.resolve('./fixtures/parallel/test2.mjs')
+ const result = await runMochaJSONAsync("parallel/test3.mjs", [
+ "--parallel",
+ "--jobs",
+ "2",
+ require.resolve("./fixtures/parallel/test1.mjs"),
+ require.resolve("./fixtures/parallel/test2.mjs"),
]);
assert.strictEqual(result.stats.failures, 1);
assert.strictEqual(result.stats.passes, 2);
});
- it('should correctly set worker ids for each process', async () => {
- const result = await runMochaJSONAsync('parallel/testworkerid3.mjs', [
- '--parallel',
- '--jobs',
- '2',
- require.resolve('./fixtures/parallel/testworkerid1.mjs'),
- require.resolve('./fixtures/parallel/testworkerid2.mjs')
+ it("should correctly set worker ids for each process", async () => {
+ const result = await runMochaJSONAsync("parallel/testworkerid3.mjs", [
+ "--parallel",
+ "--jobs",
+ "2",
+ require.resolve("./fixtures/parallel/testworkerid1.mjs"),
+ require.resolve("./fixtures/parallel/testworkerid2.mjs"),
]);
assert.strictEqual(result.stats.failures, 0);
assert.strictEqual(result.stats.passes, 3);
});
- it('should correctly handle circular array references in an exception', async () => {
- const result = await runMochaJSONAsync('parallel/circular-error-array.mjs', [
- '--parallel',
- '--jobs',
- '2',
- require.resolve('./fixtures/parallel/testworkerid1.mjs')
- ]);
+ it("should correctly handle circular array references in an exception", async () => {
+ const result = await runMochaJSONAsync(
+ "parallel/circular-error-array.mjs",
+ [
+ "--parallel",
+ "--jobs",
+ "2",
+ require.resolve("./fixtures/parallel/testworkerid1.mjs"),
+ ],
+ );
assert.strictEqual(result.stats.failures, 1);
assert.strictEqual(result.stats.passes, 1);
- assert.strictEqual(result.failures[0].err.message, 'Foo');
- assert.strictEqual(result.failures[0].err.foo.props[0], '[Circular]');
+ assert.strictEqual(result.failures[0].err.message, "Foo");
+ assert.strictEqual(result.failures[0].err.foo.props[0], "[Circular]");
});
- it('should correctly handle an exception with retries', async () => {
- const result = await runMochaJSONAsync('parallel/circular-error-array.mjs', [
- '--parallel',
- '--jobs',
- '2',
- '--retries',
- '1',
- require.resolve('./fixtures/parallel/testworkerid1.mjs')
- ]);
+ it("should correctly handle an exception with retries", async () => {
+ const result = await runMochaJSONAsync(
+ "parallel/circular-error-array.mjs",
+ [
+ "--parallel",
+ "--jobs",
+ "2",
+ "--retries",
+ "1",
+ require.resolve("./fixtures/parallel/testworkerid1.mjs"),
+ ],
+ );
assert.strictEqual(result.stats.failures, 1);
assert.strictEqual(result.stats.passes, 1);
- assert.strictEqual(result.failures[0].err.message, 'Foo');
- assert.strictEqual(result.failures[0].err.foo.props[0], '[Circular]');
+ assert.strictEqual(result.failures[0].err.message, "Foo");
+ assert.strictEqual(result.failures[0].err.foo.props[0], "[Circular]");
});
- it('should correctly handle circular object references in an exception', async () => {
- const result = await runMochaJSONAsync('parallel/circular-error-object.mjs', [
- '--parallel',
- '--jobs',
- '2',
- require.resolve('./fixtures/parallel/testworkerid1.mjs')
- ]);
+ it("should correctly handle circular object references in an exception", async () => {
+ const result = await runMochaJSONAsync(
+ "parallel/circular-error-object.mjs",
+ [
+ "--parallel",
+ "--jobs",
+ "2",
+ require.resolve("./fixtures/parallel/testworkerid1.mjs"),
+ ],
+ );
assert.strictEqual(result.stats.failures, 1);
assert.strictEqual(result.stats.passes, 1);
- assert.strictEqual(result.failures[0].err.message, 'Oh no!');
- assert.deepStrictEqual(result.failures[0].err.values, [ { toB: { toA: '[Circular]' } } ]);
+ assert.strictEqual(result.failures[0].err.message, "Oh no!");
+ assert.deepStrictEqual(result.failures[0].err.values, [
+ { toB: { toA: "[Circular]" } },
+ ]);
});
- it('should correctly handle a non-writable getter reference in an exception', async () => {
- const result = await runMochaJSONAsync('parallel/getter-error-object.mjs', [
- '--parallel',
- '--jobs',
- '2',
- require.resolve('./fixtures/parallel/testworkerid1.mjs')
+ it("should correctly handle a non-writable getter reference in an exception", async () => {
+ const result = await runMochaJSONAsync("parallel/getter-error-object.mjs", [
+ "--parallel",
+ "--jobs",
+ "2",
+ require.resolve("./fixtures/parallel/testworkerid1.mjs"),
]);
assert.strictEqual(result.stats.failures, 1);
assert.strictEqual(result.stats.passes, 1);
- assert.strictEqual(result.failures[0].err.message, 'Oh no!');
+ assert.strictEqual(result.failures[0].err.message, "Oh no!");
});
});
diff --git a/test/integration/pending.spec.js b/test/integration/pending.spec.js
index 921c39c6..11ad7ead 100644
--- a/test/integration/pending.spec.js
+++ b/test/integration/pending.spec.js
@@ -1,16 +1,16 @@
-'use strict';
+"use strict";
-var assert = require('node:assert');
-var helpers = require('./helpers');
+var assert = require("node:assert");
+var helpers = require("./helpers");
var run = helpers.runMochaJSON;
var invokeNode = helpers.invokeNode;
var toJSONResult = helpers.toJSONResult;
var args = [];
-describe('pending', function () {
- describe('pending specs', function () {
- it('should be created by omitting a function', function (done) {
- run('pending/spec.fixture.js', args, function (err, res) {
+describe("pending", function () {
+ describe("pending specs", function () {
+ it("should be created by omitting a function", function (done) {
+ run("pending/spec.fixture.js", args, function (err, res) {
if (err) {
done(err);
return;
@@ -22,8 +22,8 @@ describe('pending', function () {
done();
});
});
- it('should return the test object when used via shorthand methods', function (done) {
- run('pending/skip-shorthand.fixture.js', args, function (err, res) {
+ it("should return the test object when used via shorthand methods", function (done) {
+ run("pending/skip-shorthand.fixture.js", args, function (err, res) {
if (err) {
done(err);
return;
@@ -35,8 +35,8 @@ describe('pending', function () {
done();
});
});
- it('should keep hierarchies of suites', function (done) {
- run('pending/skip-hierarchy.fixture.js', args, function (err, res) {
+ it("should keep hierarchies of suites", function (done) {
+ run("pending/skip-hierarchy.fixture.js", args, function (err, res) {
if (err) {
done(err);
return;
@@ -48,55 +48,55 @@ describe('pending', function () {
assert.strictEqual(res.code, 0);
assert.strictEqual(
res.passes[0].fullTitle,
- 'a suite another suite a test'
+ "a suite another suite a test",
);
done();
});
});
});
- describe('synchronous skip()', function () {
- describe('in spec', function () {
- it('should immediately skip the spec and run all others', function (done) {
- run('pending/skip-sync-spec.fixture.js', args, function (err, res) {
+ describe("synchronous skip()", function () {
+ describe("in spec", function () {
+ it("should immediately skip the spec and run all others", function (done) {
+ run("pending/skip-sync-spec.fixture.js", args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'should throw this error')
- .and('to have failed test count', 1)
- .and('to have pending test count', 1)
- .and('to have pending test order', 'should skip immediately')
- .and('to have passed test count', 1)
- .and('to have passed tests', 'should run other tests in suite');
+ expect(res, "to have failed with error", "should throw this error")
+ .and("to have failed test count", 1)
+ .and("to have pending test count", 1)
+ .and("to have pending test order", "should skip immediately")
+ .and("to have passed test count", 1)
+ .and("to have passed tests", "should run other tests in suite");
done();
});
});
});
- describe('in after', function () {
- it('should throw, but run all tests', function (done) {
- run('pending/skip-sync-after.fixture.js', args, function (err, res) {
+ describe("in after", function () {
+ it("should throw, but run all tests", function (done) {
+ run("pending/skip-sync-after.fixture.js", args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', '`this.skip` forbidden')
- .and('to have failed test count', 1)
- .and('to have pending test count', 0)
- .and('to have passed test count', 3)
+ expect(res, "to have failed with error", "`this.skip` forbidden")
+ .and("to have failed test count", 1)
+ .and("to have pending test count", 0)
+ .and("to have passed test count", 3)
.and(
- 'to have passed test order',
- 'should run this test-1',
- 'should run this test-2',
- 'should run this test-3'
+ "to have passed test order",
+ "should run this test-1",
+ "should run this test-2",
+ "should run this test-3",
);
done();
});
});
});
- describe('in before', function () {
- it('should skip all suite specs', function (done) {
- run('pending/skip-sync-before.fixture.js', args, function (err, res) {
+ describe("in before", function () {
+ it("should skip all suite specs", function (done) {
+ run("pending/skip-sync-before.fixture.js", args, function (err, res) {
if (err) {
done(err);
return;
@@ -108,46 +108,46 @@ describe('pending', function () {
done();
});
});
- it('should run before and after hooks', function (done) {
- run('pending/skip-sync-before-hooks.fixture.js', function (err, res) {
+ it("should run before and after hooks", function (done) {
+ run("pending/skip-sync-before-hooks.fixture.js", function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'should throw this error')
- .and('to have failed test count', 1)
- .and('to have pending test count', 2)
- .and('to have passed test count', 2)
+ expect(res, "to have failed with error", "should throw this error")
+ .and("to have failed test count", 1)
+ .and("to have pending test count", 2)
+ .and("to have passed test count", 2)
.and(
- 'to have passed test order',
- 'should run test-1',
- 'should run test-2'
+ "to have passed test order",
+ "should run test-1",
+ "should run test-2",
);
done();
});
});
- it('should skip all sync/async inner before/after hooks', function (done) {
- run('pending/skip-sync-before-inner.fixture.js', function (err, res) {
+ it("should skip all sync/async inner before/after hooks", function (done) {
+ run("pending/skip-sync-before-inner.fixture.js", function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'should throw this error')
- .and('to have failed test count', 1)
- .and('to have pending test count', 2)
- .and('to have passed test count', 0)
+ expect(res, "to have failed with error", "should throw this error")
+ .and("to have failed test count", 1)
+ .and("to have pending test count", 2)
+ .and("to have passed test count", 0)
.and(
- 'to have pending test order',
- 'should never run this outer test',
- 'should never run this inner test'
+ "to have pending test order",
+ "should never run this outer test",
+ "should never run this inner test",
);
done();
});
});
});
- describe('in before with nested describe', function () {
- it('should skip all suite specs, even if nested', function (done) {
+ describe("in before with nested describe", function () {
+ it("should skip all suite specs, even if nested", function (done) {
run(
- 'pending/skip-sync-before-nested.fixture.js',
+ "pending/skip-sync-before-nested.fixture.js",
args,
function (err, res) {
if (err) {
@@ -159,74 +159,74 @@ describe('pending', function () {
assert.strictEqual(res.stats.failures, 0);
assert.strictEqual(res.code, 0);
done();
- }
+ },
);
});
});
- describe('in beforeEach', function () {
- it('should skip all suite specs', function (done) {
- var fixture = 'pending/skip-sync-beforeEach.fixture.js';
+ describe("in beforeEach", function () {
+ it("should skip all suite specs", function (done) {
+ var fixture = "pending/skip-sync-beforeEach.fixture.js";
run(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'should throw this error')
- .and('to have failed test count', 1)
- .and('to have pending test count', 3)
+ expect(res, "to have failed with error", "should throw this error")
+ .and("to have failed test count", 1)
+ .and("to have pending test count", 3)
.and(
- 'to have pending test order',
- 'should skip this test-1',
- 'should skip this test-2',
- 'should skip this test-3'
+ "to have pending test order",
+ "should skip this test-1",
+ "should skip this test-2",
+ "should skip this test-3",
)
- .and('to have passed test count', 0);
+ .and("to have passed test count", 0);
done();
});
});
- it('should skip only two suite specs', function (done) {
- var fixture = 'pending/skip-sync-beforeEach-cond.fixture.js';
+ it("should skip only two suite specs", function (done) {
+ var fixture = "pending/skip-sync-beforeEach-cond.fixture.js";
run(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'should throw this error')
- .and('to have failed test count', 1)
- .and('to have pending test count', 2)
+ expect(res, "to have failed with error", "should throw this error")
+ .and("to have failed test count", 1)
+ .and("to have pending test count", 2)
.and(
- 'to have pending test order',
- 'should skip this test-1',
- 'should skip this test-3'
+ "to have pending test order",
+ "should skip this test-1",
+ "should skip this test-3",
)
- .and('to have passed test count', 1)
- .and('to have passed test', 'should run this test-2');
+ .and("to have passed test count", 1)
+ .and("to have passed test", "should run this test-2");
done();
});
});
});
});
- describe('asynchronous skip()', function () {
- describe('in spec', function () {
- it('should immediately skip the spec and run all others', function (done) {
- run('pending/skip-async-spec.fixture.js', args, function (err, res) {
+ describe("asynchronous skip()", function () {
+ describe("in spec", function () {
+ it("should immediately skip the spec and run all others", function (done) {
+ run("pending/skip-async-spec.fixture.js", args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'should throw this error')
- .and('to have failed test count', 1)
- .and('to have pending test count', 1)
- .and('to have pending test order', 'should skip async')
- .and('to have passed test count', 1)
- .and('to have passed tests', 'should run other tests in suite');
+ expect(res, "to have failed with error", "should throw this error")
+ .and("to have failed test count", 1)
+ .and("to have pending test count", 1)
+ .and("to have pending test order", "should skip async")
+ .and("to have passed test count", 1)
+ .and("to have passed tests", "should run other tests in suite");
done();
});
});
});
- describe('in before', function () {
- it('should skip all suite specs', function (done) {
- run('pending/skip-async-before.fixture.js', args, function (err, res) {
+ describe("in before", function () {
+ it("should skip all suite specs", function (done) {
+ run("pending/skip-async-before.fixture.js", args, function (err, res) {
if (err) {
done(err);
return;
@@ -238,29 +238,29 @@ describe('pending', function () {
done();
});
});
- it('should run before and after hooks', function (done) {
- run('pending/skip-async-before-hooks.fixture.js', function (err, res) {
+ it("should run before and after hooks", function (done) {
+ run("pending/skip-async-before-hooks.fixture.js", function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'should throw this error')
- .and('to have failed test count', 1)
- .and('to have pending test count', 2)
- .and('to have passed test count', 2)
+ expect(res, "to have failed with error", "should throw this error")
+ .and("to have failed test count", 1)
+ .and("to have pending test count", 2)
+ .and("to have passed test count", 2)
.and(
- 'to have passed test order',
- 'should run test-1',
- 'should run test-2'
+ "to have passed test order",
+ "should run test-1",
+ "should run test-2",
);
done();
});
});
});
- describe('in before with nested describe', function () {
- it('should skip all suite specs, even if nested', function (done) {
+ describe("in before with nested describe", function () {
+ it("should skip all suite specs, even if nested", function (done) {
run(
- 'pending/skip-async-before-nested.fixture.js',
+ "pending/skip-async-before-nested.fixture.js",
args,
function (err, res) {
if (err) {
@@ -272,46 +272,46 @@ describe('pending', function () {
assert.strictEqual(res.stats.failures, 0);
assert.strictEqual(res.code, 0);
done();
- }
+ },
);
});
});
- describe('in beforeEach', function () {
- it('should skip all suite specs', function (done) {
- var fixture = 'pending/skip-async-beforeEach.fixture.js';
+ describe("in beforeEach", function () {
+ it("should skip all suite specs", function (done) {
+ var fixture = "pending/skip-async-beforeEach.fixture.js";
run(fixture, args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'should throw this error')
- .and('to have failed test count', 1)
- .and('to have pending test count', 3)
+ expect(res, "to have failed with error", "should throw this error")
+ .and("to have failed test count", 1)
+ .and("to have pending test count", 3)
.and(
- 'to have pending test order',
- 'should skip this test-1',
- 'should skip this test-2',
- 'should skip this test-3'
+ "to have pending test order",
+ "should skip this test-1",
+ "should skip this test-2",
+ "should skip this test-3",
)
- .and('to have passed test count', 0);
+ .and("to have passed test count", 0);
done();
});
});
});
});
- describe('programmatic usage', function () {
- it('should skip the test by listening to test event', function (done) {
- var path = require.resolve('./fixtures/pending/programmatic.fixture.js');
+ describe("programmatic usage", function () {
+ it("should skip the test by listening to test event", function (done) {
+ var path = require.resolve("./fixtures/pending/programmatic.fixture.js");
invokeNode([path], function (err, res) {
if (err) {
return done(err);
}
var result = toJSONResult(res);
- expect(result, 'to have passed')
- .and('to have passed test count', 0)
- .and('to have pending test count', 1)
- .and('to have pending test order', 'should succeed');
+ expect(result, "to have passed")
+ .and("to have passed test count", 0)
+ .and("to have pending test count", 1)
+ .and("to have pending test order", "should succeed");
done();
});
});
diff --git a/test/integration/plugins/global-fixtures.spec.js b/test/integration/plugins/global-fixtures.spec.js
index eecd2978..69bde3de 100644
--- a/test/integration/plugins/global-fixtures.spec.js
+++ b/test/integration/plugins/global-fixtures.spec.js
@@ -1,6 +1,6 @@
-'use strict';
+"use strict";
-const path = require('node:path');
+const path = require("node:path");
const {
touchFile,
runMochaAsync,
@@ -8,79 +8,79 @@ const {
copyFixture,
DEFAULT_FIXTURE,
resolveFixturePath,
- createTempDir
-} = require('../helpers');
+ createTempDir,
+} = require("../helpers");
-describe('global setup/teardown', function () {
- describe('when mocha run in serial mode', function () {
- it('should execute global setup and teardown', async function () {
+describe("global setup/teardown", function () {
+ describe("when mocha run in serial mode", function () {
+ it("should execute global setup and teardown", async function () {
return expect(
runMochaAsync(DEFAULT_FIXTURE, [
- '--require',
- resolveFixturePath('plugins/global-fixtures/global-setup-teardown')
+ "--require",
+ resolveFixturePath("plugins/global-fixtures/global-setup-teardown"),
]),
- 'when fulfilled',
- 'to have passed'
+ "when fulfilled",
+ "to have passed",
);
});
- describe('when only global teardown is supplied', function () {
- it('should run global teardown', async function () {
+ describe("when only global teardown is supplied", function () {
+ it("should run global teardown", async function () {
return expect(
runMochaAsync(DEFAULT_FIXTURE, [
- '--require',
- resolveFixturePath('plugins/global-fixtures/global-teardown')
+ "--require",
+ resolveFixturePath("plugins/global-fixtures/global-teardown"),
]),
- 'when fulfilled',
- 'to contain once',
- /teardown schmeardown/
+ "when fulfilled",
+ "to contain once",
+ /teardown schmeardown/,
);
});
});
- describe('when only global setup is supplied', function () {
- it('should run global setup', async function () {
+ describe("when only global setup is supplied", function () {
+ it("should run global setup", async function () {
return expect(
runMochaAsync(DEFAULT_FIXTURE, [
- '--require',
- resolveFixturePath('plugins/global-fixtures/global-setup')
+ "--require",
+ resolveFixturePath("plugins/global-fixtures/global-setup"),
]),
- 'when fulfilled',
- 'to contain once',
- /setup schmetup/
+ "when fulfilled",
+ "to contain once",
+ /setup schmetup/,
);
});
});
- it('should share context', async function () {
+ it("should share context", async function () {
return expect(
runMochaAsync(DEFAULT_FIXTURE, [
- '--require',
- resolveFixturePath('plugins/global-fixtures/global-setup-teardown')
+ "--require",
+ resolveFixturePath("plugins/global-fixtures/global-setup-teardown"),
]),
- 'when fulfilled',
- 'to contain once',
- /setup: this\.foo = bar[\s\S]+teardown: this\.foo = bar/
+ "when fulfilled",
+ "to contain once",
+ /setup: this\.foo = bar[\s\S]+teardown: this\.foo = bar/,
);
});
- describe('when supplied multiple functions', function () {
- it('should execute them sequentially', async function () {
+ describe("when supplied multiple functions", function () {
+ it("should execute them sequentially", async function () {
return expect(
runMochaAsync(DEFAULT_FIXTURE, [
- '--require',
+ "--require",
resolveFixturePath(
- 'plugins/global-fixtures/global-setup-teardown-multiple'
- )
+ "plugins/global-fixtures/global-setup-teardown-multiple",
+ ),
]),
- 'when fulfilled',
- 'to contain once',
- /teardown: this.foo = 3/
+ "when fulfilled",
+ "to contain once",
+ /teardown: this.foo = 3/,
);
});
});
- describe('when run in watch mode', function () {
+ describe("when run in watch mode", function () {
let tempDir;
let testFile;
let removeTempDir;
@@ -89,7 +89,7 @@ describe('global setup/teardown', function () {
const tempInfo = await createTempDir();
tempDir = tempInfo.dirpath;
removeTempDir = tempInfo.removeTempDir;
- testFile = path.join(tempDir, 'test.js');
+ testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
});
@@ -99,135 +99,135 @@ describe('global setup/teardown', function () {
}
});
- it('should execute global setup and teardown', async function () {
+ it("should execute global setup and teardown", async function () {
return expect(
runMochaWatchAsync(
[
- '--require',
+ "--require",
resolveFixturePath(
- 'plugins/global-fixtures/global-setup-teardown'
+ "plugins/global-fixtures/global-setup-teardown",
),
- testFile
+ testFile,
],
tempDir,
() => {
touchFile(testFile);
- }
+ },
),
- 'when fulfilled',
- 'to have passed'
+ "when fulfilled",
+ "to have passed",
);
});
- describe('when only global teardown is supplied', function () {
- it('should run global teardown', async function () {
+ describe("when only global teardown is supplied", function () {
+ it("should run global teardown", async function () {
return expect(
runMochaWatchAsync(
[
- '--require',
- resolveFixturePath('plugins/global-fixtures/global-teardown'),
- testFile
+ "--require",
+ resolveFixturePath("plugins/global-fixtures/global-teardown"),
+ testFile,
],
tempDir,
() => {
touchFile(testFile);
- }
+ },
),
- 'when fulfilled',
- 'to contain once',
- /teardown schmeardown/
+ "when fulfilled",
+ "to contain once",
+ /teardown schmeardown/,
);
});
});
- describe('when only global setup is supplied', function () {
- it('should run global setup', async function () {
+ describe("when only global setup is supplied", function () {
+ it("should run global setup", async function () {
return expect(
runMochaWatchAsync(
[
- '--require',
- resolveFixturePath('plugins/global-fixtures/global-setup'),
- testFile
+ "--require",
+ resolveFixturePath("plugins/global-fixtures/global-setup"),
+ testFile,
],
tempDir,
() => {
touchFile(testFile);
- }
+ },
),
- 'when fulfilled',
- 'to contain once',
- /setup schmetup/
+ "when fulfilled",
+ "to contain once",
+ /setup schmetup/,
);
});
});
- it('should not re-execute the global fixtures', async function () {
+ it("should not re-execute the global fixtures", async function () {
return expect(
runMochaWatchAsync(
[
- '--require',
+ "--require",
resolveFixturePath(
- 'plugins/global-fixtures/global-setup-teardown-multiple'
+ "plugins/global-fixtures/global-setup-teardown-multiple",
),
- testFile
+ testFile,
],
tempDir,
() => {
touchFile(testFile);
- }
+ },
),
- 'when fulfilled',
- 'to contain once',
- /teardown: this.foo = 3/
+ "when fulfilled",
+ "to contain once",
+ /teardown: this.foo = 3/,
);
});
});
});
- describe('when mocha run in parallel mode', function () {
- it('should execute global setup and teardown', async function () {
+ describe("when mocha run in parallel mode", function () {
+ it("should execute global setup and teardown", async function () {
return expect(
runMochaAsync(DEFAULT_FIXTURE, [
- '--parallel',
- '--require',
- resolveFixturePath('plugins/global-fixtures/global-setup-teardown')
+ "--parallel",
+ "--require",
+ resolveFixturePath("plugins/global-fixtures/global-setup-teardown"),
]),
- 'when fulfilled',
- 'to have passed'
+ "when fulfilled",
+ "to have passed",
);
});
- it('should share context', async function () {
+ it("should share context", async function () {
return expect(
runMochaAsync(DEFAULT_FIXTURE, [
- '--parallel',
- '--require',
- resolveFixturePath('plugins/global-fixtures/global-setup-teardown')
+ "--parallel",
+ "--require",
+ resolveFixturePath("plugins/global-fixtures/global-setup-teardown"),
]),
- 'when fulfilled',
- 'to contain once',
- /setup: this.foo = bar/
- ).and('when fulfilled', 'to contain once', /teardown: this.foo = bar/);
+ "when fulfilled",
+ "to contain once",
+ /setup: this.foo = bar/,
+ ).and("when fulfilled", "to contain once", /teardown: this.foo = bar/);
});
- describe('when supplied multiple functions', function () {
- it('should execute them sequentially', async function () {
+ describe("when supplied multiple functions", function () {
+ it("should execute them sequentially", async function () {
return expect(
runMochaAsync(DEFAULT_FIXTURE, [
- '--parallel',
- '--require',
+ "--parallel",
+ "--require",
resolveFixturePath(
- 'plugins/global-fixtures/global-setup-teardown-multiple'
- )
+ "plugins/global-fixtures/global-setup-teardown-multiple",
+ ),
]),
- 'when fulfilled',
- 'to contain once',
- /teardown: this.foo = 3/
+ "when fulfilled",
+ "to contain once",
+ /teardown: this.foo = 3/,
);
});
});
- describe('when run in watch mode', function () {
+ describe("when run in watch mode", function () {
let tempDir;
let testFile;
let removeTempDir;
@@ -236,7 +236,7 @@ describe('global setup/teardown', function () {
const tempInfo = await createTempDir();
tempDir = tempInfo.dirpath;
removeTempDir = tempInfo.removeTempDir;
- testFile = path.join(tempDir, 'test.js');
+ testFile = path.join(tempDir, "test.js");
copyFixture(DEFAULT_FIXTURE, testFile);
});
@@ -246,46 +246,46 @@ describe('global setup/teardown', function () {
}
});
- it('should execute global setup and teardown', async function () {
+ it("should execute global setup and teardown", async function () {
return expect(
runMochaWatchAsync(
[
- '--parallel',
- '--require',
+ "--parallel",
+ "--require",
resolveFixturePath(
- 'plugins/global-fixtures/global-setup-teardown'
+ "plugins/global-fixtures/global-setup-teardown",
),
- testFile
+ testFile,
],
tempDir,
() => {
touchFile(testFile);
- }
+ },
),
- 'when fulfilled',
- 'to have passed'
+ "when fulfilled",
+ "to have passed",
);
});
- it('should not re-execute the global fixtures', async function () {
+ it("should not re-execute the global fixtures", async function () {
return expect(
runMochaWatchAsync(
[
- '--parallel',
- '--require',
+ "--parallel",
+ "--require",
resolveFixturePath(
- 'plugins/global-fixtures/global-setup-teardown-multiple'
+ "plugins/global-fixtures/global-setup-teardown-multiple",
),
- testFile
+ testFile,
],
tempDir,
() => {
touchFile(testFile);
- }
+ },
),
- 'when fulfilled',
- 'to contain once',
- /teardown: this.foo = 3/
+ "when fulfilled",
+ "to contain once",
+ /teardown: this.foo = 3/,
);
});
});
diff --git a/test/integration/plugins/root-hooks.spec.js b/test/integration/plugins/root-hooks.spec.js
index 9fbdb141..9aa234d4 100644
--- a/test/integration/plugins/root-hooks.spec.js
+++ b/test/integration/plugins/root-hooks.spec.js
@@ -1,7 +1,7 @@
-'use strict';
+"use strict";
-var invokeMochaAsync = require('../helpers').invokeMochaAsync;
-const semver = require('semver');
+var invokeMochaAsync = require("../helpers").invokeMochaAsync;
+const semver = require("semver");
/**
* Extracts root hook log messages from run results
@@ -12,7 +12,7 @@ const semver = require('semver');
function extractHookOutputFromResult(res) {
return res.output
.trim()
- .split('\n')
+ .split("\n")
.filter(function (line) {
// every line that begins with whitespace (e.g., the test name) should be ignored;
// we just want the console.log messages
@@ -30,113 +30,113 @@ function runMochaForHookOutput(args, opts) {
return invokeMochaAsync(args, opts)[1].then(extractHookOutputFromResult);
}
-describe('root hooks', function () {
- describe('when mocha run in serial mode', function () {
- it('should run root hooks when provided via mochaHooks object export', function () {
+describe("root hooks", function () {
+ describe("when mocha run in serial mode", function () {
+ it("should run root hooks when provided via mochaHooks object export", function () {
return expect(
runMochaForHookOutput([
- '--require=' +
+ "--require=" +
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js",
),
- '--require=' +
+ "--require=" +
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-defs-b.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-defs-b.fixture.js",
),
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
- )
+ "../fixtures/plugins/root-hooks/root-hook-test.fixture.js",
+ ),
]),
- 'to be fulfilled with',
+ "to be fulfilled with",
[
- 'afterAll',
- 'afterAll array 1',
- 'afterAll array 2',
- 'afterEach',
- 'afterEach array 1',
- 'afterEach array 2',
- 'beforeAll',
- 'beforeAll array 1',
- 'beforeAll array 2',
- 'beforeEach',
- 'beforeEach array 1',
- 'beforeEach array 2'
- ]
+ "afterAll",
+ "afterAll array 1",
+ "afterAll array 2",
+ "afterEach",
+ "afterEach array 1",
+ "afterEach array 2",
+ "beforeAll",
+ "beforeAll array 1",
+ "beforeAll array 2",
+ "beforeEach",
+ "beforeEach array 1",
+ "beforeEach array 2",
+ ],
);
});
- it('should run root hooks when provided via mochaHooks function export', function () {
+ it("should run root hooks when provided via mochaHooks function export", function () {
return expect(
runMochaForHookOutput([
- '--require=' +
+ "--require=" +
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-defs-c.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-defs-c.fixture.js",
),
- '--require=' +
+ "--require=" +
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-defs-d.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-defs-d.fixture.js",
),
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
- )
+ "../fixtures/plugins/root-hooks/root-hook-test.fixture.js",
+ ),
]),
- 'to be fulfilled with',
+ "to be fulfilled with",
[
- 'afterAll',
- 'afterAll array 1',
- 'afterAll array 2',
- 'afterEach',
- 'afterEach array 1',
- 'afterEach array 2',
- 'beforeAll',
- 'beforeAll array 1',
- 'beforeAll array 2',
- 'beforeEach',
- 'beforeEach array 1',
- 'beforeEach array 2'
- ]
+ "afterAll",
+ "afterAll array 1",
+ "afterAll array 2",
+ "afterEach",
+ "afterEach array 1",
+ "afterEach array 2",
+ "beforeAll",
+ "beforeAll array 1",
+ "beforeAll array 2",
+ "beforeEach",
+ "beforeEach array 1",
+ "beforeEach array 2",
+ ],
);
});
- describe('support ESM when type=module or .mjs extension', function () {
- it('should run root hooks when provided via mochaHooks', function () {
+ describe("support ESM when type=module or .mjs extension", function () {
+ it("should run root hooks when provided via mochaHooks", function () {
return expect(
runMochaForHookOutput([
- '--require=' +
+ "--require=" +
require.resolve(
// as object
- '../fixtures/plugins/root-hooks/root-hook-defs-esm.fixture.mjs'
+ "../fixtures/plugins/root-hooks/root-hook-defs-esm.fixture.mjs",
),
- '--require=' +
+ "--require=" +
require.resolve(
// as function
- '../fixtures/plugins/root-hooks/esm/root-hook-defs-esm.fixture.js'
+ "../fixtures/plugins/root-hooks/esm/root-hook-defs-esm.fixture.js",
),
- '--require=' +
+ "--require=" +
require.resolve(
// mixed with commonjs
- '../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js",
),
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
- )
+ "../fixtures/plugins/root-hooks/root-hook-test.fixture.js",
+ ),
]),
- 'to be fulfilled with',
+ "to be fulfilled with",
[
- 'afterAll',
- 'afterEach',
- 'beforeAll',
- 'beforeEach',
- 'esm afterEach',
- 'esm beforeEach',
- 'mjs afterAll',
- 'mjs beforeAll'
- ]
+ "afterAll",
+ "afterEach",
+ "beforeAll",
+ "beforeEach",
+ "esm afterEach",
+ "esm beforeEach",
+ "mjs afterAll",
+ "mjs beforeAll",
+ ],
);
});
});
- describe('support ESM via .js extension w/o type=module', function () {
+ describe("support ESM via .js extension w/o type=module", function () {
// --(no-)experimental-detect-module was experimental when these tests were written
// https://nodejs.org/api/cli.html#--no-experimental-detect-module
// https://nodejs.org/api/packages.html#syntax-detection
@@ -145,10 +145,10 @@ describe('root hooks', function () {
function isNewerVersion(vString) {
// Latest versions considered "older": 18.20.8, 20.18.3, 22.11.0
// (May update after writing)
- return semver.satisfies(vString, '^20.19.0 || ^22.12.0 || ^24.0.0');
+ return semver.satisfies(vString, "^20.19.0 || ^22.12.0 || ^24.0.0");
}
- describe('on older versions, should fail due to ambiguous file type', function () {
+ describe("on older versions, should fail due to ambiguous file type", function () {
// --(no-)experimental-detect-module was experimental when these tests were written
// (introduced in Node 20.10.0, 21.1.0)
// newer versions of Node no longer fail :)
@@ -157,206 +157,206 @@ describe('root hooks', function () {
}
const filename =
- '../fixtures/plugins/root-hooks/root-hook-defs-esm-broken.fixture.js';
+ "../fixtures/plugins/root-hooks/root-hook-defs-esm-broken.fixture.js";
const noDetectModuleRegex = /SyntaxError: Unexpected token/;
const detectModuleRegex = /Cannot require\(\) ES Module/;
- it('with --no-experimental-detect-module', function () {
+ it("with --no-experimental-detect-module", function () {
return expect(
invokeMochaAsync(
[
- '--require=' + require.resolve(filename), // as object
- '--no-experimental-detect-module'
+ "--require=" + require.resolve(filename), // as object
+ "--no-experimental-detect-module",
],
- 'pipe'
+ "pipe",
)[1],
- 'when fulfilled',
- 'to contain output',
- noDetectModuleRegex
+ "when fulfilled",
+ "to contain output",
+ noDetectModuleRegex,
);
});
- it('with --experimental-detect-module', function () {
+ it("with --experimental-detect-module", function () {
// --experimental-detect-module was introduced in Node 20.10.0, 21.1.0
// adding the flag to older versions of Node does nothing
const expectedRegex =
- process.version >= 'v21.1.0'
+ process.version >= "v21.1.0"
? detectModuleRegex
: noDetectModuleRegex;
return expect(
invokeMochaAsync(
[
- '--require=' + require.resolve(filename), // as object
- '--experimental-detect-module'
+ "--require=" + require.resolve(filename), // as object
+ "--experimental-detect-module",
],
- 'pipe'
+ "pipe",
)[1],
- 'when fulfilled',
- 'to contain output',
- expectedRegex
+ "when fulfilled",
+ "to contain output",
+ expectedRegex,
);
});
});
- describe('on newer versions, should work', function () {
+ describe("on newer versions, should work", function () {
if (!isNewerVersion(process.versions.node)) {
return true; // skip suite on older Node versions
}
const filename =
- '../fixtures/plugins/root-hooks/root-hook-defs-esm-broken.fixture.js';
+ "../fixtures/plugins/root-hooks/root-hook-defs-esm-broken.fixture.js";
const runSuccessRegex = /0 passing/;
- it('with --no-experimental-detect-module', function () {
+ it("with --no-experimental-detect-module", function () {
return expect(
invokeMochaAsync(
[
- '--require=' + require.resolve(filename), // as object
- '--no-experimental-detect-module'
+ "--require=" + require.resolve(filename), // as object
+ "--no-experimental-detect-module",
],
- 'pipe'
+ "pipe",
)[1],
- 'when fulfilled',
- 'to contain output',
- runSuccessRegex
+ "when fulfilled",
+ "to contain output",
+ runSuccessRegex,
);
});
- it('with --experimental-detect-module', function () {
+ it("with --experimental-detect-module", function () {
return expect(
invokeMochaAsync(
[
- '--require=' + require.resolve(filename), // as object
+ "--require=" + require.resolve(filename), // as object
// enabled by default in these newer versions, but clearer to use it explicitly
- '--experimental-detect-module'
+ "--experimental-detect-module",
],
- 'pipe'
+ "pipe",
)[1],
- 'when fulfilled',
- 'to contain output',
- runSuccessRegex
+ "when fulfilled",
+ "to contain output",
+ runSuccessRegex,
);
});
});
});
});
- describe('when mocha in parallel mode', function () {
- it('should run root hooks when provided via mochaHooks object exports', function () {
+ describe("when mocha in parallel mode", function () {
+ it("should run root hooks when provided via mochaHooks object exports", function () {
return expect(
runMochaForHookOutput([
- '--require=' +
+ "--require=" +
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js",
),
- '--require=' +
+ "--require=" +
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-defs-b.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-defs-b.fixture.js",
),
- '--parallel',
+ "--parallel",
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
- )
+ "../fixtures/plugins/root-hooks/root-hook-test.fixture.js",
+ ),
]),
- 'to be fulfilled with',
+ "to be fulfilled with",
[
- 'afterAll',
- 'afterAll array 1',
- 'afterAll array 2',
- 'afterEach',
- 'afterEach array 1',
- 'afterEach array 2',
- 'beforeAll',
- 'beforeAll array 1',
- 'beforeAll array 2',
- 'beforeEach',
- 'beforeEach array 1',
- 'beforeEach array 2'
- ]
+ "afterAll",
+ "afterAll array 1",
+ "afterAll array 2",
+ "afterEach",
+ "afterEach array 1",
+ "afterEach array 2",
+ "beforeAll",
+ "beforeAll array 1",
+ "beforeAll array 2",
+ "beforeEach",
+ "beforeEach array 1",
+ "beforeEach array 2",
+ ],
);
});
- it('should run root hooks when provided via mochaHooks function export', function () {
+ it("should run root hooks when provided via mochaHooks function export", function () {
return expect(
runMochaForHookOutput([
- '--require=' +
+ "--require=" +
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-defs-c.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-defs-c.fixture.js",
),
- '--require=' +
+ "--require=" +
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-defs-d.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-defs-d.fixture.js",
),
- '--parallel',
+ "--parallel",
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
- )
+ "../fixtures/plugins/root-hooks/root-hook-test.fixture.js",
+ ),
]),
- 'to be fulfilled with',
+ "to be fulfilled with",
[
- 'afterAll',
- 'afterAll array 1',
- 'afterAll array 2',
- 'afterEach',
- 'afterEach array 1',
- 'afterEach array 2',
- 'beforeAll',
- 'beforeAll array 1',
- 'beforeAll array 2',
- 'beforeEach',
- 'beforeEach array 1',
- 'beforeEach array 2'
- ]
+ "afterAll",
+ "afterAll array 1",
+ "afterAll array 2",
+ "afterEach",
+ "afterEach array 1",
+ "afterEach array 2",
+ "beforeAll",
+ "beforeAll array 1",
+ "beforeAll array 2",
+ "beforeEach",
+ "beforeEach array 1",
+ "beforeEach array 2",
+ ],
);
});
- describe('when running multiple jobs', function () {
- it('should run root hooks when provided via mochaHooks object exports for each job', function () {
+ describe("when running multiple jobs", function () {
+ it("should run root hooks when provided via mochaHooks object exports for each job", function () {
return expect(
runMochaForHookOutput([
- '--require=' +
+ "--require=" +
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-defs-a.fixture.js",
),
- '--require=' +
+ "--require=" +
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-defs-b.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-defs-b.fixture.js",
),
- '--parallel',
+ "--parallel",
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-test.fixture.js'
+ "../fixtures/plugins/root-hooks/root-hook-test.fixture.js",
),
require.resolve(
- '../fixtures/plugins/root-hooks/root-hook-test-2.fixture.js'
- )
+ "../fixtures/plugins/root-hooks/root-hook-test-2.fixture.js",
+ ),
]),
- 'to be fulfilled with',
+ "to be fulfilled with",
[
- 'afterAll',
- 'afterAll',
- 'afterAll array 1',
- 'afterAll array 1',
- 'afterAll array 2',
- 'afterAll array 2',
- 'afterEach',
- 'afterEach',
- 'afterEach array 1',
- 'afterEach array 1',
- 'afterEach array 2',
- 'afterEach array 2',
- 'beforeAll',
- 'beforeAll',
- 'beforeAll array 1',
- 'beforeAll array 1',
- 'beforeAll array 2',
- 'beforeAll array 2',
- 'beforeEach',
- 'beforeEach',
- 'beforeEach array 1',
- 'beforeEach array 1',
- 'beforeEach array 2',
- 'beforeEach array 2'
- ]
+ "afterAll",
+ "afterAll",
+ "afterAll array 1",
+ "afterAll array 1",
+ "afterAll array 2",
+ "afterAll array 2",
+ "afterEach",
+ "afterEach",
+ "afterEach array 1",
+ "afterEach array 1",
+ "afterEach array 2",
+ "afterEach array 2",
+ "beforeAll",
+ "beforeAll",
+ "beforeAll array 1",
+ "beforeAll array 1",
+ "beforeAll array 2",
+ "beforeAll array 2",
+ "beforeEach",
+ "beforeEach",
+ "beforeEach array 1",
+ "beforeEach array 1",
+ "beforeEach array 2",
+ "beforeEach array 2",
+ ],
);
});
});
diff --git a/test/integration/regression.spec.js b/test/integration/regression.spec.js
index f6ae4c1c..dd498ca9 100644
--- a/test/integration/regression.spec.js
+++ b/test/integration/regression.spec.js
@@ -1,21 +1,21 @@
-'use strict';
+"use strict";
-var run = require('./helpers').runMocha;
-var runJSON = require('./helpers').runMochaJSON;
+var run = require("./helpers").runMocha;
+var runJSON = require("./helpers").runMochaJSON;
-describe('regressions', function () {
- it('issue-1991: Declarations do not get cleaned up unless you set them to `null` - Memory Leak', function (done) {
+describe("regressions", function () {
+ it("issue-1991: Declarations do not get cleaned up unless you set them to `null` - Memory Leak", function (done) {
// on a modern MBP takes ±5 seconds on node 4.0, but on older laptops with node 0.12 ±40 seconds.
// Could easily take longer on even weaker machines (Travis-CI containers for example).
this.timeout(120000);
this.slow(12000);
- run('regression/issue-1991.fixture.js', [], function (err, res) {
+ run("regression/issue-1991.fixture.js", [], function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'not to contain output', 'process out of memory').and(
- 'to have passed'
+ expect(res, "not to contain output", "process out of memory").and(
+ "to have passed",
);
done();
});
@@ -23,55 +23,55 @@ describe('regressions', function () {
describe("issue-2286: after doesn't execute if test was skipped in beforeEach", function () {
var afterWasRun = false;
- describe('suite with skipped test for meta test', function () {
+ describe("suite with skipped test for meta test", function () {
beforeEach(function () {
this.skip();
});
after(function () {
afterWasRun = true;
});
- it('should be pending', function () {});
+ it("should be pending", function () {});
});
- after('meta test', function () {
- expect(afterWasRun, 'to be', true);
+ after("meta test", function () {
+ expect(afterWasRun, "to be", true);
});
});
- it('issue-2315: cannot read property currentRetry of undefined', function (done) {
- runJSON('regression/issue-2315.fixture.js', [], function (err, res) {
+ it("issue-2315: cannot read property currentRetry of undefined", function (done) {
+ runJSON("regression/issue-2315.fixture.js", [], function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have failed')
- .and('not to have pending tests')
- .and('to have failed test count', 1);
+ expect(res, "to have failed")
+ .and("not to have pending tests")
+ .and("to have failed test count", 1);
done();
});
});
- it('issue-2406: should run nested describe.only suites', function (done) {
- runJSON('regression/issue-2406.fixture.js', [], function (err, res) {
+ it("issue-2406: should run nested describe.only suites", function (done) {
+ runJSON("regression/issue-2406.fixture.js", [], function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have passed')
- .and('not to have pending tests')
- .and('to have passed test count', 2);
+ expect(res, "to have passed")
+ .and("not to have pending tests")
+ .and("to have passed test count", 2);
done();
});
});
- it('issue-2417: should not recurse infinitely with .only suites nested within each other', function (done) {
- runJSON('regression/issue-2417.fixture.js', [], function (err, res) {
+ it("issue-2417: should not recurse infinitely with .only suites nested within each other", function (done) {
+ runJSON("regression/issue-2417.fixture.js", [], function (err, res) {
if (err) {
done(err);
return;
}
- expect(res, 'to have passed')
- .and('not to have pending tests')
- .and('to have passed test count', 1);
+ expect(res, "to have passed")
+ .and("not to have pending tests")
+ .and("to have passed test count", 1);
done();
});
});
diff --git a/test/integration/reporters.spec.js b/test/integration/reporters.spec.js
index 1529f28e..c1164d6f 100644
--- a/test/integration/reporters.spec.js
+++ b/test/integration/reporters.spec.js
@@ -1,62 +1,62 @@
-'use strict';
+"use strict";
-var os = require('node:os');
-var fs = require('node:fs');
-var crypto = require('node:crypto');
-var path = require('node:path');
-var run = require('./helpers').runMocha;
+var os = require("node:os");
+var fs = require("node:fs");
+var crypto = require("node:crypto");
+var path = require("node:path");
+var run = require("./helpers").runMocha;
-describe('reporters', function () {
- describe('markdown', function () {
+describe("reporters", function () {
+ describe("markdown", function () {
var res;
before(function (done) {
run(
- 'passing.fixture.js',
- ['--reporter', 'markdown'],
+ "passing.fixture.js",
+ ["--reporter", "markdown"],
function (err, result) {
res = result;
done(err);
- }
+ },
);
});
- it('does not exceed maximum callstack (issue: 1875)', function () {
- expect(res.output, 'not to contain', 'RangeError');
+ it("does not exceed maximum callstack (issue: 1875)", function () {
+ expect(res.output, "not to contain", "RangeError");
});
- it('contains spec src', function () {
- var src = ['```js', 'assert(true);', '```'].join('\n');
+ it("contains spec src", function () {
+ var src = ["```js", "assert(true);", "```"].join("\n");
- expect(res.output, 'to contain', src);
+ expect(res.output, "to contain", src);
});
});
- describe('xunit', function () {
- it('prints test cases with --reporter-options output (issue: 1864)', function (done) {
- var randomStr = crypto.randomBytes(8).toString('hex');
- var tmpDir = os.tmpdir().replace(new RegExp(path.sep + '$'), '');
- var tmpFile = tmpDir + path.sep + 'test-issue-1864-' + randomStr + '.xml';
+ describe("xunit", function () {
+ it("prints test cases with --reporter-options output (issue: 1864)", function (done) {
+ var randomStr = crypto.randomBytes(8).toString("hex");
+ var tmpDir = os.tmpdir().replace(new RegExp(path.sep + "$"), "");
+ var tmpFile = tmpDir + path.sep + "test-issue-1864-" + randomStr + ".xml";
var args = [
- '--reporter=xunit',
- '--reporter-options',
- 'output=' + tmpFile
+ "--reporter=xunit",
+ "--reporter-options",
+ "output=" + tmpFile,
];
var expectedOutput = [
'<testcase classname="suite" name="test1" file="',
'<testcase classname="suite" name="test2" file="',
- '</testsuite>'
+ "</testsuite>",
];
- run('passing.fixture.js', args, function (err) {
+ run("passing.fixture.js", args, function (err) {
if (err) return done(err);
- var xml = fs.readFileSync(tmpFile, 'utf8');
+ var xml = fs.readFileSync(tmpFile, "utf8");
fs.unlinkSync(tmpFile);
expectedOutput.forEach(function (line) {
- expect(xml, 'to contain', line);
+ expect(xml, "to contain", line);
});
done(err);
@@ -64,44 +64,44 @@ describe('reporters', function () {
});
});
- describe('loader', function () {
- it('loads a reporter from a path relative to the current working directory', function (done) {
+ describe("loader", function () {
+ it("loads a reporter from a path relative to the current working directory", function (done) {
var reporterAtARelativePath =
- 'test/integration/fixtures/simple-reporter.js';
+ "test/integration/fixtures/simple-reporter.js";
- var args = ['--reporter=' + reporterAtARelativePath];
+ var args = ["--reporter=" + reporterAtARelativePath];
- run('passing.fixture.js', args, function (err, result) {
+ run("passing.fixture.js", args, function (err, result) {
if (err) {
done(err);
return;
}
- expect(result, 'to have passed');
+ expect(result, "to have passed");
done();
});
});
- it('loads a reporter from an absolute path', function (done) {
+ it("loads a reporter from an absolute path", function (done) {
// Generates an absolute path string
var reporterAtAnAbsolutePath = path.join(
process.cwd(),
- 'test/integration/fixtures/simple-reporter.js'
+ "test/integration/fixtures/simple-reporter.js",
);
- var args = ['--reporter=' + reporterAtAnAbsolutePath];
+ var args = ["--reporter=" + reporterAtAnAbsolutePath];
- run('passing.fixture.js', args, function (err, result) {
+ run("passing.fixture.js", args, function (err, result) {
if (err) {
done(err);
return;
}
- expect(result, 'to have passed');
+ expect(result, "to have passed");
done();
});
});
});
- describe('tap', function () {
+ describe("tap", function () {
var not = function (predicate) {
return function () {
return !predicate.apply(this, arguments);
@@ -132,10 +132,10 @@ describe('reporters', function () {
);
};
- describe('produces valid TAP v13 output', function () {
+ describe("produces valid TAP v13 output", function () {
var runFixtureAndValidateOutput = function (fixture, expected) {
- it('for ' + fixture, function (done) {
- var args = ['--reporter=tap', '--reporter-option', 'tapVersion=13'];
+ it("for " + fixture, function (done) {
+ var args = ["--reporter=tap", "--reporter-option", "tapVersion=13"];
run(fixture, args, function (err, res) {
if (err) {
@@ -144,30 +144,30 @@ describe('reporters', function () {
}
var expectedVersion = 13;
- var expectedPlan = '1..' + expected.numTests;
+ var expectedPlan = "1.." + expected.numTests;
- var outputLines = res.output.split('\n');
+ var outputLines = res.output.split("\n");
// first line must be version line
expect(
outputLines[0],
- 'to equal',
- 'TAP version ' + expectedVersion
+ "to equal",
+ "TAP version " + expectedVersion,
);
// plan must appear once
- expect(outputLines, 'to contain', expectedPlan);
+ expect(outputLines, "to contain", expectedPlan);
expect(
outputLines.filter(function (l) {
return l === expectedPlan;
}),
- 'to have length',
- 1
+ "to have length",
+ 1,
);
// plan cannot appear in middle of the output
var firstTestLine = outputLines.findIndex(testLinePredicate);
// there must be at least one test line
- expect(firstTestLine, 'to be greater than', -1);
+ expect(firstTestLine, "to be greater than", -1);
var lastTestLine =
outputLines.length -
1 -
@@ -177,8 +177,8 @@ describe('reporters', function () {
});
expect(
planLine < firstTestLine || planLine > lastTestLine,
- 'to equal',
- true
+ "to equal",
+ true,
);
done();
@@ -186,24 +186,24 @@ describe('reporters', function () {
});
};
- runFixtureAndValidateOutput('passing.fixture.js', {
- numTests: 2
+ runFixtureAndValidateOutput("passing.fixture.js", {
+ numTests: 2,
});
- runFixtureAndValidateOutput('reporters.fixture.js', {
- numTests: 12
+ runFixtureAndValidateOutput("reporters.fixture.js", {
+ numTests: 12,
});
});
- it('should fail if given invalid `tapVersion`', function (done) {
- var invalidTapVersion = 'nosuch';
+ it("should fail if given invalid `tapVersion`", function (done) {
+ var invalidTapVersion = "nosuch";
var args = [
- '--reporter=tap',
- '--reporter-option',
- 'tapVersion=' + invalidTapVersion
+ "--reporter=tap",
+ "--reporter-option",
+ "tapVersion=" + invalidTapVersion,
];
run(
- 'reporters.fixture.js',
+ "reporters.fixture.js",
args,
function (err, res) {
if (err) {
@@ -212,26 +212,26 @@ describe('reporters', function () {
}
var pattern = `Error: invalid or unsupported TAP version: "${invalidTapVersion}"`;
- expect(res, 'to satisfy', {
+ expect(res, "to satisfy", {
code: 1,
- output: new RegExp(pattern, 'm')
+ output: new RegExp(pattern, "m"),
});
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
- it('places exceptions correctly in YAML blocks', function (done) {
- var args = ['--reporter=tap', '--reporter-option', 'tapVersion=13'];
+ it("places exceptions correctly in YAML blocks", function (done) {
+ var args = ["--reporter=tap", "--reporter-option", "tapVersion=13"];
- run('reporters.fixture.js', args, function (err, res) {
+ run("reporters.fixture.js", args, function (err, res) {
if (err) {
done(err);
return;
}
- var outputLines = res.output.split('\n');
+ var outputLines = res.output.split("\n");
for (var i = 0; i + 1 < outputLines.length; i++) {
if (
@@ -249,8 +249,8 @@ describe('reporters', function () {
: outputLines.slice(blockLinesStart);
i += blockLines.length;
- expect(blockLines[0], 'to match', /^\s+---/);
- expect(blockLines[blockLines.length - 1], 'to match', /^\s+\.\.\./);
+ expect(blockLines[0], "to match", /^\s+---/);
+ expect(blockLines[blockLines.length - 1], "to match", /^\s+\.\.\./);
}
}
diff --git a/test/integration/retries.spec.js b/test/integration/retries.spec.js
index d9388829..e6bc5ef4 100644
--- a/test/integration/retries.spec.js
+++ b/test/integration/retries.spec.js
@@ -1,16 +1,16 @@
-'use strict';
+"use strict";
-var assert = require('node:assert');
-var helpers = require('./helpers');
+var assert = require("node:assert");
+var helpers = require("./helpers");
var runJSON = helpers.runMochaJSON;
var args = [];
-var bang = require('../../lib/reporters/base').symbols.bang;
+var bang = require("../../lib/reporters/base").symbols.bang;
-describe('retries', function () {
- it('are ran in correct order', function (done) {
+describe("retries", function () {
+ it("are ran in correct order", function (done) {
helpers.runMocha(
- 'retries/hooks.fixture.js',
- ['--reporter', 'dot'],
+ "retries/hooks.fixture.js",
+ ["--reporter", "dot"],
function (err, res) {
var lines, expected;
@@ -30,23 +30,23 @@ describe('retries', function () {
.slice(0, -1);
expected = [
- 'before',
- 'before each 0',
- 'TEST 0',
- 'after each 1',
- 'before each 1',
- 'TEST 1',
- 'after each 2',
- 'before each 2',
- 'TEST 2',
- 'after each 3',
- 'before each 3',
- 'TEST 3',
- 'after each 4',
- 'before each 4',
- 'TEST 4',
- bang + 'after each 5',
- 'after'
+ "before",
+ "before each 0",
+ "TEST 0",
+ "after each 1",
+ "before each 1",
+ "TEST 1",
+ "after each 2",
+ "before each 2",
+ "TEST 2",
+ "after each 3",
+ "before each 3",
+ "TEST 3",
+ "after each 4",
+ "before each 4",
+ "TEST 4",
+ bang + "after each 5",
+ "after",
];
expected.forEach(function (line, i) {
@@ -55,27 +55,27 @@ describe('retries', function () {
assert.strictEqual(res.code, 1);
done();
- }
+ },
);
});
- it('should exit early if test passes', function (done) {
- runJSON('retries/early-pass.fixture.js', args, function (err, res) {
+ it("should exit early if test passes", function (done) {
+ runJSON("retries/early-pass.fixture.js", args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed')
- .and('to have passed test count', 2)
- .and('to have failed test count', 0)
- .and('to have retried test', 'should pass after 1 retry', 1);
+ expect(res, "to have passed")
+ .and("to have passed test count", 2)
+ .and("to have failed test count", 0)
+ .and("to have retried test", "should pass after 1 retry", 1);
done();
});
});
- it('should let test override', function (done) {
- runJSON('retries/nested.fixture.js', args, function (err, res) {
+ it("should let test override", function (done) {
+ runJSON("retries/nested.fixture.js", args, function (err, res) {
if (err) {
done(err);
return;
@@ -89,10 +89,10 @@ describe('retries', function () {
});
});
- it('should not hang w/ async test', function (done) {
+ it("should not hang w/ async test", function (done) {
helpers.runMocha(
- 'retries/async.fixture.js',
- ['--reporter', 'dot'],
+ "retries/async.fixture.js",
+ ["--reporter", "dot"],
function (err, res) {
var lines, expected;
@@ -112,17 +112,17 @@ describe('retries', function () {
.slice(0, -1);
expected = [
- 'before',
- 'before each 0',
- 'TEST 0',
- 'after each 1',
- 'before each 1',
- 'TEST 1',
- 'after each 2',
- 'before each 2',
- 'TEST 2',
- 'after each 3',
- 'after'
+ "before",
+ "before each 0",
+ "TEST 0",
+ "after each 1",
+ "before each 1",
+ "TEST 1",
+ "after each 2",
+ "before each 2",
+ "TEST 2",
+ "after each 3",
+ "after",
];
expected.forEach(function (line, i) {
@@ -131,7 +131,7 @@ describe('retries', function () {
assert.strictEqual(res.code, 0);
done();
- }
+ },
);
});
});
diff --git a/test/integration/suite.spec.js b/test/integration/suite.spec.js
index 1b4c1472..758954b9 100644
--- a/test/integration/suite.spec.js
+++ b/test/integration/suite.spec.js
@@ -1,12 +1,12 @@
-'use strict';
+"use strict";
-var run = require('./helpers').runMocha;
+var run = require("./helpers").runMocha;
var args = [];
-describe('suite w/no callback', function () {
- it('should throw a helpful error message when a callback for suite is not supplied', function (done) {
+describe("suite w/no callback", function () {
+ it("should throw a helpful error message when a callback for suite is not supplied", function (done) {
run(
- 'suite/suite-no-callback.fixture.js',
+ "suite/suite-no-callback.fixture.js",
args,
function (err, res) {
if (err) {
@@ -14,20 +14,20 @@ describe('suite w/no callback', function () {
}
expect(
res.output,
- 'to match',
- /no callback was supplied. Supply a callback/
+ "to match",
+ /no callback was supplied. Supply a callback/,
);
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
});
-describe('skipped suite w/no callback', function () {
- it('should not throw an error when a callback for skipped suite is not supplied', function (done) {
+describe("skipped suite w/no callback", function () {
+ it("should not throw an error when a callback for skipped suite is not supplied", function (done) {
run(
- 'suite/suite-skipped-no-callback.fixture.js',
+ "suite/suite-skipped-no-callback.fixture.js",
args,
function (err, res) {
if (err) {
@@ -35,40 +35,40 @@ describe('skipped suite w/no callback', function () {
}
var pattern = /TypeError/g;
var result = res.output.match(pattern) || [];
- expect(result, 'to have length', 0);
+ expect(result, "to have length", 0);
done();
- }
+ },
);
});
});
-describe('skipped suite w/ callback', function () {
- it('should not throw an error when a callback for skipped suite is supplied', function (done) {
- run('suite/suite-skipped-callback.fixture.js', args, function (err, res) {
+describe("skipped suite w/ callback", function () {
+ it("should not throw an error when a callback for skipped suite is supplied", function (done) {
+ run("suite/suite-skipped-callback.fixture.js", args, function (err, res) {
if (err) {
return done(err);
}
var pattern = /TypeError/g;
var result = res.output.match(pattern) || [];
- expect(result, 'to have length', 0);
+ expect(result, "to have length", 0);
done();
});
});
});
-describe('suite returning a value', function () {
- it('should not give a deprecation warning for suite callback returning a value', function (done) {
+describe("suite returning a value", function () {
+ it("should not give a deprecation warning for suite callback returning a value", function (done) {
run(
- 'suite/suite-returning-value.fixture.js',
+ "suite/suite-returning-value.fixture.js",
args,
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'not to contain output', /Suites ignore return values/);
+ expect(res, "not to contain output", /Suites ignore return values/);
done();
},
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
});
});
diff --git a/test/integration/timeout.spec.js b/test/integration/timeout.spec.js
index 6c33fa42..af39800e 100644
--- a/test/integration/timeout.spec.js
+++ b/test/integration/timeout.spec.js
@@ -1,12 +1,12 @@
-'use strict';
+"use strict";
-var assert = require('node:assert');
-var run = require('./helpers').runMochaJSON;
+var assert = require("node:assert");
+var run = require("./helpers").runMochaJSON;
var args = [];
-describe('this.timeout()', function () {
- it('is respected by sync and async suites', function (done) {
- run('timeout.fixture.js', args, function (err, res) {
+describe("this.timeout()", function () {
+ it("is respected by sync and async suites", function (done) {
+ run("timeout.fixture.js", args, function (err, res) {
if (err) {
done(err);
return;
@@ -19,13 +19,13 @@ describe('this.timeout()', function () {
});
});
- it('should allow overriding if disabled per-test', function (done) {
- run('timeout-override.fixture.js', args, function (err, res) {
+ it("should allow overriding if disabled per-test", function (done) {
+ run("timeout-override.fixture.js", args, function (err, res) {
if (err) {
done(err);
return;
}
- expect(res.stats.failures, 'to be', 1);
+ expect(res.stats.failures, "to be", 1);
done();
});
});
diff --git a/test/integration/uncaught.spec.js b/test/integration/uncaught.spec.js
index 96b90c2f..0a62b743 100644
--- a/test/integration/uncaught.spec.js
+++ b/test/integration/uncaught.spec.js
@@ -1,216 +1,216 @@
-'use strict';
+"use strict";
const {
runMocha,
runMochaJSON: run,
invokeMochaAsync,
invokeNode,
- resolveFixturePath
-} = require('./helpers');
+ resolveFixturePath,
+} = require("./helpers");
var args = [];
-describe('uncaught exceptions', function () {
- it('handles uncaught exceptions from hooks', function (done) {
- run('uncaught/hook', args, function (err, res) {
+describe("uncaught exceptions", function () {
+ it("handles uncaught exceptions from hooks", function (done) {
+ run("uncaught/hook", args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'oh noes')
- .and('to have passed test count', 0)
- .and('to have pending test count', 0)
- .and('to have failed test count', 1)
- .and('to have failed test', '"before each" hook for "test"');
+ expect(res, "to have failed with error", "oh noes")
+ .and("to have passed test count", 0)
+ .and("to have pending test count", 0)
+ .and("to have failed test count", 1)
+ .and("to have failed test", '"before each" hook for "test"');
done();
});
});
- it('handles uncaught exceptions from async specs', function (done) {
- run('uncaught/double', args, function (err, res) {
+ it("handles uncaught exceptions from async specs", function (done) {
+ run("uncaught/double", args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'global error', 'test error')
- .and('to have passed test count', 0)
- .and('to have pending test count', 0)
- .and('to have failed test count', 2)
+ expect(res, "to have failed with error", "global error", "test error")
+ .and("to have passed test count", 0)
+ .and("to have pending test count", 0)
+ .and("to have failed test count", 2)
.and(
- 'to have failed test',
- 'fails exactly once when a global error is thrown first',
- 'fails exactly once when a global error is thrown second'
+ "to have failed test",
+ "fails exactly once when a global error is thrown first",
+ "fails exactly once when a global error is thrown second",
);
done();
});
});
- it('handles uncaught exceptions from which Mocha cannot recover', function (done) {
- run('uncaught/fatal', args, function (err, res) {
+ it("handles uncaught exceptions from which Mocha cannot recover", function (done) {
+ run("uncaught/fatal", args, function (err, res) {
if (err) {
return done(err);
}
- var testName = 'should bail if a successful test asynchronously fails';
- expect(res, 'to have failed with error', 'global error')
- .and('to have passed test count', 1)
- .and('to have failed test count', 1)
- .and('to have passed test', testName)
- .and('to have failed test', testName);
+ var testName = "should bail if a successful test asynchronously fails";
+ expect(res, "to have failed with error", "global error")
+ .and("to have passed test count", 1)
+ .and("to have failed test count", 1)
+ .and("to have passed test", testName)
+ .and("to have failed test", testName);
done();
});
});
- it('handles uncaught exceptions within pending tests', function (done) {
- run('uncaught/pending', args, function (err, res) {
+ it("handles uncaught exceptions within pending tests", function (done) {
+ run("uncaught/pending", args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'I am uncaught!')
- .and('to have passed test count', 3)
- .and('to have pending test count', 1)
- .and('to have failed test count', 1)
+ expect(res, "to have failed with error", "I am uncaught!")
+ .and("to have passed test count", 3)
+ .and("to have pending test count", 1)
+ .and("to have failed test count", 1)
.and(
- 'to have passed test',
- 'test1',
- 'test3 - should run',
- 'test4 - should run'
+ "to have passed test",
+ "test1",
+ "test3 - should run",
+ "test4 - should run",
)
- .and('to have pending test order', 'test2')
- .and('to have failed test', 'test2');
+ .and("to have pending test order", "test2")
+ .and("to have failed test", "test2");
done();
});
});
- it('handles uncaught exceptions within open tests', function (done) {
- run('uncaught/recover', args, function (err, res) {
+ it("handles uncaught exceptions within open tests", function (done) {
+ run("uncaught/recover", args, function (err, res) {
if (err) {
return done(err);
}
expect(
res,
- 'to have failed with error',
- 'Whoops!',
- 'Whoops!', // JSON reporter does not show the second error message
- 'should get upto here and throw'
+ "to have failed with error",
+ "Whoops!",
+ "Whoops!", // JSON reporter does not show the second error message
+ "should get upto here and throw",
)
- .and('to have passed test count', 2)
- .and('to have failed test count', 3)
- .and('to have passed test', 'should wait 15ms', 'test 3')
+ .and("to have passed test count", 2)
+ .and("to have failed test count", 3)
+ .and("to have passed test", "should wait 15ms", "test 3")
.and(
- 'to have failed test',
- 'throw delayed error',
- 'throw delayed error',
- '"after all" hook for "test 3"'
+ "to have failed test",
+ "throw delayed error",
+ "throw delayed error",
+ '"after all" hook for "test 3"',
);
done();
});
});
- it('removes uncaught exceptions handlers correctly', function (done) {
- invokeNode([resolveFixturePath('uncaught/listeners')], function (err, res) {
+ it("removes uncaught exceptions handlers correctly", function (done) {
+ invokeNode([resolveFixturePath("uncaught/listeners")], function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have passed');
+ expect(res, "to have passed");
done();
});
});
it("handles uncaught exceptions after runner's end", function (done) {
runMocha(
- 'uncaught/after-runner',
+ "uncaught/after-runner",
args,
function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed').and('to satisfy', {
+ expect(res, "to have failed").and("to satisfy", {
failing: 0,
passing: 1,
pending: 0,
- output: expect.it('to contain', 'Error: Unexpected crash')
+ output: expect.it("to contain", "Error: Unexpected crash"),
});
done();
},
- 'pipe'
+ "pipe",
);
});
- it('issue-1327: should run the first test and then bail', function (done) {
- run('uncaught/issue-1327', args, function (err, res) {
+ it("issue-1327: should run the first test and then bail", function (done) {
+ run("uncaught/issue-1327", args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with error', 'Too bad')
- .and('to have passed test count', 1)
- .and('to have failed test count', 1)
- .and('to have passed test', 'test 1')
- .and('to have failed test', 'test 1');
+ expect(res, "to have failed with error", "Too bad")
+ .and("to have passed test count", 1)
+ .and("to have failed test count", 1)
+ .and("to have passed test", "test 1")
+ .and("to have failed test", "test 1");
done();
});
});
- it('issue-1417: uncaught exceptions from async specs', function (done) {
- run('uncaught/issue-1417', args, function (err, res) {
+ it("issue-1417: uncaught exceptions from async specs", function (done) {
+ run("uncaught/issue-1417", args, function (err, res) {
if (err) {
return done(err);
}
- expect(res, 'to have failed with errors', 'sync error a', 'sync error b')
- .and('to have exit code', 2)
- .and('not to have passed tests')
- .and('not to have pending tests')
- .and('to have failed test order', [
- 'fails exactly once when a global error is thrown synchronously and done errors',
- 'fails exactly once when a global error is thrown synchronously and done completes'
+ expect(res, "to have failed with errors", "sync error a", "sync error b")
+ .and("to have exit code", 2)
+ .and("not to have passed tests")
+ .and("not to have pending tests")
+ .and("to have failed test order", [
+ "fails exactly once when a global error is thrown synchronously and done errors",
+ "fails exactly once when a global error is thrown synchronously and done completes",
]);
done();
});
});
- describe('issue-4481: behavior of non-Mocha-originating unhandled rejections', function () {
+ describe("issue-4481: behavior of non-Mocha-originating unhandled rejections", function () {
describe('when Node is in "warn" mode', function () {
- it('should warn', async function () {
+ it("should warn", async function () {
const [, promise] = invokeMochaAsync(
[
- resolveFixturePath('uncaught/unhandled'),
- '--unhandled-rejections=warn'
+ resolveFixturePath("uncaught/unhandled"),
+ "--unhandled-rejections=warn",
],
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
return expect(
promise,
- 'when fulfilled',
- 'to have passed with output',
- /UnhandledPromiseRejectionWarning: Error: yikes/
+ "when fulfilled",
+ "to have passed with output",
+ /UnhandledPromiseRejectionWarning: Error: yikes/,
);
});
});
describe('when Node is in "strict" mode', function () {
- it('should fail with an uncaught exception', async function () {
+ it("should fail with an uncaught exception", async function () {
const [, promise] = invokeMochaAsync(
[
- resolveFixturePath('uncaught/unhandled'),
- '--unhandled-rejections=strict'
+ resolveFixturePath("uncaught/unhandled"),
+ "--unhandled-rejections=strict",
],
- {stdio: 'pipe'}
+ { stdio: "pipe" },
);
return expect(
promise,
- 'when fulfilled',
- 'to have failed with output',
- /Error: yikes/
+ "when fulfilled",
+ "to have failed with output",
+ /Error: yikes/,
);
});
});
diff --git a/test/interfaces/bdd.spec.js b/test/interfaces/bdd.spec.js
index b96b386d..99554554 100644
--- a/test/interfaces/bdd.spec.js
+++ b/test/interfaces/bdd.spec.js
@@ -1,68 +1,68 @@
-'use strict';
+"use strict";
-describe('integer primitives', function () {
- describe('arithmetic', function () {
- it('should add', function () {
- expect(1 + 1, 'to be', 2);
- expect(2 + 2, 'to be', 4);
+describe("integer primitives", function () {
+ describe("arithmetic", function () {
+ it("should add", function () {
+ expect(1 + 1, "to be", 2);
+ expect(2 + 2, "to be", 4);
});
- it('should subtract', function () {
- expect(1 - 1, 'to be', 0);
- expect(2 - 1, 'to be', 1);
+ it("should subtract", function () {
+ expect(1 - 1, "to be", 0);
+ expect(2 - 1, "to be", 1);
});
});
});
-describe('integer primitives', function () {
- describe('arithmetic is not', function () {
- it('should add', function () {
- expect(1 + 1, 'not to equal', 3);
- expect(2 + 2, 'not to equal', 5);
+describe("integer primitives", function () {
+ describe("arithmetic is not", function () {
+ it("should add", function () {
+ expect(1 + 1, "not to equal", 3);
+ expect(2 + 2, "not to equal", 5);
});
});
});
-context('test suite', function () {
+context("test suite", function () {
beforeEach(function () {
this.number = 5;
});
- specify('share a property', function () {
- expect(this.number, 'to be', 5);
+ specify("share a property", function () {
+ expect(this.number, "to be", 5);
});
});
-describe('pending suite', function () {
- describe.skip('this is pending suite', function () {
- it('should not run', function () {
- expect(1 + 1, 'to be', 3);
+describe("pending suite", function () {
+ describe.skip("this is pending suite", function () {
+ it("should not run", function () {
+ expect(1 + 1, "to be", 3);
});
});
});
-describe('pending tests', function () {
- it.skip('should not run', function () {
- expect(1 + 1, 'to be', 3);
+describe("pending tests", function () {
+ it.skip("should not run", function () {
+ expect(1 + 1, "to be", 3);
});
});
-describe('setting timeout by appending it to test', function () {
+describe("setting timeout by appending it to test", function () {
var runningTest =
- it('enables users to call timeout on active tests', function () {
- expect(1 + 1, 'to be', 2);
+ it("enables users to call timeout on active tests", function () {
+ expect(1 + 1, "to be", 2);
}).timeout(1003);
var skippedTest =
- xit('enables users to call timeout on pending tests', function () {
- expect(1 + 1, 'to be', 3);
+ xit("enables users to call timeout on pending tests", function () {
+ expect(1 + 1, "to be", 3);
}).timeout(1002);
- it('sets timeout on pending tests', function () {
- expect(skippedTest._timeout, 'to be', 1002);
+ it("sets timeout on pending tests", function () {
+ expect(skippedTest._timeout, "to be", 1002);
});
- it('sets timeout on running tests', function () {
- expect(runningTest._timeout, 'to be', 1003);
+ it("sets timeout on running tests", function () {
+ expect(runningTest._timeout, "to be", 1003);
});
});
diff --git a/test/interfaces/exports.spec.js b/test/interfaces/exports.spec.js
index ab2742a9..572d8c63 100644
--- a/test/interfaces/exports.spec.js
+++ b/test/interfaces/exports.spec.js
@@ -1,46 +1,46 @@
-'use strict';
+"use strict";
var calls = [];
exports.Array = {
before: function () {
- calls.push('before');
+ calls.push("before");
},
after: function () {
- calls.push('after');
- expect(calls, 'to equal', [
- 'before',
- 'before each',
- 'one',
- 'after each',
- 'before each',
- 'two',
- 'after each',
- 'after'
+ calls.push("after");
+ expect(calls, "to equal", [
+ "before",
+ "before each",
+ "one",
+ "after each",
+ "before each",
+ "two",
+ "after each",
+ "after",
]);
},
- '#indexOf()': {
+ "#indexOf()": {
beforeEach: function () {
- calls.push('before each');
+ calls.push("before each");
},
afterEach: function () {
- calls.push('after each');
+ calls.push("after each");
},
- 'should return -1 when the value is not present': function () {
- calls.push('one');
- expect([1, 2, 3].indexOf(5), 'to be', -1);
- expect([1, 2, 3].indexOf(0), 'to be', -1);
+ "should return -1 when the value is not present": function () {
+ calls.push("one");
+ expect([1, 2, 3].indexOf(5), "to be", -1);
+ expect([1, 2, 3].indexOf(0), "to be", -1);
},
- 'should return the correct index when the value is present': function () {
- calls.push('two');
- expect([1, 2, 3].indexOf(1), 'to be', 0);
- expect([1, 2, 3].indexOf(2), 'to be', 1);
- expect([1, 2, 3].indexOf(3), 'to be', 2);
- }
- }
+ "should return the correct index when the value is present": function () {
+ calls.push("two");
+ expect([1, 2, 3].indexOf(1), "to be", 0);
+ expect([1, 2, 3].indexOf(2), "to be", 1);
+ expect([1, 2, 3].indexOf(3), "to be", 2);
+ },
+ },
};
diff --git a/test/interfaces/qunit.spec.js b/test/interfaces/qunit.spec.js
index 8a555cbb..cafbc7e2 100644
--- a/test/interfaces/qunit.spec.js
+++ b/test/interfaces/qunit.spec.js
@@ -1,20 +1,20 @@
-'use strict';
+"use strict";
-suite('integer primitives');
+suite("integer primitives");
-test('should add', function () {
- expect(2 + 2, 'to be', 4);
+test("should add", function () {
+ expect(2 + 2, "to be", 4);
});
-test('should decrement', function () {
+test("should decrement", function () {
var number = 3;
- expect(--number, 'to be', 2);
- expect(--number, 'to be', 1);
- expect(--number, 'to be', 0);
+ expect(--number, "to be", 2);
+ expect(--number, "to be", 1);
+ expect(--number, "to be", 0);
});
-suite('String');
+suite("String");
-test('#length', function () {
- expect('foo', 'to have length', 3);
+test("#length", function () {
+ expect("foo", "to have length", 3);
});
diff --git a/test/interfaces/tdd.spec.js b/test/interfaces/tdd.spec.js
index 357ef5a6..14642c1e 100644
--- a/test/interfaces/tdd.spec.js
+++ b/test/interfaces/tdd.spec.js
@@ -1,41 +1,41 @@
-'use strict';
+"use strict";
-suite('integer primitives', function () {
- suite('arithmetic', function () {
+suite("integer primitives", function () {
+ suite("arithmetic", function () {
var initialValue = 41;
suiteSetup(function (done) {
- expect(initialValue, 'to be', 41);
+ expect(initialValue, "to be", 41);
initialValue += 1;
done();
});
- test('should add', function () {
- expect(initialValue, 'to be', 42);
- expect(1 + 1, 'to be', 2);
- expect(2 + 2, 'to be', 4);
+ test("should add", function () {
+ expect(initialValue, "to be", 42);
+ expect(1 + 1, "to be", 2);
+ expect(2 + 2, "to be", 4);
});
- test('should subtract', function () {
- expect(initialValue, 'to be', 42);
- expect(1 - 1, 'to be', 0);
- expect(2 - 1, 'to be', 1);
+ test("should subtract", function () {
+ expect(initialValue, "to be", 42);
+ expect(1 - 1, "to be", 0);
+ expect(2 - 1, "to be", 1);
});
- test.skip('should skip this test', function () {
+ test.skip("should skip this test", function () {
var zero = 0;
- expect(zero, 'to be', 1);
+ expect(zero, "to be", 1);
});
- suite.skip('should skip this suite', function () {
- test('should skip this test', function () {
+ suite.skip("should skip this suite", function () {
+ test("should skip this test", function () {
var zero = 0;
- expect(zero, 'to be', 1);
+ expect(zero, "to be", 1);
});
});
suiteTeardown(function (done) {
- expect(initialValue, 'to be', 42);
+ expect(initialValue, "to be", 42);
done();
});
});
diff --git a/test/jsapi/index.js b/test/jsapi/index.js
index f3c33434..38193eba 100644
--- a/test/jsapi/index.js
+++ b/test/jsapi/index.js
@@ -1,25 +1,25 @@
-'use strict';
+"use strict";
-var Mocha = require('../../');
+var Mocha = require("../../");
var mocha = new Mocha({
- ui: 'bdd',
- globals: ['okGlobalA', 'okGlobalB', 'okGlobalC', 'callback*'],
- growl: true
+ ui: "bdd",
+ globals: ["okGlobalA", "okGlobalB", "okGlobalC", "callback*"],
+ growl: true,
});
-require('../setup');
+require("../setup");
-mocha.addFile('test/unit/suite.spec.js');
-mocha.addFile('test/unit/runner.spec.js');
-mocha.addFile('test/unit/runnable.spec.js');
-mocha.addFile('test/unit/hook-sync.spec.js');
-mocha.addFile('test/unit/hook-sync-nested.spec.js');
-mocha.addFile('test/unit/hook-async.spec.js');
-mocha.addFile('test/unit/duration.spec.js');
-mocha.addFile('test/unit/globals.spec.js');
-mocha.addFile('test/unit/timeout.spec.js');
+mocha.addFile("test/unit/suite.spec.js");
+mocha.addFile("test/unit/runner.spec.js");
+mocha.addFile("test/unit/runnable.spec.js");
+mocha.addFile("test/unit/hook-sync.spec.js");
+mocha.addFile("test/unit/hook-sync-nested.spec.js");
+mocha.addFile("test/unit/hook-async.spec.js");
+mocha.addFile("test/unit/duration.spec.js");
+mocha.addFile("test/unit/globals.spec.js");
+mocha.addFile("test/unit/timeout.spec.js");
mocha.run(function () {
- console.log('done');
+ console.log("done");
});
diff --git a/test/node-unit/buffered-worker-pool.spec.js b/test/node-unit/buffered-worker-pool.spec.js
index 09764075..ff70e7f1 100644
--- a/test/node-unit/buffered-worker-pool.spec.js
+++ b/test/node-unit/buffered-worker-pool.spec.js
@@ -1,9 +1,9 @@
-'use strict';
+"use strict";
-const rewiremock = require('rewiremock/node');
-const sinon = require('sinon');
+const rewiremock = require("rewiremock/node");
+const sinon = require("sinon");
-describe('class BufferedWorkerPool', function () {
+describe("class BufferedWorkerPool", function () {
let BufferedWorkerPool;
let pool;
let stats;
@@ -12,28 +12,33 @@ describe('class BufferedWorkerPool', function () {
let result;
beforeEach(function () {
- stats = {totalWorkers: 10, busyWorkers: 8, idleWorkers: 2, pendingTasks: 3};
- result = {failures: 0, events: []};
+ stats = {
+ totalWorkers: 10,
+ busyWorkers: 8,
+ idleWorkers: 2,
+ pendingTasks: 3,
+ };
+ result = { failures: 0, events: [] };
pool = {
terminate: sinon.stub().resolves(),
exec: sinon.stub().resolves(result),
- stats: sinon.stub().returns(stats)
+ stats: sinon.stub().returns(stats),
};
serializer = {
- deserialize: sinon.stub()
+ deserialize: sinon.stub(),
};
- serializeJavascript = sinon.spy(require('serialize-javascript'));
+ serializeJavascript = sinon.spy(require("serialize-javascript"));
BufferedWorkerPool = rewiremock.proxy(
- require.resolve('../../lib/nodejs/buffered-worker-pool'),
+ require.resolve("../../lib/nodejs/buffered-worker-pool"),
{
workerpool: {
pool: sinon.stub().returns(pool),
- cpus: 8
+ cpus: 8,
},
- '../../lib/nodejs/serializer': serializer,
- 'serialize-javascript': serializeJavascript
- }
+ "../../lib/nodejs/serializer": serializer,
+ "serialize-javascript": serializeJavascript,
+ },
).BufferedWorkerPool;
// reset cache
@@ -44,138 +49,138 @@ describe('class BufferedWorkerPool', function () {
sinon.restore();
});
- describe('static method', function () {
- describe('create()', function () {
- it('should return a BufferedWorkerPool instance', function () {
+ describe("static method", function () {
+ describe("create()", function () {
+ it("should return a BufferedWorkerPool instance", function () {
expect(
- BufferedWorkerPool.create({foo: 'bar'}),
- 'to be a',
- BufferedWorkerPool
+ BufferedWorkerPool.create({ foo: "bar" }),
+ "to be a",
+ BufferedWorkerPool,
);
});
- describe('when passed no arguments', function () {
- it('should not throw', function () {
- expect(BufferedWorkerPool.create, 'not to throw');
+ describe("when passed no arguments", function () {
+ it("should not throw", function () {
+ expect(BufferedWorkerPool.create, "not to throw");
});
});
});
- describe('serializeOptions()', function () {
- describe('when passed no arguments', function () {
- it('should not throw', function () {
- expect(BufferedWorkerPool.serializeOptions, 'not to throw');
+ describe("serializeOptions()", function () {
+ describe("when passed no arguments", function () {
+ it("should not throw", function () {
+ expect(BufferedWorkerPool.serializeOptions, "not to throw");
});
});
- it('should return a serialized string', function () {
+ it("should return a serialized string", function () {
expect(
- BufferedWorkerPool.serializeOptions({foo: 'bar'}),
- 'to be a',
- 'string'
+ BufferedWorkerPool.serializeOptions({ foo: "bar" }),
+ "to be a",
+ "string",
);
});
- describe('when called multiple times with the same object', function () {
- it('should not perform serialization twice', function () {
- const obj = {foo: 'bar'};
+ describe("when called multiple times with the same object", function () {
+ it("should not perform serialization twice", function () {
+ const obj = { foo: "bar" };
BufferedWorkerPool.serializeOptions(obj);
BufferedWorkerPool.serializeOptions(obj);
- expect(serializeJavascript, 'was called once');
+ expect(serializeJavascript, "was called once");
});
- it('should return the same value', function () {
- const obj = {foo: 'bar'};
+ it("should return the same value", function () {
+ const obj = { foo: "bar" };
expect(
BufferedWorkerPool.serializeOptions(obj),
- 'to be',
- BufferedWorkerPool.serializeOptions(obj)
+ "to be",
+ BufferedWorkerPool.serializeOptions(obj),
);
});
});
});
});
- describe('constructor', function () {
- it('should apply defaults', function () {
- expect(new BufferedWorkerPool(), 'to satisfy', {
+ describe("constructor", function () {
+ it("should apply defaults", function () {
+ expect(new BufferedWorkerPool(), "to satisfy", {
options: {
- workerType: 'process',
- forkOpts: {execArgv: process.execArgv},
- maxWorkers: expect.it('to be greater than or equal to', 1)
- }
+ workerType: "process",
+ forkOpts: { execArgv: process.execArgv },
+ maxWorkers: expect.it("to be greater than or equal to", 1),
+ },
});
});
});
- describe('instance method', function () {
+ describe("instance method", function () {
let workerPool;
beforeEach(function () {
workerPool = BufferedWorkerPool.create();
});
- describe('stats()', function () {
- it('should return the object returned by `workerpool.Pool#stats`', function () {
- expect(workerPool.stats(), 'to be', stats);
+ describe("stats()", function () {
+ it("should return the object returned by `workerpool.Pool#stats`", function () {
+ expect(workerPool.stats(), "to be", stats);
});
});
- describe('run()', function () {
- describe('when passed no arguments', function () {
- it('should reject', async function () {
- return expect(workerPool.run(), 'to be rejected with', {
- code: 'ERR_MOCHA_INVALID_ARG_TYPE'
+ describe("run()", function () {
+ describe("when passed no arguments", function () {
+ it("should reject", async function () {
+ return expect(workerPool.run(), "to be rejected with", {
+ code: "ERR_MOCHA_INVALID_ARG_TYPE",
});
});
});
- describe('when passed a non-string filepath', function () {
- it('should reject', async function () {
- return expect(workerPool.run(123), 'to be rejected with', {
- code: 'ERR_MOCHA_INVALID_ARG_TYPE'
+ describe("when passed a non-string filepath", function () {
+ it("should reject", async function () {
+ return expect(workerPool.run(123), "to be rejected with", {
+ code: "ERR_MOCHA_INVALID_ARG_TYPE",
});
});
});
- it('should serialize the options object', async function () {
- await workerPool.run('file.js', {foo: 'bar'});
+ it("should serialize the options object", async function () {
+ await workerPool.run("file.js", { foo: "bar" });
- expect(pool.exec, 'to have a call satisfying', [
- 'run',
- ['file.js', '{"foo":"bar"}']
- ]).and('was called once');
+ expect(pool.exec, "to have a call satisfying", [
+ "run",
+ ["file.js", '{"foo":"bar"}'],
+ ]).and("was called once");
});
- it('should deserialize the result', async function () {
- await workerPool.run('file.js', {foo: 'bar'});
- expect(serializer.deserialize, 'to have a call satisfying', [
- result
- ]).and('was called once');
+ it("should deserialize the result", async function () {
+ await workerPool.run("file.js", { foo: "bar" });
+ expect(serializer.deserialize, "to have a call satisfying", [
+ result,
+ ]).and("was called once");
});
});
- describe('terminate()', function () {
- describe('when called with `force`', function () {
+ describe("terminate()", function () {
+ describe("when called with `force`", function () {
beforeEach(async function () {
await workerPool.terminate(true);
});
it('should delegate to the underlying pool w/ "force" behavior', async function () {
- expect(pool.terminate, 'to have a call satisfying', [true]).and(
- 'was called once'
+ expect(pool.terminate, "to have a call satisfying", [true]).and(
+ "was called once",
);
});
});
- describe('when called without `force`', function () {
+ describe("when called without `force`", function () {
beforeEach(async function () {
await workerPool.terminate();
});
it('should delegate to the underlying pool w/o "force" behavior', async function () {
- expect(pool.terminate, 'to have a call satisfying', [false]).and(
- 'was called once'
+ expect(pool.terminate, "to have a call satisfying", [false]).and(
+ "was called once",
);
});
});
diff --git a/test/node-unit/cli/config.spec.js b/test/node-unit/cli/config.spec.js
index 1dba0fe1..922f24e0 100644
--- a/test/node-unit/cli/config.spec.js
+++ b/test/node-unit/cli/config.spec.js
@@ -1,177 +1,177 @@
-'use strict';
+"use strict";
-const sinon = require('sinon');
-const rewiremock = require('rewiremock/node');
-const {parsers} = require('../../../lib/cli/config');
+const sinon = require("sinon");
+const rewiremock = require("rewiremock/node");
+const { parsers } = require("../../../lib/cli/config");
-describe('cli/config', function () {
- const phonyConfigObject = {ok: true};
+describe("cli/config", function () {
+ const phonyConfigObject = { ok: true };
afterEach(function () {
sinon.restore();
});
- describe('loadConfig()', function () {
+ describe("loadConfig()", function () {
let parsers;
let loadConfig;
beforeEach(function () {
const config = rewiremock.proxy(
- require.resolve('../../../lib/cli/config')
+ require.resolve("../../../lib/cli/config"),
);
parsers = config.parsers;
loadConfig = config.loadConfig;
});
- describe('when parsing succeeds', function () {
+ describe("when parsing succeeds", function () {
beforeEach(function () {
- sinon.stub(parsers, 'yaml').returns(phonyConfigObject);
- sinon.stub(parsers, 'json').returns(phonyConfigObject);
- sinon.stub(parsers, 'js').returns(phonyConfigObject);
+ sinon.stub(parsers, "yaml").returns(phonyConfigObject);
+ sinon.stub(parsers, "json").returns(phonyConfigObject);
+ sinon.stub(parsers, "js").returns(phonyConfigObject);
});
describe('when supplied a filepath with ".yaml" extension', function () {
- const filepath = 'foo.yaml';
+ const filepath = "foo.yaml";
- it('should use the YAML parser', function () {
+ it("should use the YAML parser", function () {
loadConfig(filepath);
- expect(parsers.yaml, 'to have calls satisfying', [
- {args: [filepath], returned: phonyConfigObject}
- ]).and('was called once');
+ expect(parsers.yaml, "to have calls satisfying", [
+ { args: [filepath], returned: phonyConfigObject },
+ ]).and("was called once");
});
});
describe('when supplied a filepath with ".yml" extension', function () {
- const filepath = 'foo.yml';
+ const filepath = "foo.yml";
- it('should use the YAML parser', function () {
+ it("should use the YAML parser", function () {
loadConfig(filepath);
- expect(parsers.yaml, 'to have calls satisfying', [
- {args: [filepath], returned: phonyConfigObject}
- ]).and('was called once');
+ expect(parsers.yaml, "to have calls satisfying", [
+ { args: [filepath], returned: phonyConfigObject },
+ ]).and("was called once");
});
});
describe('when supplied a filepath with ".js" extension', function () {
- const filepath = 'foo.js';
+ const filepath = "foo.js";
- it('should use the JS parser', function () {
+ it("should use the JS parser", function () {
loadConfig(filepath);
- expect(parsers.js, 'to have calls satisfying', [
- {args: [filepath], returned: phonyConfigObject}
- ]).and('was called once');
+ expect(parsers.js, "to have calls satisfying", [
+ { args: [filepath], returned: phonyConfigObject },
+ ]).and("was called once");
});
});
describe('when supplied a filepath with ".cjs" extension', function () {
- const filepath = 'foo.cjs';
+ const filepath = "foo.cjs";
- it('should use the JS parser', function () {
+ it("should use the JS parser", function () {
loadConfig(filepath);
- expect(parsers.js, 'to have calls satisfying', [
- {args: [filepath], returned: phonyConfigObject}
- ]).and('was called once');
+ expect(parsers.js, "to have calls satisfying", [
+ { args: [filepath], returned: phonyConfigObject },
+ ]).and("was called once");
});
});
describe('when supplied a filepath with ".jsonc" extension', function () {
- const filepath = 'foo.jsonc';
+ const filepath = "foo.jsonc";
- it('should use the JSON parser', function () {
- loadConfig('foo.jsonc');
- expect(parsers.json, 'to have calls satisfying', [
- {args: [filepath], returned: phonyConfigObject}
- ]).and('was called once');
+ it("should use the JSON parser", function () {
+ loadConfig("foo.jsonc");
+ expect(parsers.json, "to have calls satisfying", [
+ { args: [filepath], returned: phonyConfigObject },
+ ]).and("was called once");
});
});
describe('when supplied a filepath with ".json" extension', function () {
- const filepath = 'foo.json';
+ const filepath = "foo.json";
- it('should use the JSON parser', function () {
- loadConfig('foo.json');
- expect(parsers.json, 'to have calls satisfying', [
- {args: [filepath], returned: phonyConfigObject}
- ]).and('was called once');
+ it("should use the JSON parser", function () {
+ loadConfig("foo.json");
+ expect(parsers.json, "to have calls satisfying", [
+ { args: [filepath], returned: phonyConfigObject },
+ ]).and("was called once");
});
});
});
- describe('when supplied a filepath with unsupported extension', function () {
+ describe("when supplied a filepath with unsupported extension", function () {
beforeEach(function () {
- sinon.stub(parsers, 'json').returns(phonyConfigObject);
+ sinon.stub(parsers, "json").returns(phonyConfigObject);
});
- it('should use the JSON parser', function () {
- loadConfig('foo.bar');
- expect(parsers.json, 'was called');
+ it("should use the JSON parser", function () {
+ loadConfig("foo.bar");
+ expect(parsers.json, "was called");
});
});
- describe('when config file parsing fails', function () {
+ describe("when config file parsing fails", function () {
beforeEach(function () {
- sinon.stub(parsers, 'yaml').throws('goo.yaml is unparsable');
+ sinon.stub(parsers, "yaml").throws("goo.yaml is unparsable");
});
- it('should throw', function () {
+ it("should throw", function () {
expect(
- () => loadConfig('goo.yaml'),
- 'to throw',
- 'Unable to read/parse goo.yaml: goo.yaml is unparsable'
+ () => loadConfig("goo.yaml"),
+ "to throw",
+ "Unable to read/parse goo.yaml: goo.yaml is unparsable",
);
});
});
});
- describe('findConfig()', function () {
+ describe("findConfig()", function () {
let findup;
let findConfig;
let CONFIG_FILES;
beforeEach(function () {
- findup = {sync: sinon.stub().returns('/some/path/.mocharc.js')};
+ findup = { sync: sinon.stub().returns("/some/path/.mocharc.js") };
const config = rewiremock.proxy(
- require.resolve('../../../lib/cli/config'),
- r => ({
- 'find-up': r.by(() => findup)
- })
+ require.resolve("../../../lib/cli/config"),
+ (r) => ({
+ "find-up": r.by(() => findup),
+ }),
);
findConfig = config.findConfig;
CONFIG_FILES = config.CONFIG_FILES;
});
- it('should look for one of the config files using findup-sync', function () {
+ it("should look for one of the config files using findup-sync", function () {
findConfig();
- expect(findup, 'to have a call satisfying', {
- args: [CONFIG_FILES, {cwd: process.cwd()}],
- returned: '/some/path/.mocharc.js'
+ expect(findup, "to have a call satisfying", {
+ args: [CONFIG_FILES, { cwd: process.cwd() }],
+ returned: "/some/path/.mocharc.js",
});
});
- it('should support an explicit `cwd`', function () {
- findConfig('/some/path/');
- expect(findup, 'to have a call satisfying', {
- args: [CONFIG_FILES, {cwd: '/some/path/'}],
- returned: '/some/path/.mocharc.js'
+ it("should support an explicit `cwd`", function () {
+ findConfig("/some/path/");
+ expect(findup, "to have a call satisfying", {
+ args: [CONFIG_FILES, { cwd: "/some/path/" }],
+ returned: "/some/path/.mocharc.js",
});
});
});
- describe('parsers()', function () {
- it('should print error message for faulty require', function () {
+ describe("parsers()", function () {
+ it("should print error message for faulty require", function () {
// Fixture exists, but fails loading.
// Prints correct error message without using fallback path.
expect(
- () => parsers.js(require.resolve('./fixtures/bad-require.fixture.js')),
- 'to throw',
- {message: /Cannot find module 'fake'/, code: 'MODULE_NOT_FOUND'}
+ () => parsers.js(require.resolve("./fixtures/bad-require.fixture.js")),
+ "to throw",
+ { message: /Cannot find module 'fake'/, code: "MODULE_NOT_FOUND" },
);
});
- it('should print error message for non-existing file', function () {
- expect(() => parsers.js('not-existing.js'), 'to throw', {
+ it("should print error message for non-existing file", function () {
+ expect(() => parsers.js("not-existing.js"), "to throw", {
message: /Cannot find module 'not-existing.js'/,
- code: 'MODULE_NOT_FOUND'
+ code: "MODULE_NOT_FOUND",
});
});
});
diff --git a/test/node-unit/cli/fixtures/bad-module.fixture.js b/test/node-unit/cli/fixtures/bad-module.fixture.js
index 18fb55ce..232645bc 100644
--- a/test/node-unit/cli/fixtures/bad-module.fixture.js
+++ b/test/node-unit/cli/fixtures/bad-module.fixture.js
@@ -1 +1 @@
-throw new Error('this module is wonky');
+throw new Error("this module is wonky");
diff --git a/test/node-unit/cli/fixtures/bad-require.fixture.js b/test/node-unit/cli/fixtures/bad-require.fixture.js
index ad8ca090..6ef55cba 100644
--- a/test/node-unit/cli/fixtures/bad-require.fixture.js
+++ b/test/node-unit/cli/fixtures/bad-require.fixture.js
@@ -1 +1 @@
-require('fake');
+require("fake");
diff --git a/test/node-unit/cli/mocha-flags.spec.js b/test/node-unit/cli/mocha-flags.spec.js
index 29647dea..80a38f6e 100644
--- a/test/node-unit/cli/mocha-flags.spec.js
+++ b/test/node-unit/cli/mocha-flags.spec.js
@@ -1,27 +1,27 @@
-'use strict';
+"use strict";
const {
types,
- expectedTypeForFlag
-} = require('../../../lib/cli/run-option-metadata');
+ expectedTypeForFlag,
+} = require("../../../lib/cli/run-option-metadata");
-describe('mocha-flags', function () {
- describe('expectedTypeForFlag()', function () {
+describe("mocha-flags", function () {
+ describe("expectedTypeForFlag()", function () {
Object.entries(types).forEach(([dataType, flags]) => {
- flags.forEach(flag => {
+ flags.forEach((flag) => {
it(`returns expected ${flag}'s type as ${dataType}`, function () {
- expect(expectedTypeForFlag(flag), 'to equal', dataType);
+ expect(expectedTypeForFlag(flag), "to equal", dataType);
});
});
});
- it('returns undefined for node flags', function () {
- expect(expectedTypeForFlag('--throw-deprecation'), 'to equal', undefined);
- expect(expectedTypeForFlag('throw-deprecation'), 'to equal', undefined);
+ it("returns undefined for node flags", function () {
+ expect(expectedTypeForFlag("--throw-deprecation"), "to equal", undefined);
+ expect(expectedTypeForFlag("throw-deprecation"), "to equal", undefined);
});
- it('returns undefined for unsupported flags', function () {
- expect(expectedTypeForFlag('--foo'), 'to equal', undefined);
+ it("returns undefined for unsupported flags", function () {
+ expect(expectedTypeForFlag("--foo"), "to equal", undefined);
});
});
});
diff --git a/test/node-unit/cli/node-flags.spec.js b/test/node-unit/cli/node-flags.spec.js
index 828a8a93..12582b23 100644
--- a/test/node-unit/cli/node-flags.spec.js
+++ b/test/node-unit/cli/node-flags.spec.js
@@ -1,136 +1,136 @@
-'use strict';
+"use strict";
const nodeEnvFlags = [...process.allowedNodeEnvironmentFlags];
const {
isNodeFlag,
impliesNoTimeouts,
- unparseNodeFlags
-} = require('../../../lib/cli/node-flags');
+ unparseNodeFlags,
+} = require("../../../lib/cli/node-flags");
-const {isMochaFlag} = require('../../../lib/cli/run-option-metadata');
+const { isMochaFlag } = require("../../../lib/cli/run-option-metadata");
-describe('node-flags', function () {
- describe('isNodeFlag()', function () {
- describe('for all allowed node environment flags', function () {
+describe("node-flags", function () {
+ describe("isNodeFlag()", function () {
+ describe("for all allowed node environment flags", function () {
nodeEnvFlags
- .filter(flag => !isMochaFlag(flag))
- .forEach(envFlag => {
+ .filter((flag) => !isMochaFlag(flag))
+ .forEach((envFlag) => {
it(`${envFlag} should return true`, function () {
- expect(isNodeFlag(envFlag), 'to be true');
+ expect(isNodeFlag(envFlag), "to be true");
});
});
});
- describe('for all allowed node env flags which conflict with mocha flags', function () {
+ describe("for all allowed node env flags which conflict with mocha flags", function () {
nodeEnvFlags
- .filter(flag => isMochaFlag(flag))
- .forEach(envFlag => {
+ .filter((flag) => isMochaFlag(flag))
+ .forEach((envFlag) => {
it(`${envFlag} should return false`, function () {
- expect(isNodeFlag(envFlag), 'to be false');
+ expect(isNodeFlag(envFlag), "to be false");
});
});
});
- describe('when expecting leading dashes', function () {
- it('should require leading dashes', function () {
- expect(isNodeFlag('throw-deprecation', false), 'to be false');
- expect(isNodeFlag('--throw-deprecation', false), 'to be true');
+ describe("when expecting leading dashes", function () {
+ it("should require leading dashes", function () {
+ expect(isNodeFlag("throw-deprecation", false), "to be false");
+ expect(isNodeFlag("--throw-deprecation", false), "to be true");
});
});
- describe('special cases', function () {
+ describe("special cases", function () {
it('should return true for flags starting with "preserve-symlinks"', function () {
- expect(isNodeFlag('preserve-symlinks'), 'to be true');
- expect(isNodeFlag('preserve-symlinks-main'), 'to be true');
- expect(isNodeFlag('preserve_symlinks'), 'to be true');
+ expect(isNodeFlag("preserve-symlinks"), "to be true");
+ expect(isNodeFlag("preserve-symlinks-main"), "to be true");
+ expect(isNodeFlag("preserve_symlinks"), "to be true");
});
it('should return true for flags starting with "harmony-" or "harmony_"', function () {
- expect(isNodeFlag('harmony-literally-anything'), 'to be true');
- expect(isNodeFlag('harmony_literally_underscores'), 'to be true');
- expect(isNodeFlag('harmonynope'), 'to be false');
+ expect(isNodeFlag("harmony-literally-anything"), "to be true");
+ expect(isNodeFlag("harmony_literally_underscores"), "to be true");
+ expect(isNodeFlag("harmonynope"), "to be false");
});
it('should return true for flags starting with "trace-" or "trace_"', function () {
- expect(isNodeFlag('trace-literally-anything'), 'to be true');
- expect(isNodeFlag('trace_literally_underscores'), 'to be true');
- expect(isNodeFlag('tracenope'), 'to be false');
+ expect(isNodeFlag("trace-literally-anything"), "to be true");
+ expect(isNodeFlag("trace_literally_underscores"), "to be true");
+ expect(isNodeFlag("tracenope"), "to be false");
});
it('should return true for "harmony" itself', function () {
- expect(isNodeFlag('harmony'), 'to be true');
+ expect(isNodeFlag("harmony"), "to be true");
});
it('should return true for "gc-global"', function () {
- expect(isNodeFlag('gc-global'), 'to be true');
- expect(isNodeFlag('gc_global'), 'to be true');
+ expect(isNodeFlag("gc-global"), "to be true");
+ expect(isNodeFlag("gc_global"), "to be true");
});
it('should return true for "es-staging"', function () {
- expect(isNodeFlag('es-staging'), 'to be true');
- expect(isNodeFlag('es_staging'), 'to be true');
+ expect(isNodeFlag("es-staging"), "to be true");
+ expect(isNodeFlag("es_staging"), "to be true");
});
it('should return true for "use-strict"', function () {
- expect(isNodeFlag('use-strict'), 'to be true');
- expect(isNodeFlag('use_strict'), 'to be true');
+ expect(isNodeFlag("use-strict"), "to be true");
+ expect(isNodeFlag("use_strict"), "to be true");
});
it('should return true for flags starting with "--v8-"', function () {
- expect(isNodeFlag('v8-'), 'to be false');
- expect(isNodeFlag('v8-options'), 'to be false');
- expect(isNodeFlag('v8_options'), 'to be false');
- expect(isNodeFlag('v8-anything-else'), 'to be true');
- expect(isNodeFlag('v8_anything_else'), 'to be true');
+ expect(isNodeFlag("v8-"), "to be false");
+ expect(isNodeFlag("v8-options"), "to be false");
+ expect(isNodeFlag("v8_options"), "to be false");
+ expect(isNodeFlag("v8-anything-else"), "to be true");
+ expect(isNodeFlag("v8_anything_else"), "to be true");
});
});
});
- describe('impliesNoTimeouts()', function () {
- it('should return true for inspect flags', function () {
- expect(impliesNoTimeouts('inspect'), 'to be true');
- expect(impliesNoTimeouts('inspect-brk'), 'to be true');
+ describe("impliesNoTimeouts()", function () {
+ it("should return true for inspect flags", function () {
+ expect(impliesNoTimeouts("inspect"), "to be true");
+ expect(impliesNoTimeouts("inspect-brk"), "to be true");
});
});
- describe('unparseNodeFlags()', function () {
- it('should handle single v8 flags', function () {
- expect(unparseNodeFlags({'v8-numeric': 100}), 'to equal', [
- '--v8-numeric=100'
+ describe("unparseNodeFlags()", function () {
+ it("should handle single v8 flags", function () {
+ expect(unparseNodeFlags({ "v8-numeric": 100 }), "to equal", [
+ "--v8-numeric=100",
]);
- expect(unparseNodeFlags({'v8-boolean': true}), 'to equal', [
- '--v8-boolean'
+ expect(unparseNodeFlags({ "v8-boolean": true }), "to equal", [
+ "--v8-boolean",
]);
});
- it('should handle multiple v8 flags', function () {
+ it("should handle multiple v8 flags", function () {
expect(
- unparseNodeFlags({'v8-numeric-one': 1, 'v8-numeric-two': 2}),
- 'to equal',
- ['--v8-numeric-one=1', '--v8-numeric-two=2']
+ unparseNodeFlags({ "v8-numeric-one": 1, "v8-numeric-two": 2 }),
+ "to equal",
+ ["--v8-numeric-one=1", "--v8-numeric-two=2"],
);
expect(
- unparseNodeFlags({'v8-boolean-one': true, 'v8-boolean-two': true}),
- 'to equal',
- ['--v8-boolean-one', '--v8-boolean-two']
+ unparseNodeFlags({ "v8-boolean-one": true, "v8-boolean-two": true }),
+ "to equal",
+ ["--v8-boolean-one", "--v8-boolean-two"],
);
expect(
unparseNodeFlags({
- 'v8-boolean-one': true,
- 'v8-numeric-one': 1,
- 'v8-boolean-two': true
+ "v8-boolean-one": true,
+ "v8-numeric-one": 1,
+ "v8-boolean-two": true,
}),
- 'to equal',
- ['--v8-boolean-one', '--v8-numeric-one=1', '--v8-boolean-two']
+ "to equal",
+ ["--v8-boolean-one", "--v8-numeric-one=1", "--v8-boolean-two"],
);
expect(
unparseNodeFlags({
- 'v8-numeric-one': 1,
- 'v8-boolean-one': true,
- 'v8-numeric-two': 2
+ "v8-numeric-one": 1,
+ "v8-boolean-one": true,
+ "v8-numeric-two": 2,
}),
- 'to equal',
- ['--v8-numeric-one=1', '--v8-boolean-one', '--v8-numeric-two=2']
+ "to equal",
+ ["--v8-numeric-one=1", "--v8-boolean-one", "--v8-numeric-two=2"],
);
});
});
diff --git a/test/node-unit/cli/options.spec.js b/test/node-unit/cli/options.spec.js
index e9d62670..2efc343f 100644
--- a/test/node-unit/cli/options.spec.js
+++ b/test/node-unit/cli/options.spec.js
@@ -1,35 +1,35 @@
-'use strict';
+"use strict";
-const sinon = require('sinon');
-const rewiremock = require('rewiremock/node');
-const {ONE_AND_DONE_ARGS} = require('../../../lib/cli/one-and-dones');
-const {constants} = require('../../../lib/error-constants');
+const sinon = require("sinon");
+const rewiremock = require("rewiremock/node");
+const { ONE_AND_DONE_ARGS } = require("../../../lib/cli/one-and-dones");
+const { constants } = require("../../../lib/error-constants");
-const modulePath = require.resolve('../../../lib/cli/options');
-const mocharcPath = require.resolve('../../../lib/mocharc.json');
-const configPath = require.resolve('../../../lib/cli/config');
+const modulePath = require.resolve("../../../lib/cli/options");
+const mocharcPath = require.resolve("../../../lib/mocharc.json");
+const configPath = require.resolve("../../../lib/cli/config");
const proxyLoadOptions = ({
readFileSync = {},
findupSync = null,
findConfig = {},
- loadConfig = {}
+ loadConfig = {},
} = {}) =>
- rewiremock.proxy(modulePath, r => ({
- 'node:fs': r.with({readFileSync}).directChildOnly(),
+ rewiremock.proxy(modulePath, (r) => ({
+ "node:fs": r.with({ readFileSync }).directChildOnly(),
[mocharcPath]: defaults,
- 'find-up': r
- .by(() => (findupSync ? {sync: findupSync} : {}))
+ "find-up": r
+ .by(() => (findupSync ? { sync: findupSync } : {}))
.directChildOnly(),
- [configPath]: r.with({findConfig, loadConfig}).directChildOnly()
+ [configPath]: r.with({ findConfig, loadConfig }).directChildOnly(),
})).loadOptions;
const defaults = {
timeout: 1000,
- extension: ['js']
+ extension: ["js"],
};
-describe('options', function () {
+describe("options", function () {
let readFileSync;
let findupSync;
let loadOptions;
@@ -48,512 +48,510 @@ describe('options', function () {
* 4. `mocha` prop of `package.json`
* 5. default rc
*/
- describe('loadOptions()', function () {
- describe('when no parameter provided', function () {
+ describe("loadOptions()", function () {
+ describe("when no parameter provided", function () {
beforeEach(function () {
this.timeout(1000);
readFileSync = sinon.stub();
- readFileSync.onFirstCall().returns('{}');
- findConfig = sinon.stub().returns('/some/.mocharc.json');
+ readFileSync.onFirstCall().returns("{}");
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
loadConfig = sinon.stub().returns({});
- findupSync = sinon.stub().returns('/some/package.json');
+ findupSync = sinon.stub().returns("/some/package.json");
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
});
- it('should return an object containing positional args, defaults, and anti-reloading flags', function () {
+ it("should return an object containing positional args, defaults, and anti-reloading flags", function () {
expect(
loadOptions(),
- 'to equal',
+ "to equal",
Object.assign({}, defaults, {
_: [],
config: false,
- package: false
- })
+ package: false,
+ }),
);
});
});
- describe('when parameter provided', function () {
- describe('package.json', function () {
- describe('when path to package.json (`--package <path>`) is valid', function () {
+ describe("when parameter provided", function () {
+ describe("package.json", function () {
+ describe("when path to package.json (`--package <path>`) is valid", function () {
let result;
beforeEach(function () {
- const filepath = '/some/package.json';
+ const filepath = "/some/package.json";
readFileSync = sinon.stub();
// package.json
readFileSync.onFirstCall().returns('{"mocha": {"retries": 3}}');
- findConfig = sinon.stub().returns('/some/.mocharc.json');
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
loadConfig = sinon.stub().returns({});
findupSync = sinon.stub();
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
- result = loadOptions(['--package', filepath]);
+ result = loadOptions(["--package", filepath]);
});
- it('should return merged options incl. package.json opts', function () {
+ it("should return merged options incl. package.json opts", function () {
expect(
result,
- 'to equal',
+ "to equal",
Object.assign(
{
- _: []
+ _: [],
},
defaults,
{
config: false,
package: false,
- retries: 3
- }
- )
+ retries: 3,
+ },
+ ),
);
});
- it('should not try to find a package.json', function () {
- expect(findupSync, 'was not called');
+ it("should not try to find a package.json", function () {
+ expect(findupSync, "was not called");
});
- it('should set package = false', function () {
- expect(result, 'to have property', 'package', false);
+ it("should set package = false", function () {
+ expect(result, "to have property", "package", false);
});
});
- describe('when path to package.json (`--package <path>`) is invalid', function () {
+ describe("when path to package.json (`--package <path>`) is invalid", function () {
beforeEach(function () {
readFileSync = sinon.stub();
// package.json
- readFileSync.onFirstCall().throws('bad file message');
- findConfig = sinon.stub().returns('/some/.mocharc.json');
+ readFileSync.onFirstCall().throws("bad file message");
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
loadConfig = sinon.stub().returns({});
findupSync = sinon.stub();
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
});
- it('should throw', function () {
+ it("should throw", function () {
expect(
() => {
- loadOptions('--package /something/wherever --require butts');
+ loadOptions("--package /something/wherever --require butts");
},
- 'to throw',
- 'Unable to read /something/wherever: bad file message'
+ "to throw",
+ "Unable to read /something/wherever: bad file message",
);
});
});
- describe('when path to package.json unspecified', function () {
+ describe("when path to package.json unspecified", function () {
let result;
beforeEach(function () {
- const filepath = '/some/package.json';
+ const filepath = "/some/package.json";
readFileSync = sinon.stub();
// package.json
readFileSync
.onFirstCall()
.returns('{"mocha": {"retries": 3, "_": ["foobar.spec.js"]}}');
- findConfig = sinon.stub().returns('/some/.mocharc.json');
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
loadConfig = sinon.stub().returns({});
findupSync = sinon.stub().returns(filepath);
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
result = loadOptions();
});
- it('should return merged options incl. found package.json', function () {
+ it("should return merged options incl. found package.json", function () {
expect(
result,
- 'to equal',
+ "to equal",
Object.assign(
{
- _: ['foobar.spec.js']
+ _: ["foobar.spec.js"],
},
defaults,
{
config: false,
package: false,
- retries: 3
- }
- )
+ retries: 3,
+ },
+ ),
);
});
- it('should set package = false', function () {
- expect(result, 'to have property', 'package', false);
+ it("should set package = false", function () {
+ expect(result, "to have property", "package", false);
});
});
- describe('when path to package.json unspecified and package.json exists but is invalid', function () {
+ describe("when path to package.json unspecified and package.json exists but is invalid", function () {
beforeEach(function () {
- const filepath = '/some/package.json';
+ const filepath = "/some/package.json";
readFileSync = sinon.stub();
// package.json
- readFileSync
- .onFirstCall()
- .returns('{definitely-invalid');
- findConfig = sinon.stub().returns('/some/.mocharc.json');
+ readFileSync.onFirstCall().returns("{definitely-invalid");
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
loadConfig = sinon.stub().returns({});
findupSync = sinon.stub().returns(filepath);
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
});
- it('should throw', function () {
+ it("should throw", function () {
expect(
() => {
loadOptions();
},
- 'to throw',
- /SyntaxError/,
+ "to throw",
+ /SyntaxError/,
);
});
});
- describe('when called with package = false (`--no-package`)', function () {
+ describe("when called with package = false (`--no-package`)", function () {
let result;
beforeEach(function () {
readFileSync = sinon.stub();
- readFileSync.onFirstCall().returns('{}');
- findConfig = sinon.stub().returns('/some/path/to/.mocharc.json');
- loadConfig = sinon.stub().returns({'check-leaks': true});
- findupSync = sinon.stub().returns('/some/package.json');
+ readFileSync.onFirstCall().returns("{}");
+ findConfig = sinon.stub().returns("/some/path/to/.mocharc.json");
+ loadConfig = sinon.stub().returns({ "check-leaks": true });
+ findupSync = sinon.stub().returns("/some/package.json");
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
- result = loadOptions('--no-diff --no-package');
+ result = loadOptions("--no-diff --no-package");
});
- it('should return parsed args and default config', function () {
+ it("should return parsed args and default config", function () {
expect(
result,
- 'to equal',
- Object.assign({_: []}, defaults, {
+ "to equal",
+ Object.assign({ _: [] }, defaults, {
diff: false,
- 'check-leaks': true,
+ "check-leaks": true,
config: false,
- package: false
- })
+ package: false,
+ }),
);
});
- it('should not look for package.json', function () {
- expect(findupSync, 'was not called');
+ it("should not look for package.json", function () {
+ expect(findupSync, "was not called");
});
- it('should set package = false', function () {
- expect(result, 'to have property', 'package', false);
+ it("should set package = false", function () {
+ expect(result, "to have property", "package", false);
});
});
});
- describe('rc file', function () {
- describe('when called with config = false (`--no-config`)', function () {
+ describe("rc file", function () {
+ describe("when called with config = false (`--no-config`)", function () {
let result;
beforeEach(function () {
readFileSync = sinon.stub();
readFileSync
.onFirstCall()
.returns(
- '{"mocha": {"check-leaks": true, "_": ["foobar.spec.js"]}}'
+ '{"mocha": {"check-leaks": true, "_": ["foobar.spec.js"]}}',
);
findConfig = sinon.stub();
loadConfig = sinon.stub();
- findupSync = sinon.stub().returns('/some/package.json');
+ findupSync = sinon.stub().returns("/some/package.json");
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
- result = loadOptions('--no-diff --no-config');
+ result = loadOptions("--no-diff --no-config");
});
- it('should return parsed args, default config and package.json', function () {
+ it("should return parsed args, default config and package.json", function () {
expect(
result,
- 'to equal',
- Object.assign({_: ['foobar.spec.js']}, defaults, {
+ "to equal",
+ Object.assign({ _: ["foobar.spec.js"] }, defaults, {
diff: false,
- 'check-leaks': true,
+ "check-leaks": true,
config: false,
- package: false
- })
+ package: false,
+ }),
);
});
- it('should not attempt to load a config file', function () {
- expect(loadConfig, 'was not called');
+ it("should not attempt to load a config file", function () {
+ expect(loadConfig, "was not called");
});
- it('should not attempt to find a config file', function () {
- expect(findConfig, 'was not called');
+ it("should not attempt to find a config file", function () {
+ expect(findConfig, "was not called");
});
- it('should set config = false', function () {
- expect(result, 'to have property', 'config', false);
+ it("should set config = false", function () {
+ expect(result, "to have property", "config", false);
});
});
- describe('when path to config (`--config <path>`) is invalid', function () {
+ describe("when path to config (`--config <path>`) is invalid", function () {
let config;
beforeEach(function () {
readFileSync = sinon.stub();
- config = '/some/.mocharc.json';
- readFileSync.onFirstCall().returns('{}');
+ config = "/some/.mocharc.json";
+ readFileSync.onFirstCall().returns("{}");
findConfig = sinon.stub();
- loadConfig = sinon.stub().throws('Error', 'failed to parse');
- findupSync = sinon.stub().returns('/some/package.json');
+ loadConfig = sinon.stub().throws("Error", "failed to parse");
+ findupSync = sinon.stub().returns("/some/package.json");
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
});
- it('should not look for a config', function () {
+ it("should not look for a config", function () {
try {
loadOptions(`--config ${config}`);
} catch (ignored) {}
- expect(findConfig, 'was not called');
+ expect(findConfig, "was not called");
});
- it('should attempt to load file at path', function () {
+ it("should attempt to load file at path", function () {
try {
loadOptions(`--config ${config}`);
} catch (ignored) {}
- expect(loadConfig, 'to have a call satisfying', [config]);
+ expect(loadConfig, "to have a call satisfying", [config]);
});
- it('should throw to warn the user', function () {
+ it("should throw to warn the user", function () {
expect(
() => {
loadOptions(`--config ${config}`);
},
- 'to throw',
- 'failed to parse'
+ "to throw",
+ "failed to parse",
);
});
});
- describe('when called with unspecified config', function () {
- describe('when an rc file would be found', function () {
+ describe("when called with unspecified config", function () {
+ describe("when an rc file would be found", function () {
let result;
beforeEach(function () {
readFileSync = sinon.stub();
- readFileSync.onFirstCall().returns('{}');
+ readFileSync.onFirstCall().returns("{}");
readFileSync.onSecondCall().throws();
- findConfig = sinon.stub().returns('/some/.mocharc.json');
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
loadConfig = sinon.stub().returns({});
- findupSync = sinon.stub().returns('/some/package.json');
+ findupSync = sinon.stub().returns("/some/package.json");
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
result = loadOptions();
});
- it('should look for a config', function () {
- expect(findConfig, 'was called');
+ it("should look for a config", function () {
+ expect(findConfig, "was called");
});
- it('should attempt to load file at found path', function () {
- expect(loadConfig, 'to have a call satisfying', [
- '/some/.mocharc.json'
+ it("should attempt to load file at found path", function () {
+ expect(loadConfig, "to have a call satisfying", [
+ "/some/.mocharc.json",
]);
});
- it('should set config = false', function () {
- expect(result, 'to have property', 'config', false);
+ it("should set config = false", function () {
+ expect(result, "to have property", "config", false);
});
});
- describe('when an rc file would not be found', function () {
+ describe("when an rc file would not be found", function () {
let result;
beforeEach(function () {
readFileSync = sinon.stub();
- readFileSync.onFirstCall().returns('{}');
+ readFileSync.onFirstCall().returns("{}");
readFileSync.onSecondCall().throws();
findConfig = sinon.stub().returns(null);
loadConfig = sinon.stub().returns({});
- findupSync = sinon.stub().returns('/some/package.json');
+ findupSync = sinon.stub().returns("/some/package.json");
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
result = loadOptions();
});
- it('should look for a config', function () {
- expect(findConfig, 'was called');
+ it("should look for a config", function () {
+ expect(findConfig, "was called");
});
- it('should not attempt to load a config file', function () {
- expect(loadConfig, 'was not called');
+ it("should not attempt to load a config file", function () {
+ expect(loadConfig, "was not called");
});
- it('should set config = false', function () {
- expect(result, 'to have property', 'config', false);
+ it("should set config = false", function () {
+ expect(result, "to have property", "config", false);
});
});
});
});
});
- describe('env options', function () {
- it('should parse flags from MOCHA_OPTIONS', function () {
- readFileSync = sinon.stub().onFirstCall().returns('{}');
- findConfig = sinon.stub().returns('/some/.mocharc.json');
+ describe("env options", function () {
+ it("should parse flags from MOCHA_OPTIONS", function () {
+ readFileSync = sinon.stub().onFirstCall().returns("{}");
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
loadConfig = sinon.stub().returns({});
- findupSync = sinon.stub().returns('/some/package.json');
+ findupSync = sinon.stub().returns("/some/package.json");
sinon
- .stub(process, 'env')
- .value({MOCHA_OPTIONS: '--retries 42 --color'});
+ .stub(process, "env")
+ .value({ MOCHA_OPTIONS: "--retries 42 --color" });
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
- expect(loadOptions(), 'to satisfy', {
+ expect(loadOptions(), "to satisfy", {
retries: 42,
- color: true
+ color: true,
});
});
});
- describe('config priority', function () {
- it('should prioritize package.json over defaults', function () {
+ describe("config priority", function () {
+ it("should prioritize package.json over defaults", function () {
readFileSync = sinon.stub();
readFileSync
.onFirstCall()
.returns(
- '{"mocha": {"timeout": 700, "require": "bar", "extension": "ts"}}'
+ '{"mocha": {"timeout": 700, "require": "bar", "extension": "ts"}}',
);
- findConfig = sinon.stub().returns('/some/.mocharc.json');
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
loadConfig = sinon.stub().returns({});
- findupSync = sinon.stub().returns('/some/package.json');
+ findupSync = sinon.stub().returns("/some/package.json");
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
- expect(loadOptions(), 'to satisfy', {
+ expect(loadOptions(), "to satisfy", {
timeout: 700,
- require: ['bar'],
- extension: ['ts']
+ require: ["bar"],
+ extension: ["ts"],
});
});
- it('should prioritize rc file over package.json', function () {
+ it("should prioritize rc file over package.json", function () {
readFileSync = sinon.stub();
readFileSync.onFirstCall().returns('{"mocha": {"timeout": 700}}');
- readFileSync.onSecondCall().returns('--timeout 800');
- findConfig = sinon.stub().returns('/some/.mocharc.json');
- loadConfig = sinon.stub().returns({timeout: 600});
- findupSync = sinon.stub().returns('/some/package.json');
+ readFileSync.onSecondCall().returns("--timeout 800");
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
+ loadConfig = sinon.stub().returns({ timeout: 600 });
+ findupSync = sinon.stub().returns("/some/package.json");
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
- expect(loadOptions(), 'to have property', 'timeout', 600);
+ expect(loadOptions(), "to have property", "timeout", 600);
});
- it('should prioritize args over rc file', function () {
+ it("should prioritize args over rc file", function () {
readFileSync = sinon.stub();
readFileSync.onFirstCall().returns('{"mocha": {"timeout": 700}}');
- readFileSync.onSecondCall().returns('--timeout 800');
- findConfig = sinon.stub().returns('/some/.mocharc.json');
- loadConfig = sinon.stub().returns({timeout: 600});
- findupSync = sinon.stub().returns('/some/package.json');
+ readFileSync.onSecondCall().returns("--timeout 800");
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
+ loadConfig = sinon.stub().returns({ timeout: 600 });
+ findupSync = sinon.stub().returns("/some/package.json");
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
expect(
- loadOptions('--timeout 500'),
- 'to have property',
- 'timeout',
- '500'
+ loadOptions("--timeout 500"),
+ "to have property",
+ "timeout",
+ "500",
);
});
- it('should prioritize env over rc file', function () {
+ it("should prioritize env over rc file", function () {
readFileSync = sinon.stub();
- readFileSync.onFirstCall().returns('{}');
- readFileSync.onSecondCall().returns('');
- findConfig = sinon.stub().returns('/some/.mocharc.json');
- loadConfig = sinon.stub().returns({retries: 300});
- findupSync = sinon.stub().returns('/some/package.json');
+ readFileSync.onFirstCall().returns("{}");
+ readFileSync.onSecondCall().returns("");
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
+ loadConfig = sinon.stub().returns({ retries: 300 });
+ findupSync = sinon.stub().returns("/some/package.json");
sinon
- .stub(process, 'env')
- .value({MOCHA_OPTIONS: '--retries 800 --color'});
+ .stub(process, "env")
+ .value({ MOCHA_OPTIONS: "--retries 800 --color" });
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
- expect(loadOptions(), 'to have property', 'retries', 800);
+ expect(loadOptions(), "to have property", "retries", 800);
});
});
- describe('when called with a one-and-done arg', function () {
+ describe("when called with a one-and-done arg", function () {
beforeEach(function () {
readFileSync = sinon.stub();
findConfig = sinon.stub();
@@ -563,14 +561,14 @@ describe('options', function () {
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
});
- ONE_AND_DONE_ARGS.forEach(arg => {
+ ONE_AND_DONE_ARGS.forEach((arg) => {
describe(`"${arg}"`, function () {
it(`should return basic parsed arguments and flag`, function () {
- expect(loadOptions(`--${arg}`), 'to equal', {_: [], [arg]: true});
+ expect(loadOptions(`--${arg}`), "to equal", { _: [], [arg]: true });
});
});
});
@@ -583,20 +581,20 @@ describe('options', function () {
beforeEach(function () {
readFileSync = sinon.stub();
readFileSync.onFirstCall().throws();
- findConfig = sinon.stub().returns('/some/.mocharc.json');
- loadConfig = sinon.stub().returns({extension: ['tsx']});
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
+ loadConfig = sinon.stub().returns({ extension: ["tsx"] });
findupSync = sinon.stub();
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
- result = loadOptions(['--extension', 'ts']);
+ result = loadOptions(["--extension", "ts"]);
});
- it('should not concatenate the default value', function () {
- expect(result, 'to have property', 'extension', ['ts', 'tsx']);
+ it("should not concatenate the default value", function () {
+ expect(result, "to have property", "extension", ["ts", "tsx"]);
});
});
@@ -606,20 +604,20 @@ describe('options', function () {
beforeEach(function () {
readFileSync = sinon.stub();
readFileSync.onFirstCall().throws();
- findConfig = sinon.stub().returns('/some/.mocharc.json');
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
loadConfig = sinon.stub().returns({});
findupSync = sinon.stub();
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
result = loadOptions();
});
- it('should retain the default', function () {
- expect(result, 'to have property', 'extension', ['js']);
+ it("should retain the default", function () {
+ expect(result, "to have property", "extension", ["js"]);
});
});
});
@@ -631,22 +629,24 @@ describe('options', function () {
beforeEach(function () {
readFileSync = sinon.stub();
readFileSync.onFirstCall().throws();
- findConfig = sinon.stub().returns('/some/.mocharc.json');
- loadConfig = sinon.stub().returns({spec: '{dirA,dirB}/**/*.spec.js'});
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
+ loadConfig = sinon
+ .stub()
+ .returns({ spec: "{dirA,dirB}/**/*.spec.js" });
findupSync = sinon.stub();
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
- result = loadOptions(['*.test.js']);
+ result = loadOptions(["*.test.js"]);
});
- it('should place both - unsplitted - into the positional arguments array', function () {
- expect(result, 'to have property', '_', [
- '*.test.js',
- '{dirA,dirB}/**/*.spec.js'
+ it("should place both - unsplitted - into the positional arguments array", function () {
+ expect(result, "to have property", "_", [
+ "*.test.js",
+ "{dirA,dirB}/**/*.spec.js",
]);
});
});
@@ -658,22 +658,24 @@ describe('options', function () {
beforeEach(function () {
readFileSync = sinon.stub();
readFileSync.onFirstCall().throws();
- findConfig = sinon.stub().returns('/some/.mocharc.json');
- loadConfig = sinon.stub().returns({ignore: '{dirA,dirB}/**/*.spec.js'});
+ findConfig = sinon.stub().returns("/some/.mocharc.json");
+ loadConfig = sinon
+ .stub()
+ .returns({ ignore: "{dirA,dirB}/**/*.spec.js" });
findupSync = sinon.stub();
loadOptions = proxyLoadOptions({
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
- result = loadOptions(['--ignore', '*.test.js']);
+ result = loadOptions(["--ignore", "*.test.js"]);
});
- it('should not split option values by comma', function () {
- expect(result, 'to have property', 'ignore', [
- '*.test.js',
- '{dirA,dirB}/**/*.spec.js'
+ it("should not split option values by comma", function () {
+ expect(result, "to have property", "ignore", [
+ "*.test.js",
+ "{dirA,dirB}/**/*.spec.js",
]);
});
});
@@ -681,20 +683,20 @@ describe('options', function () {
describe('"numeric arguments"', function () {
const numericArg = 123;
- const unsupportedError = arg => {
+ const unsupportedError = (arg) => {
return {
message: `Option ${arg} is unsupported by the mocha cli`,
- code: constants.UNSUPPORTED
+ code: constants.UNSUPPORTED,
};
};
- const invalidArgError = (flag, arg, expectedType = 'string') => {
+ const invalidArgError = (flag, arg, expectedType = "string") => {
return {
message: `Mocha flag '${flag}' given invalid option: '${arg}'`,
code: constants.INVALID_ARG_TYPE,
argument: arg,
- actual: 'number',
- expected: expectedType
+ actual: "number",
+ expected: expectedType,
};
};
@@ -707,77 +709,77 @@ describe('options', function () {
readFileSync,
findConfig,
loadConfig,
- findupSync
+ findupSync,
});
});
- it('throws UNSUPPORTED error when numeric option is passed to cli', function () {
+ it("throws UNSUPPORTED error when numeric option is passed to cli", function () {
expect(
() => loadOptions(`${numericArg}`),
- 'to throw',
- unsupportedError(numericArg)
+ "to throw",
+ unsupportedError(numericArg),
);
});
- it('throws INVALID_ARG_TYPE error when numeric argument is passed to mocha flag that does not accept numeric value', function () {
- const flag = '--delay';
+ it("throws INVALID_ARG_TYPE error when numeric argument is passed to mocha flag that does not accept numeric value", function () {
+ const flag = "--delay";
expect(
() => loadOptions(`${flag} ${numericArg}`),
- 'to throw',
- invalidArgError(flag, numericArg, 'boolean')
+ "to throw",
+ invalidArgError(flag, numericArg, "boolean"),
);
});
it('throws INVALID_ARG_TYPE error when incompatible flag does not have preceding "--"', function () {
- const flag = 'delay';
+ const flag = "delay";
expect(
() => loadOptions(`${flag} ${numericArg}`),
- 'to throw',
- invalidArgError(flag, numericArg, 'boolean')
+ "to throw",
+ invalidArgError(flag, numericArg, "boolean"),
);
});
- it('shows correct flag in error when multiple mocha flags have numeric values', function () {
- const flag = '--delay';
+ it("shows correct flag in error when multiple mocha flags have numeric values", function () {
+ const flag = "--delay";
expect(
() =>
loadOptions(
- `--timeout ${numericArg} ${flag} ${numericArg} --retries ${numericArg}`
+ `--timeout ${numericArg} ${flag} ${numericArg} --retries ${numericArg}`,
),
- 'to throw',
- invalidArgError(flag, numericArg, 'boolean')
+ "to throw",
+ invalidArgError(flag, numericArg, "boolean"),
);
});
- it('throws UNSUPPORTED error when numeric arg is passed to unsupported flag', function () {
- const invalidFlag = 'foo';
+ it("throws UNSUPPORTED error when numeric arg is passed to unsupported flag", function () {
+ const invalidFlag = "foo";
expect(
() => loadOptions(`${invalidFlag} ${numericArg}`),
- 'to throw',
- unsupportedError(numericArg)
+ "to throw",
+ unsupportedError(numericArg),
);
});
- it('does not throw error if numeric value is passed to a compatible mocha flag', function () {
- expect(() => loadOptions(`--retries ${numericArg}`), 'not to throw');
+ it("does not throw error if numeric value is passed to a compatible mocha flag", function () {
+ expect(() => loadOptions(`--retries ${numericArg}`), "not to throw");
});
- it('does not throw error if numeric value is passed to a node options', function () {
+ it("does not throw error if numeric value is passed to a node options", function () {
expect(
() =>
loadOptions(
- `--secure-heap-min=${numericArg} --conditions=${numericArg}`
+ `--secure-heap-min=${numericArg} --conditions=${numericArg}`,
),
- 'not to throw'
+ "not to throw",
);
});
- it('does not throw error if numeric value is passed to string flag', function () {
- expect(() => loadOptions(`--grep ${numericArg}`), 'not to throw');
+ it("does not throw error if numeric value is passed to string flag", function () {
+ expect(() => loadOptions(`--grep ${numericArg}`), "not to throw");
});
- it('does not throw error if numeric value is passed to an array flag', function () {
- expect(() => loadOptions(`--spec ${numericArg}`), 'not to throw');
+ it("does not throw error if numeric value is passed to an array flag", function () {
+ expect(() => loadOptions(`--spec ${numericArg}`), "not to throw");
});
});
});
diff --git a/test/node-unit/cli/run-helpers.spec.js b/test/node-unit/cli/run-helpers.spec.js
index 889b48f5..34268c4e 100644
--- a/test/node-unit/cli/run-helpers.spec.js
+++ b/test/node-unit/cli/run-helpers.spec.js
@@ -1,80 +1,83 @@
-'use strict';
+"use strict";
-const {validateLegacyPlugin, list} = require('../../../lib/cli/run-helpers');
-const Mocha = require('../../../lib/mocha');
+const { validateLegacyPlugin, list } = require("../../../lib/cli/run-helpers");
+const Mocha = require("../../../lib/mocha");
-describe('helpers', function () {
- describe('validateLegacyPlugin()', function () {
+describe("helpers", function () {
+ describe("validateLegacyPlugin()", function () {
describe('when used with "reporter" key', function () {
- it('should disallow an array of names', function () {
+ it("should disallow an array of names", function () {
expect(
- () => validateLegacyPlugin({reporter: ['bar']}, 'reporter'),
- 'to throw',
+ () => validateLegacyPlugin({ reporter: ["bar"] }, "reporter"),
+ "to throw",
{
- code: 'ERR_MOCHA_INVALID_REPORTER',
- message: /can only be specified once/i
- }
+ code: "ERR_MOCHA_INVALID_REPORTER",
+ message: /can only be specified once/i,
+ },
);
});
- it('should fail to recognize an unknown reporter', function () {
+ it("should fail to recognize an unknown reporter", function () {
expect(
- () => validateLegacyPlugin({reporter: 'bar'}, 'reporter'),
- 'to throw',
- {code: 'ERR_MOCHA_INVALID_REPORTER', message: /cannot find module/i}
+ () => validateLegacyPlugin({ reporter: "bar" }, "reporter"),
+ "to throw",
+ {
+ code: "ERR_MOCHA_INVALID_REPORTER",
+ message: /cannot find module/i,
+ },
);
});
});
describe('when used with an "ui" key', function () {
- it('should disallow an array of names', function () {
- expect(() => validateLegacyPlugin({ui: ['bar']}, 'ui'), 'to throw', {
- code: 'ERR_MOCHA_INVALID_INTERFACE',
- message: /can only be specified once/i
+ it("should disallow an array of names", function () {
+ expect(() => validateLegacyPlugin({ ui: ["bar"] }, "ui"), "to throw", {
+ code: "ERR_MOCHA_INVALID_INTERFACE",
+ message: /can only be specified once/i,
});
});
- it('should fail to recognize an unknown interface', function () {
- expect(() => validateLegacyPlugin({ui: 'bar'}, 'ui'), 'to throw', {
- code: 'ERR_MOCHA_INVALID_INTERFACE',
- message: /cannot find module/i
+ it("should fail to recognize an unknown interface", function () {
+ expect(() => validateLegacyPlugin({ ui: "bar" }, "ui"), "to throw", {
+ code: "ERR_MOCHA_INVALID_INTERFACE",
+ message: /cannot find module/i,
});
});
});
- describe('when used with an unknown plugin type', function () {
- it('should fail', function () {
+ describe("when used with an unknown plugin type", function () {
+ it("should fail", function () {
expect(
- () => validateLegacyPlugin({frog: 'bar'}, 'frog'),
- 'to throw',
- /unknown plugin/i
+ () => validateLegacyPlugin({ frog: "bar" }, "frog"),
+ "to throw",
+ /unknown plugin/i,
);
});
});
- describe('when used with a third-party interface', function () {
+ describe("when used with a third-party interface", function () {
it('should add the interface to "Mocha.interfaces"', function () {
// let's suppose that `glob` is an interface
- const opts = {ui: 'glob'};
- validateLegacyPlugin(opts, 'ui', Mocha.interfaces);
- expect(opts.ui, 'to equal', 'glob');
- expect(Mocha.interfaces, 'to satisfy', {glob: require('glob')});
+ const opts = { ui: "glob" };
+ validateLegacyPlugin(opts, "ui", Mocha.interfaces);
+ expect(opts.ui, "to equal", "glob");
+ expect(Mocha.interfaces, "to satisfy", { glob: require("glob") });
delete Mocha.interfaces.glob;
});
});
- describe('when a plugin throws an exception upon load', function () {
- it('should fail and report the original error', function () {
+ describe("when a plugin throws an exception upon load", function () {
+ it("should fail and report the original error", function () {
expect(
() =>
validateLegacyPlugin(
{
- reporter: require.resolve('./fixtures/bad-module.fixture.js')
+ reporter: require.resolve("./fixtures/bad-module.fixture.js"),
},
- 'reporter'
+ "reporter",
),
- 'to throw',
- {message: /wonky/, code: 'ERR_MOCHA_INVALID_REPORTER'}
+ "to throw",
+ { message: /wonky/, code: "ERR_MOCHA_INVALID_REPORTER" },
);
});
@@ -83,38 +86,38 @@ describe('helpers', function () {
() =>
validateLegacyPlugin(
{
- reporter: require.resolve('./fixtures/bad-require.fixture.js')
+ reporter: require.resolve("./fixtures/bad-require.fixture.js"),
},
- 'reporter'
+ "reporter",
),
- 'to throw',
+ "to throw",
{
message: /Error: Cannot find module 'fake'/,
- code: 'ERR_MOCHA_INVALID_REPORTER'
- }
+ code: "ERR_MOCHA_INVALID_REPORTER",
+ },
);
});
});
});
- describe('list()', function () {
- describe('when provided a flat array', function () {
- it('should return a flat array', function () {
- expect(list(['foo', 'bar']), 'to equal', ['foo', 'bar']);
+ describe("list()", function () {
+ describe("when provided a flat array", function () {
+ it("should return a flat array", function () {
+ expect(list(["foo", "bar"]), "to equal", ["foo", "bar"]);
});
});
- describe('when provided a nested array', function () {
- it('should return a flat array', function () {
- expect(list([['foo', 'bar'], 'baz']), 'to equal', [
- 'foo',
- 'bar',
- 'baz'
+ describe("when provided a nested array", function () {
+ it("should return a flat array", function () {
+ expect(list([["foo", "bar"], "baz"]), "to equal", [
+ "foo",
+ "bar",
+ "baz",
]);
});
});
- describe('when given a comma-delimited string', function () {
- it('should return a flat array', function () {
- expect(list('foo,bar'), 'to equal', ['foo', 'bar']);
+ describe("when given a comma-delimited string", function () {
+ it("should return a flat array", function () {
+ expect(list("foo,bar"), "to equal", ["foo", "bar"]);
});
});
});
diff --git a/test/node-unit/cli/run.spec.js b/test/node-unit/cli/run.spec.js
index 1e0ccd7b..aa61661e 100644
--- a/test/node-unit/cli/run.spec.js
+++ b/test/node-unit/cli/run.spec.js
@@ -1,19 +1,19 @@
-'use strict';
+"use strict";
-const {builder} = require('../../../lib/cli/run');
-const {types} = require('../../../lib/cli/run-option-metadata');
+const { builder } = require("../../../lib/cli/run");
+const { types } = require("../../../lib/cli/run-option-metadata");
-describe('command', function () {
- describe('run', function () {
- describe('builder', function () {
- const IGNORED_OPTIONS = new Set(['help', 'version']);
- const options = builder(require('yargs')()).getOptions();
- ['number', 'string', 'boolean', 'array'].forEach(type => {
+describe("command", function () {
+ describe("run", function () {
+ describe("builder", function () {
+ const IGNORED_OPTIONS = new Set(["help", "version"]);
+ const options = builder(require("yargs")()).getOptions();
+ ["number", "string", "boolean", "array"].forEach((type) => {
describe(`${type} type`, function () {
- Array.from(new Set(options[type])).forEach(option => {
+ Array.from(new Set(options[type])).forEach((option) => {
if (!IGNORED_OPTIONS.has(option)) {
it(`should include option ${option}`, function () {
- expect(types[type], 'to contain', option);
+ expect(types[type], "to contain", option);
});
}
});
diff --git a/test/node-unit/esm-utils.spec.js b/test/node-unit/esm-utils.spec.js
index 2ca4cbfc..caaaf249 100644
--- a/test/node-unit/esm-utils.spec.js
+++ b/test/node-unit/esm-utils.spec.js
@@ -1,77 +1,76 @@
-'use strict';
+"use strict";
-const esmUtils = require('../../lib/nodejs/esm-utils');
-const sinon = require('sinon');
-const url = require('node:url');
+const esmUtils = require("../../lib/nodejs/esm-utils");
+const sinon = require("sinon");
+const url = require("node:url");
-describe('esm-utils', function () {
- describe('requireOrImport', function () {
- it('should show an informative error message for a broken default import', async function () {
+describe("esm-utils", function () {
+ describe("requireOrImport", function () {
+ it("should show an informative error message for a broken default import", async function () {
return expect(
() =>
esmUtils.requireOrImport(
- '../../test/node-unit/fixtures/broken-default-import.mjs'
+ "../../test/node-unit/fixtures/broken-default-import.mjs",
),
- 'to be rejected with error satisfying',
+ "to be rejected with error satisfying",
{
- name: 'SyntaxError',
+ name: "SyntaxError",
message:
- "The requested module './module-without-default-export.mjs' does not provide an export named 'default'"
- }
+ "The requested module './module-without-default-export.mjs' does not provide an export named 'default'",
+ },
);
});
- it('should show a syntax error message when importing a TypeScript file with invalid syntax', async function () {
+ it("should show a syntax error message when importing a TypeScript file with invalid syntax", async function () {
return expect(
() =>
esmUtils.requireOrImport(
- '../../test/node-unit/fixtures/broken-syntax.ts'
+ "../../test/node-unit/fixtures/broken-syntax.ts",
),
- 'to be rejected with error satisfying',
+ "to be rejected with error satisfying",
{
- name: 'SyntaxError',
- message:
- /Invalid or unexpected token|Expected ident/
- }
+ name: "SyntaxError",
+ message: /Invalid or unexpected token|Expected ident/,
+ },
);
});
});
- describe('loadFilesAsync()', function () {
+ describe("loadFilesAsync()", function () {
beforeEach(function () {
- sinon.stub(esmUtils, 'doImport').resolves({});
+ sinon.stub(esmUtils, "doImport").resolves({});
});
afterEach(function () {
sinon.restore();
});
- it('should not decorate imported module if no decorator passed', async function () {
+ it("should not decorate imported module if no decorator passed", async function () {
await esmUtils.loadFilesAsync(
- ['/foo/bar.mjs'],
+ ["/foo/bar.mjs"],
+ () => {},
() => {},
- () => {}
);
expect(
esmUtils.doImport.firstCall.args[0].toString(),
- 'to be',
- url.pathToFileURL('/foo/bar.mjs').toString()
+ "to be",
+ url.pathToFileURL("/foo/bar.mjs").toString(),
);
});
- it('should decorate imported module with passed decorator', async function () {
+ it("should decorate imported module with passed decorator", async function () {
await esmUtils.loadFilesAsync(
- ['/foo/bar.mjs'],
+ ["/foo/bar.mjs"],
() => {},
() => {},
- x => `${x}?foo=bar`
+ (x) => `${x}?foo=bar`,
);
expect(
esmUtils.doImport.firstCall.args[0].toString(),
- 'to be',
- `${url.pathToFileURL('/foo/bar.mjs').toString()}?foo=bar`
+ "to be",
+ `${url.pathToFileURL("/foo/bar.mjs").toString()}?foo=bar`,
);
});
});
diff --git a/test/node-unit/mocha.spec.js b/test/node-unit/mocha.spec.js
index b6488569..50603f2e 100644
--- a/test/node-unit/mocha.spec.js
+++ b/test/node-unit/mocha.spec.js
@@ -1,61 +1,61 @@
-'use strict';
+"use strict";
-const path = require('node:path');
-const rewiremock = require('rewiremock/node');
-const sinon = require('sinon');
-const {EventEmitter} = require('node:events');
+const path = require("node:path");
+const rewiremock = require("rewiremock/node");
+const sinon = require("sinon");
+const { EventEmitter } = require("node:events");
-const DUMB_FIXTURE_PATH = require.resolve('./fixtures/dumb-module.fixture.js');
+const DUMB_FIXTURE_PATH = require.resolve("./fixtures/dumb-module.fixture.js");
const DUMBER_FIXTURE_PATH = require.resolve(
- './fixtures/dumber-module.fixture.js'
+ "./fixtures/dumber-module.fixture.js",
);
-describe('Mocha', function () {
+describe("Mocha", function () {
let stubs;
let opts;
let Mocha;
beforeEach(function () {
- opts = {reporter: sinon.stub()};
+ opts = { reporter: sinon.stub() };
stubs = {};
stubs.errors = {
warn: sinon.stub(),
createMochaInstanceAlreadyDisposedError: sinon
.stub()
- .throws({code: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED'}),
+ .throws({ code: "ERR_MOCHA_INSTANCE_ALREADY_DISPOSED" }),
createInvalidReporterError: sinon
.stub()
- .throws({code: 'ERR_MOCHA_INVALID_REPORTER'}),
+ .throws({ code: "ERR_MOCHA_INVALID_REPORTER" }),
createUnsupportedError: sinon
.stub()
- .throws({code: 'ERR_MOCHA_UNSUPPORTED'})
+ .throws({ code: "ERR_MOCHA_UNSUPPORTED" }),
};
stubs.utils = {
supportsEsModules: sinon.stub().returns(false),
isString: sinon.stub(),
noop: sinon.stub(),
cwd: sinon.stub().returns(process.cwd()),
- isBrowser: sinon.stub().returns(false)
+ isBrowser: sinon.stub().returns(false),
};
stubs.suite = Object.assign(sinon.createStubInstance(EventEmitter), {
slow: sinon.stub(),
timeout: sinon.stub(),
bail: sinon.stub(),
reset: sinon.stub(),
- dispose: sinon.stub()
+ dispose: sinon.stub(),
});
stubs.Suite = sinon.stub().returns(stubs.suite);
stubs.Suite.constants = {};
stubs.ParallelBufferedRunner = sinon.stub().returns({});
stubs.esmUtils = {
- loadFilesAsync: sinon.stub()
+ loadFilesAsync: sinon.stub(),
};
const runner = Object.assign(sinon.createStubInstance(EventEmitter), {
runAsync: sinon.stub().resolves(0),
globals: sinon.stub(),
grep: sinon.stub(),
- dispose: sinon.stub()
+ dispose: sinon.stub(),
});
stubs.Runner = sinon.stub().returns(runner);
// the Runner constructor is the main export, and constants is a static prop.
@@ -63,16 +63,16 @@ describe('Mocha', function () {
stubs.Runner.constants = {};
Mocha = rewiremock.proxy(
- () => require('../../lib/mocha'),
- r => ({
- '../../lib/utils.js': r.with(stubs.utils).callThrough(),
- '../../lib/suite.js': stubs.Suite,
- '../../lib/nodejs/parallel-buffered-runner.js':
+ () => require("../../lib/mocha"),
+ (r) => ({
+ "../../lib/utils.js": r.with(stubs.utils).callThrough(),
+ "../../lib/suite.js": stubs.Suite,
+ "../../lib/nodejs/parallel-buffered-runner.js":
stubs.ParallelBufferedRunner,
- '../../lib/nodejs/esm-utils': stubs.esmUtils,
- '../../lib/runner.js': stubs.Runner,
- '../../lib/errors.js': stubs.errors
- })
+ "../../lib/nodejs/esm-utils": stubs.esmUtils,
+ "../../lib/runner.js": stubs.Runner,
+ "../../lib/errors.js": stubs.errors,
+ }),
);
delete require.cache[DUMB_FIXTURE_PATH];
delete require.cache[DUMBER_FIXTURE_PATH];
@@ -84,108 +84,108 @@ describe('Mocha', function () {
sinon.restore();
});
- describe('instance method', function () {
+ describe("instance method", function () {
let mocha;
beforeEach(function () {
mocha = new Mocha(opts);
});
- describe('parallelMode()', function () {
- describe('when `Mocha` is running in Node.js', function () {
- it('should return the Mocha instance', function () {
- expect(mocha.parallelMode(), 'to be', mocha);
+ describe("parallelMode()", function () {
+ describe("when `Mocha` is running in Node.js", function () {
+ it("should return the Mocha instance", function () {
+ expect(mocha.parallelMode(), "to be", mocha);
});
- describe('when parallel mode is already enabled', function () {
+ describe("when parallel mode is already enabled", function () {
beforeEach(function () {
mocha.options.parallel = true;
mocha._runnerClass = stubs.ParallelBufferedRunner;
mocha._lazyLoadFiles = true;
});
- it('should not swap the Runner, nor change lazy loading setting', function () {
- expect(mocha.parallelMode(true), 'to satisfy', {
- options: {parallel: true},
+ it("should not swap the Runner, nor change lazy loading setting", function () {
+ expect(mocha.parallelMode(true), "to satisfy", {
+ options: { parallel: true },
_runnerClass: stubs.ParallelBufferedRunner,
- _lazyLoadFiles: true
+ _lazyLoadFiles: true,
});
});
});
- describe('when parallel mode is already disabled', function () {
+ describe("when parallel mode is already disabled", function () {
beforeEach(function () {
mocha.options.parallel = false;
mocha._runnerClass = Mocha.Runner;
mocha._lazyLoadFiles = false;
});
- it('should not swap the Runner, nor change lazy loading setting', function () {
- expect(mocha.parallelMode(false), 'to satisfy', {
- options: {parallel: false},
+ it("should not swap the Runner, nor change lazy loading setting", function () {
+ expect(mocha.parallelMode(false), "to satisfy", {
+ options: { parallel: false },
_runnerClass: Mocha.Runner,
- _lazyLoadFiles: false
+ _lazyLoadFiles: false,
});
});
});
- describe('when `Mocha` instance in serial mode', function () {
+ describe("when `Mocha` instance in serial mode", function () {
beforeEach(function () {
mocha.options.parallel = false;
});
- describe('when passed `true` value', function () {
- describe('when `Mocha` instance is in `INIT` state', function () {
+ describe("when passed `true` value", function () {
+ describe("when `Mocha` instance is in `INIT` state", function () {
beforeEach(function () {
- mocha._state = 'init';
+ mocha._state = "init";
});
- it('should enable parallel mode', function () {
+ it("should enable parallel mode", function () {
// FIXME: the dynamic require() call breaks the mock of
// `ParallelBufferedRunner` and returns the real class.
// don't know how to make this work or if it's even possible
- expect(mocha.parallelMode(true), 'to satisfy', {
- _runnerClass: expect.it('not to be', Mocha.Runner),
+ expect(mocha.parallelMode(true), "to satisfy", {
+ _runnerClass: expect.it("not to be", Mocha.Runner),
options: {
- parallel: true
+ parallel: true,
},
- _lazyLoadFiles: true
+ _lazyLoadFiles: true,
});
});
});
- describe('when `Mocha` instance is not in `INIT` state', function () {
+ describe("when `Mocha` instance is not in `INIT` state", function () {
beforeEach(function () {
- mocha._state = 'disposed';
+ mocha._state = "disposed";
});
- it('should throw', function () {
+ it("should throw", function () {
expect(
() => {
mocha.parallelMode(true);
},
- 'to throw',
+ "to throw",
{
- code: 'ERR_MOCHA_UNSUPPORTED'
- }
+ code: "ERR_MOCHA_UNSUPPORTED",
+ },
);
});
});
});
- describe('when passed non-`true` value', function () {
- describe('when `Mocha` instance is in `INIT` state', function () {
+ describe("when passed non-`true` value", function () {
+ describe("when `Mocha` instance is in `INIT` state", function () {
beforeEach(function () {
- mocha._state = 'init';
+ mocha._state = "init";
});
- it('should enable serial mode', function () {
- expect(mocha.parallelMode(0), 'to satisfy', {
+ it("should enable serial mode", function () {
+ expect(mocha.parallelMode(0), "to satisfy", {
_runnerClass: Mocha.Runner,
options: {
- parallel: false
+ parallel: false,
},
- _lazyLoadFiles: false
+ _lazyLoadFiles: false,
});
});
});
@@ -194,169 +194,169 @@ describe('Mocha', function () {
});
});
- describe('addFile()', function () {
- it('should add the given file to the files array', function () {
- mocha.addFile('some-file.js');
- expect(mocha.files, 'to exhaustively satisfy', ['some-file.js']);
+ describe("addFile()", function () {
+ it("should add the given file to the files array", function () {
+ mocha.addFile("some-file.js");
+ expect(mocha.files, "to exhaustively satisfy", ["some-file.js"]);
});
- it('should be chainable', function () {
- expect(mocha.addFile('some-file.js'), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.addFile("some-file.js"), "to be", mocha);
});
});
- describe('loadFiles()', function () {
- it('should load all files from the files array', function () {
+ describe("loadFiles()", function () {
+ it("should load all files from the files array", function () {
this.timeout(1000);
mocha.files = [DUMB_FIXTURE_PATH, DUMBER_FIXTURE_PATH];
mocha.loadFiles();
- expect(require.cache, 'to have keys', [
+ expect(require.cache, "to have keys", [
DUMB_FIXTURE_PATH,
- DUMBER_FIXTURE_PATH
+ DUMBER_FIXTURE_PATH,
]);
});
- it('should execute the optional callback if given', function () {
- expect(cb => {
+ it("should execute the optional callback if given", function () {
+ expect((cb) => {
mocha.loadFiles(cb);
- }, 'to call the callback');
+ }, "to call the callback");
});
});
- describe('loadFilesAsync()', function () {
- it('shoud pass esmDecorator to actual load function', async function () {
- const esmDecorator = x => `${x}?foo=bar`;
+ describe("loadFilesAsync()", function () {
+ it("shoud pass esmDecorator to actual load function", async function () {
+ const esmDecorator = (x) => `${x}?foo=bar`;
- await mocha.loadFilesAsync({esmDecorator});
+ await mocha.loadFilesAsync({ esmDecorator });
- expect(stubs.esmUtils.loadFilesAsync, 'was called once');
+ expect(stubs.esmUtils.loadFilesAsync, "was called once");
expect(
stubs.esmUtils.loadFilesAsync.firstCall.args[3],
- 'to be',
- esmDecorator
+ "to be",
+ esmDecorator,
);
});
});
- describe('unloadFiles()', function () {
- it('should delegate Mocha.unloadFile() for each item in its list of files', function () {
+ describe("unloadFiles()", function () {
+ it("should delegate Mocha.unloadFile() for each item in its list of files", function () {
mocha.files = [DUMB_FIXTURE_PATH, DUMBER_FIXTURE_PATH];
- sinon.stub(Mocha, 'unloadFile');
+ sinon.stub(Mocha, "unloadFile");
mocha.unloadFiles();
- expect(Mocha.unloadFile, 'to have a call exhaustively satisfying', [
- DUMB_FIXTURE_PATH
+ expect(Mocha.unloadFile, "to have a call exhaustively satisfying", [
+ DUMB_FIXTURE_PATH,
])
- .and('to have a call exhaustively satisfying', [DUMBER_FIXTURE_PATH])
- .and('was called twice');
+ .and("to have a call exhaustively satisfying", [DUMBER_FIXTURE_PATH])
+ .and("was called twice");
});
- it('should be chainable', function () {
- expect(mocha.unloadFiles(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.unloadFiles(), "to be", mocha);
});
});
- describe('reporter()', function () {
- describe('when a reporter exists relative to the cwd', function () {
+ describe("reporter()", function () {
+ describe("when a reporter exists relative to the cwd", function () {
beforeEach(function () {
stubs.utils.cwd.returns(
- path.resolve(__dirname, '..', '..', 'lib', 'reporters')
+ path.resolve(__dirname, "..", "..", "lib", "reporters"),
);
});
- it('should load from current working directory', function () {
+ it("should load from current working directory", function () {
expect(function () {
- mocha.reporter('./lib/reporters/spec.js');
- }, 'not to throw');
+ mocha.reporter("./lib/reporters/spec.js");
+ }, "not to throw");
});
- describe('when the reporter throws upon load', function () {
+ describe("when the reporter throws upon load", function () {
it('should throw "invalid reporter" exception', function () {
expect(
function () {
mocha.reporter(
- './test/node-unit/fixtures/wonky-reporter.fixture.js'
+ "./test/node-unit/fixtures/wonky-reporter.fixture.js",
);
},
- 'to throw',
+ "to throw",
{
- code: 'ERR_MOCHA_INVALID_REPORTER'
- }
+ code: "ERR_MOCHA_INVALID_REPORTER",
+ },
);
});
});
});
describe('when a reporter exists relative to the "mocha" module path', function () {
- it('should load from module path', function () {
+ it("should load from module path", function () {
expect(function () {
- mocha.reporter('./reporters/spec');
- }, 'not to throw');
+ mocha.reporter("./reporters/spec");
+ }, "not to throw");
});
- describe('when the reporter throws upon load', function () {
+ describe("when the reporter throws upon load", function () {
it('should throw "invalid reporter" exception', function () {
expect(
function () {
mocha.reporter(
- '../test/node-unit/fixtures/wonky-reporter.fixture.js'
+ "../test/node-unit/fixtures/wonky-reporter.fixture.js",
);
},
- 'to throw',
+ "to throw",
{
- code: 'ERR_MOCHA_INVALID_REPORTER'
- }
+ code: "ERR_MOCHA_INVALID_REPORTER",
+ },
);
});
});
});
});
- describe('unloadFiles()', function () {
- it('should reset referencesCleaned and allow for next run', function (done) {
+ describe("unloadFiles()", function () {
+ it("should reset referencesCleaned and allow for next run", function (done) {
mocha.run(function () {
mocha.unloadFiles();
mocha.run(done);
});
});
- it('should not be allowed when the current instance is already disposed', function () {
+ it("should not be allowed when the current instance is already disposed", function () {
mocha.dispose();
expect(
function () {
mocha.unloadFiles();
},
- 'to throw',
- {code: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED'}
+ "to throw",
+ { code: "ERR_MOCHA_INSTANCE_ALREADY_DISPOSED" },
);
});
});
- describe('lazyLoadFiles()', function () {
- it('should return the `Mocha` instance', function () {
- expect(mocha.lazyLoadFiles(), 'to be', mocha);
+ describe("lazyLoadFiles()", function () {
+ it("should return the `Mocha` instance", function () {
+ expect(mocha.lazyLoadFiles(), "to be", mocha);
});
- describe('when passed a non-`true` value', function () {
- it('should enable eager loading', function () {
+ describe("when passed a non-`true` value", function () {
+ it("should enable eager loading", function () {
mocha.lazyLoadFiles(0);
- expect(mocha._lazyLoadFiles, 'to be false');
+ expect(mocha._lazyLoadFiles, "to be false");
});
});
- describe('when passed `true`', function () {
- it('should enable lazy loading', function () {
+ describe("when passed `true`", function () {
+ it("should enable lazy loading", function () {
mocha.lazyLoadFiles(true);
- expect(mocha._lazyLoadFiles, 'to be true');
+ expect(mocha._lazyLoadFiles, "to be true");
});
});
});
});
- describe('static method', function () {
- describe('unloadFile()', function () {
- it('should unload a specific file from cache', function () {
+ describe("static method", function () {
+ describe("unloadFile()", function () {
+ it("should unload a specific file from cache", function () {
require(DUMB_FIXTURE_PATH);
Mocha.unloadFile(DUMB_FIXTURE_PATH);
- expect(require.cache, 'not to have key', DUMB_FIXTURE_PATH);
+ expect(require.cache, "not to have key", DUMB_FIXTURE_PATH);
});
});
});
diff --git a/test/node-unit/parallel-buffered-runner.spec.js b/test/node-unit/parallel-buffered-runner.spec.js
index 5d0a64b7..cb5f389d 100644
--- a/test/node-unit/parallel-buffered-runner.spec.js
+++ b/test/node-unit/parallel-buffered-runner.spec.js
@@ -1,21 +1,21 @@
-'use strict';
+"use strict";
const {
EVENT_RUN_BEGIN,
EVENT_TEST_PASS,
EVENT_TEST_FAIL,
EVENT_SUITE_END,
- EVENT_SUITE_BEGIN
-} = require('../../lib/runner').constants;
-const rewiremock = require('rewiremock/node');
-const Suite = require('../../lib/suite');
-const Runner = require('../../lib/runner');
-const sinon = require('sinon');
-const {constants} = require('../../lib/utils');
-const {MOCHA_ID_PROP_NAME} = constants;
-
-describe('parallel-buffered-runner', function () {
- describe('ParallelBufferedRunner', function () {
+ EVENT_SUITE_BEGIN,
+} = require("../../lib/runner").constants;
+const rewiremock = require("rewiremock/node");
+const Suite = require("../../lib/suite");
+const Runner = require("../../lib/runner");
+const sinon = require("sinon");
+const { constants } = require("../../lib/utils");
+const { MOCHA_ID_PROP_NAME } = constants;
+
+describe("parallel-buffered-runner", function () {
+ describe("ParallelBufferedRunner", function () {
let run;
let BufferedWorkerPool;
let terminate;
@@ -25,7 +25,7 @@ describe('parallel-buffered-runner', function () {
let fatalError;
beforeEach(function () {
- suite = new Suite('a root suite', {}, true);
+ suite = new Suite("a root suite", {}, true);
warn = sinon.stub();
fatalError = new Error();
@@ -37,77 +37,77 @@ describe('parallel-buffered-runner', function () {
create: sinon.stub().returns({
run,
terminate,
- stats: sinon.stub().returns({})
- })
+ stats: sinon.stub().returns({}),
+ }),
};
/**
* @type {ParallelBufferedRunner}
*/
ParallelBufferedRunner = rewiremock.proxy(
- () => require('../../lib/nodejs/parallel-buffered-runner'),
- r => ({
- '../../lib/nodejs/buffered-worker-pool': {
- BufferedWorkerPool
+ () => require("../../lib/nodejs/parallel-buffered-runner"),
+ (r) => ({
+ "../../lib/nodejs/buffered-worker-pool": {
+ BufferedWorkerPool,
},
- '../../lib/utils': r.with({warn}).callThrough(),
- '../../lib/errors': r
+ "../../lib/utils": r.with({ warn }).callThrough(),
+ "../../lib/errors": r
.with({
- createFatalError: sinon.stub().returns(fatalError)
+ createFatalError: sinon.stub().returns(fatalError),
})
- .callThrough()
- })
+ .callThrough(),
+ }),
);
});
- describe('constructor', function () {
+ describe("constructor", function () {
it('should start in "IDLE" state', function () {
expect(
new ParallelBufferedRunner(suite),
- 'to have property',
- '_state',
- 'IDLE'
+ "to have property",
+ "_state",
+ "IDLE",
);
});
});
- describe('instance property', function () {
+ describe("instance property", function () {
let runner;
beforeEach(function () {
runner = new ParallelBufferedRunner(suite);
});
- describe('_state', function () {
- it('should disallow an invalid state transition', function () {
+ describe("_state", function () {
+ it("should disallow an invalid state transition", function () {
expect(
() => {
- runner._state = 'BAILED';
+ runner._state = "BAILED";
},
- 'to throw',
- /invalid state transition/
+ "to throw",
+ /invalid state transition/,
);
});
});
});
- describe('event', function () {
+ describe("event", function () {
let runner;
beforeEach(function () {
runner = new ParallelBufferedRunner(suite);
});
- describe('EVENT_RUN_END', function () {
- it('should change the state to COMPLETE', function () {
- runner._state = 'RUNNING';
+ describe("EVENT_RUN_END", function () {
+ it("should change the state to COMPLETE", function () {
+ runner._state = "RUNNING";
runner.emit(Runner.constants.EVENT_RUN_END);
- expect(runner._state, 'to be', 'COMPLETE');
+ expect(runner._state, "to be", "COMPLETE");
});
});
});
- describe('instance method', function () {
- describe('run()', function () {
+ describe("instance method", function () {
+ describe("run()", function () {
let runner;
beforeEach(function () {
@@ -116,551 +116,551 @@ describe('parallel-buffered-runner', function () {
// the purpose of this is to ensure that--despite using `Promise`s
// internally--`BufferedRunner#run` does not return a `Promise`.
- it('should be chainable', function (done) {
- expect(runner.run(done, {files: [], options: {}}), 'to be', runner);
+ it("should be chainable", function (done) {
+ expect(runner.run(done, { files: [], options: {} }), "to be", runner);
});
- it('should emit `EVENT_RUN_BEGIN`', async function () {
+ it("should emit `EVENT_RUN_BEGIN`", async function () {
return expect(
() =>
- new Promise(resolve => {
- runner.run(resolve, {files: [], options: {}});
+ new Promise((resolve) => {
+ runner.run(resolve, { files: [], options: {} });
}),
- 'to emit from',
+ "to emit from",
runner,
- EVENT_RUN_BEGIN
+ EVENT_RUN_BEGIN,
);
});
- describe('when instructed to link objects', function () {
+ describe("when instructed to link objects", function () {
beforeEach(function () {
runner._linkPartialObjects = true;
});
- it('should create object references', function () {
- const options = {reporter: runner._workerReporter};
+ it("should create object references", function () {
+ const options = { reporter: runner._workerReporter };
const someSuite = {
- title: 'some suite',
- [MOCHA_ID_PROP_NAME]: 'bar'
+ title: "some suite",
+ [MOCHA_ID_PROP_NAME]: "bar",
};
- run.withArgs('some-file.js', options).resolves({
+ run.withArgs("some-file.js", options).resolves({
failureCount: 0,
events: [
{
eventName: EVENT_SUITE_END,
- data: someSuite
+ data: someSuite,
},
{
eventName: EVENT_TEST_PASS,
data: {
- title: 'some test',
- [MOCHA_ID_PROP_NAME]: 'foo',
+ title: "some test",
+ [MOCHA_ID_PROP_NAME]: "foo",
parent: {
// this stub object points to someSuite with id 'bar'
- [MOCHA_ID_PROP_NAME]: 'bar'
- }
- }
+ [MOCHA_ID_PROP_NAME]: "bar",
+ },
+ },
},
{
eventName: EVENT_SUITE_END,
// ensure we are not passing the _same_ someSuite,
// because we won't get the same one from the subprocess
- data: {...someSuite}
- }
- ]
+ data: { ...someSuite },
+ },
+ ],
});
return expect(
() =>
- new Promise(resolve => {
- runner.run(resolve, {files: ['some-file.js'], options: {}});
+ new Promise((resolve) => {
+ runner.run(resolve, { files: ["some-file.js"], options: {} });
}),
- 'to emit from',
+ "to emit from",
runner,
EVENT_TEST_PASS,
{
- title: 'some test',
- [MOCHA_ID_PROP_NAME]: 'foo',
+ title: "some test",
+ [MOCHA_ID_PROP_NAME]: "foo",
parent: expect
- .it('to be', someSuite)
- .and('to have property', 'title', 'some suite')
- }
+ .it("to be", someSuite)
+ .and("to have property", "title", "some suite"),
+ },
);
});
- describe('when event data object is missing an ID', function () {
- it('should result in an uncaught exception', function (done) {
- const options = {reporter: runner._workerReporter};
- sinon.spy(runner, 'uncaught');
+ describe("when event data object is missing an ID", function () {
+ it("should result in an uncaught exception", function (done) {
+ const options = { reporter: runner._workerReporter };
+ sinon.spy(runner, "uncaught");
const someSuite = {
- title: 'some suite',
- [MOCHA_ID_PROP_NAME]: 'bar'
+ title: "some suite",
+ [MOCHA_ID_PROP_NAME]: "bar",
};
- run.withArgs('some-file.js', options).resolves({
+ run.withArgs("some-file.js", options).resolves({
failureCount: 0,
events: [
{
eventName: EVENT_SUITE_END,
- data: someSuite
+ data: someSuite,
},
{
eventName: EVENT_TEST_PASS,
data: {
- title: 'some test',
+ title: "some test",
// note missing ID right here
parent: {
// this stub object points to someSuite with id 'bar'
- [MOCHA_ID_PROP_NAME]: 'bar'
- }
- }
+ [MOCHA_ID_PROP_NAME]: "bar",
+ },
+ },
},
{
eventName: EVENT_SUITE_END,
// ensure we are not passing the _same_ someSuite,
// because we won't get the same one from the subprocess
- data: {...someSuite}
- }
- ]
+ data: { ...someSuite },
+ },
+ ],
});
runner.run(
() => {
- expect(runner.uncaught, 'to have a call satisfying', [
- fatalError
+ expect(runner.uncaught, "to have a call satisfying", [
+ fatalError,
]);
done();
},
- {files: ['some-file.js'], options: {}}
+ { files: ["some-file.js"], options: {} },
);
});
});
});
- describe('when a worker fails', function () {
- it('should recover', function (done) {
- const options = {reporter: runner._workerReporter};
- run.withArgs('some-file.js', options).rejects(new Error('whoops'));
- run.withArgs('some-other-file.js', options).resolves({
+ describe("when a worker fails", function () {
+ it("should recover", function (done) {
+ const options = { reporter: runner._workerReporter };
+ run.withArgs("some-file.js", options).rejects(new Error("whoops"));
+ run.withArgs("some-other-file.js", options).resolves({
failureCount: 0,
events: [
{
eventName: EVENT_TEST_PASS,
data: {
- title: 'some test'
- }
+ title: "some test",
+ },
},
{
eventName: EVENT_SUITE_END,
data: {
- title: 'some suite'
- }
- }
- ]
+ title: "some suite",
+ },
+ },
+ ],
});
runner.run(
() => {
- expect(terminate, 'to have calls satisfying', [{args: []}]);
+ expect(terminate, "to have calls satisfying", [{ args: [] }]);
done();
},
{
- files: ['some-file.js', 'some-other-file.js'],
- options
- }
+ files: ["some-file.js", "some-other-file.js"],
+ options,
+ },
);
});
- it('should delegate to Runner#uncaught', function (done) {
- const options = {reporter: runner._workerReporter};
- sinon.spy(runner, 'uncaught');
- const err = new Error('whoops');
- run.withArgs('some-file.js', options).rejects(new Error('whoops'));
- run.withArgs('some-other-file.js', options).resolves({
+ it("should delegate to Runner#uncaught", function (done) {
+ const options = { reporter: runner._workerReporter };
+ sinon.spy(runner, "uncaught");
+ const err = new Error("whoops");
+ run.withArgs("some-file.js", options).rejects(new Error("whoops"));
+ run.withArgs("some-other-file.js", options).resolves({
failureCount: 0,
events: [
{
eventName: EVENT_TEST_PASS,
data: {
- title: 'some test'
- }
+ title: "some test",
+ },
},
{
eventName: EVENT_SUITE_END,
data: {
- title: 'some suite'
- }
- }
- ]
+ title: "some suite",
+ },
+ },
+ ],
});
runner.run(
() => {
- expect(runner.uncaught, 'to have a call satisfying', [err]);
+ expect(runner.uncaught, "to have a call satisfying", [err]);
done();
},
{
- files: ['some-file.js', 'some-other-file.js'],
- options
- }
+ files: ["some-file.js", "some-other-file.js"],
+ options,
+ },
);
});
});
- describe('when suite should bail', function () {
- describe('when no event contains an error', function () {
- it('should not force-terminate', function (done) {
+ describe("when suite should bail", function () {
+ describe("when no event contains an error", function () {
+ it("should not force-terminate", function (done) {
run.resolves({
failureCount: 0,
events: [
{
eventName: EVENT_SUITE_BEGIN,
data: {
- title: 'some suite',
- _bail: true
- }
+ title: "some suite",
+ _bail: true,
+ },
},
{
eventName: EVENT_TEST_PASS,
data: {
- title: 'some test'
- }
+ title: "some test",
+ },
},
{
eventName: EVENT_SUITE_END,
data: {
- title: 'some suite',
- _bail: true
- }
- }
- ]
+ title: "some suite",
+ _bail: true,
+ },
+ },
+ ],
});
runner.run(
() => {
- expect(terminate, 'to have a call satisfying', {
- args: []
- }).and('was called once');
+ expect(terminate, "to have a call satisfying", {
+ args: [],
+ }).and("was called once");
done();
},
{
- files: ['some-file.js', 'some-other-file.js'],
- options: {}
- }
+ files: ["some-file.js", "some-other-file.js"],
+ options: {},
+ },
);
});
});
- describe('when an event contains an error and has positive failures', function () {
- describe('when subsequent files have not yet been run', function () {
- it('should cleanly terminate the thread pool', function (done) {
- const options = {reporter: runner._workerReporter};
+ describe("when an event contains an error and has positive failures", function () {
+ describe("when subsequent files have not yet been run", function () {
+ it("should cleanly terminate the thread pool", function (done) {
+ const options = { reporter: runner._workerReporter };
const err = {
- __type: 'Error',
- message: 'oh no'
+ __type: "Error",
+ message: "oh no",
};
- run.withArgs('some-file.js', options).resolves({
+ run.withArgs("some-file.js", options).resolves({
failureCount: 1,
events: [
{
eventName: EVENT_SUITE_BEGIN,
data: {
- title: 'some suite',
- _bail: true
- }
+ title: "some suite",
+ _bail: true,
+ },
},
{
eventName: EVENT_TEST_FAIL,
data: {
- title: 'some test'
+ title: "some test",
},
- error: err
+ error: err,
},
{
eventName: EVENT_SUITE_END,
data: {
- title: 'some suite',
- _bail: true
- }
- }
- ]
+ title: "some suite",
+ _bail: true,
+ },
+ },
+ ],
});
- run.withArgs('some-other-file.js', options).rejects();
+ run.withArgs("some-other-file.js", options).rejects();
runner.run(
() => {
- expect(terminate, 'to have calls satisfying', [
- {args: []}, // this is the pool force-terminating
- {args: []} // this will always be called, and will do nothing due to the previous call
- ]).and('was called twice');
+ expect(terminate, "to have calls satisfying", [
+ { args: [] }, // this is the pool force-terminating
+ { args: [] }, // this will always be called, and will do nothing due to the previous call
+ ]).and("was called twice");
done();
},
{
- files: ['some-file.js', 'some-other-file.js'],
- options
- }
+ files: ["some-file.js", "some-other-file.js"],
+ options,
+ },
);
});
});
- describe('when subsequent files already started running', function () {
- it('should cleanly terminate the thread pool', function (done) {
- const options = {reporter: runner._workerReporter};
+ describe("when subsequent files already started running", function () {
+ it("should cleanly terminate the thread pool", function (done) {
+ const options = { reporter: runner._workerReporter };
const err = {
- __type: 'Error',
- message: 'oh no'
+ __type: "Error",
+ message: "oh no",
};
- run.withArgs('some-file.js', options).resolves({
+ run.withArgs("some-file.js", options).resolves({
failureCount: 1,
events: [
{
eventName: EVENT_SUITE_BEGIN,
data: {
- title: 'some suite',
- _bail: true
- }
+ title: "some suite",
+ _bail: true,
+ },
},
{
eventName: EVENT_TEST_FAIL,
data: {
- title: 'some test'
+ title: "some test",
},
- error: err
+ error: err,
},
{
eventName: EVENT_SUITE_END,
data: {
- title: 'some suite',
- _bail: true
- }
- }
- ]
+ title: "some suite",
+ _bail: true,
+ },
+ },
+ ],
});
- run.withArgs('some-other-file.js', options).resolves({
+ run.withArgs("some-other-file.js", options).resolves({
failureCount: 0,
events: [
{
eventName: EVENT_SUITE_BEGIN,
data: {
- title: 'some suite'
- }
+ title: "some suite",
+ },
},
{
eventName: EVENT_TEST_PASS,
data: {
- title: 'some test'
- }
+ title: "some test",
+ },
},
{
eventName: EVENT_SUITE_END,
data: {
- title: 'some suite'
- }
- }
- ]
+ title: "some suite",
+ },
+ },
+ ],
});
runner.run(
() => {
- expect(terminate, 'to have calls satisfying', [
- {args: []}, // this is the pool force-terminating
- {args: []} // this will always be called, and will do nothing due to the previous call
- ]).and('was called twice');
+ expect(terminate, "to have calls satisfying", [
+ { args: [] }, // this is the pool force-terminating
+ { args: [] }, // this will always be called, and will do nothing due to the previous call
+ ]).and("was called twice");
done();
},
{
- files: ['some-file.js', 'some-other-file.js'],
- options
- }
+ files: ["some-file.js", "some-other-file.js"],
+ options,
+ },
);
});
});
});
});
- describe('when a suite has a bail flag', function () {
- describe('when no event contains an error', function () {
- it('should not force-terminate', function (done) {
+ describe("when a suite has a bail flag", function () {
+ describe("when no event contains an error", function () {
+ it("should not force-terminate", function (done) {
run.resolves({
failureCount: 0,
events: [
{
eventName: EVENT_TEST_PASS,
data: {
- title: 'some test'
- }
+ title: "some test",
+ },
},
{
eventName: EVENT_SUITE_END,
data: {
- title: 'some suite',
- _bail: true
- }
- }
- ]
+ title: "some suite",
+ _bail: true,
+ },
+ },
+ ],
});
runner.run(
() => {
- expect(terminate, 'to have a call satisfying', {
- args: []
- }).and('was called once');
+ expect(terminate, "to have a call satisfying", {
+ args: [],
+ }).and("was called once");
done();
},
{
- files: ['some-file.js', 'some-other-file.js'],
- options: {}
- }
+ files: ["some-file.js", "some-other-file.js"],
+ options: {},
+ },
);
});
});
- describe('when an event contains an error and has positive failures', function () {
- describe('when subsequent files have not yet been run', function () {
- it('should cleanly terminate the thread pool', function (done) {
- const options = {reporter: runner._workerReporter};
+ describe("when an event contains an error and has positive failures", function () {
+ describe("when subsequent files have not yet been run", function () {
+ it("should cleanly terminate the thread pool", function (done) {
+ const options = { reporter: runner._workerReporter };
const err = {
- __type: 'Error',
- message: 'oh no'
+ __type: "Error",
+ message: "oh no",
};
- run.withArgs('some-file.js', options).resolves({
+ run.withArgs("some-file.js", options).resolves({
failureCount: 1,
events: [
{
eventName: EVENT_TEST_FAIL,
data: {
- title: 'some test'
+ title: "some test",
},
- error: err
+ error: err,
},
{
eventName: EVENT_SUITE_END,
data: {
- title: 'some suite',
- _bail: true
- }
- }
- ]
+ title: "some suite",
+ _bail: true,
+ },
+ },
+ ],
});
- run.withArgs('some-other-file.js', options).rejects();
+ run.withArgs("some-other-file.js", options).rejects();
runner.run(
() => {
- expect(terminate, 'to have calls satisfying', [
- {args: []}, // this is the pool force-terminating
- {args: []} // this will always be called, and will do nothing due to the previous call
- ]).and('was called twice');
+ expect(terminate, "to have calls satisfying", [
+ { args: [] }, // this is the pool force-terminating
+ { args: [] }, // this will always be called, and will do nothing due to the previous call
+ ]).and("was called twice");
done();
},
{
- files: ['some-file.js', 'some-other-file.js'],
- options
- }
+ files: ["some-file.js", "some-other-file.js"],
+ options,
+ },
);
});
});
- describe('when subsequent files already started running', function () {
- it('should cleanly terminate the thread pool', function (done) {
- const options = {reporter: runner._workerReporter};
+ describe("when subsequent files already started running", function () {
+ it("should cleanly terminate the thread pool", function (done) {
+ const options = { reporter: runner._workerReporter };
const err = {
- __type: 'Error',
- message: 'oh no'
+ __type: "Error",
+ message: "oh no",
};
- run.withArgs('some-file.js', options).resolves({
+ run.withArgs("some-file.js", options).resolves({
failureCount: 1,
events: [
{
eventName: EVENT_TEST_FAIL,
data: {
- title: 'some test'
+ title: "some test",
},
- error: err
+ error: err,
},
{
eventName: EVENT_SUITE_END,
data: {
- title: 'some suite',
- _bail: true
- }
- }
- ]
+ title: "some suite",
+ _bail: true,
+ },
+ },
+ ],
});
- run.withArgs('some-other-file.js', options).resolves({
+ run.withArgs("some-other-file.js", options).resolves({
failureCount: 0,
events: [
{
eventName: EVENT_TEST_PASS,
data: {
- title: 'some test'
- }
+ title: "some test",
+ },
},
{
eventName: EVENT_SUITE_END,
data: {
- title: 'some suite'
- }
- }
- ]
+ title: "some suite",
+ },
+ },
+ ],
});
runner.run(
() => {
- expect(terminate, 'to have calls satisfying', [
- {args: []}, // this is the pool force-terminating
- {args: []} // this will always be called, and will do nothing due to the previous call
- ]).and('was called twice');
+ expect(terminate, "to have calls satisfying", [
+ { args: [] }, // this is the pool force-terminating
+ { args: [] }, // this will always be called, and will do nothing due to the previous call
+ ]).and("was called twice");
done();
},
{
- files: ['some-file.js', 'some-other-file.js'],
- options
- }
+ files: ["some-file.js", "some-other-file.js"],
+ options,
+ },
);
});
});
- describe('when subsequent files have not yet been run', function () {
- it('should cleanly terminate the thread pool', function (done) {
- const options = {reporter: runner._workerReporter};
+ describe("when subsequent files have not yet been run", function () {
+ it("should cleanly terminate the thread pool", function (done) {
+ const options = { reporter: runner._workerReporter };
const err = {
- __type: 'Error',
- message: 'oh no'
+ __type: "Error",
+ message: "oh no",
};
- run.withArgs('some-file.js', options).resolves({
+ run.withArgs("some-file.js", options).resolves({
failureCount: 1,
events: [
{
eventName: EVENT_TEST_FAIL,
data: {
- title: 'some test'
+ title: "some test",
},
- error: err
+ error: err,
},
{
eventName: EVENT_SUITE_END,
data: {
- title: 'some suite',
- _bail: true
- }
- }
- ]
+ title: "some suite",
+ _bail: true,
+ },
+ },
+ ],
});
- run.withArgs('some-other-file.js', options).rejects();
+ run.withArgs("some-other-file.js", options).rejects();
runner.run(
() => {
- expect(terminate, 'to have calls satisfying', [
- {args: []}, // this is the pool force-terminating
- {args: []} // this will always be called, and will do nothing due to the previous call
- ]).and('was called twice');
+ expect(terminate, "to have calls satisfying", [
+ { args: [] }, // this is the pool force-terminating
+ { args: [] }, // this will always be called, and will do nothing due to the previous call
+ ]).and("was called twice");
done();
},
{
- files: ['some-file.js', 'some-other-file.js'],
- options
- }
+ files: ["some-file.js", "some-other-file.js"],
+ options,
+ },
);
});
});
@@ -668,41 +668,41 @@ describe('parallel-buffered-runner', function () {
});
});
- describe('linkPartialObjects()', function () {
+ describe("linkPartialObjects()", function () {
let runner;
beforeEach(function () {
runner = new ParallelBufferedRunner(suite);
});
- it('should return the runner', function () {
- expect(runner.linkPartialObjects(), 'to be', runner);
+ it("should return the runner", function () {
+ expect(runner.linkPartialObjects(), "to be", runner);
});
// avoid testing implementation details; don't check _linkPartialObjects
});
- describe('isParallelMode()', function () {
+ describe("isParallelMode()", function () {
let runner;
beforeEach(function () {
runner = new ParallelBufferedRunner(suite);
});
- it('should return true', function () {
- expect(runner.isParallelMode(), 'to be true');
+ it("should return true", function () {
+ expect(runner.isParallelMode(), "to be true");
});
});
- describe('workerReporter()', function () {
+ describe("workerReporter()", function () {
let runner;
beforeEach(function () {
runner = new ParallelBufferedRunner(suite);
});
- it('should return its context', function () {
- expect(runner.workerReporter(), 'to be', runner);
+ it("should return its context", function () {
+ expect(runner.workerReporter(), "to be", runner);
});
});
});
diff --git a/test/node-unit/reporters/parallel-buffered.spec.js b/test/node-unit/reporters/parallel-buffered.spec.js
index a3bc9751..d03c10eb 100644
--- a/test/node-unit/reporters/parallel-buffered.spec.js
+++ b/test/node-unit/reporters/parallel-buffered.spec.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
// this reporter does not actually output anything to the terminal, so we
// need to test it differently.
@@ -16,14 +16,14 @@ const {
EVENT_DELAY_END,
EVENT_HOOK_BEGIN,
EVENT_HOOK_END,
- EVENT_RUN_END
-} = require('../../../lib/runner').constants;
-const {EventEmitter} = require('node:events');
-const sinon = require('sinon');
-const rewiremock = require('rewiremock/node');
-const semver = require('semver');
+ EVENT_RUN_END,
+} = require("../../../lib/runner").constants;
+const { EventEmitter } = require("node:events");
+const sinon = require("sinon");
+const rewiremock = require("rewiremock/node");
+const semver = require("semver");
-describe('ParallelBuffered', function () {
+describe("ParallelBuffered", function () {
/** @type {EventEmitter} */
let runner;
let ParallelBuffered;
@@ -31,27 +31,27 @@ describe('ParallelBuffered', function () {
beforeEach(function () {
runner = new EventEmitter();
ParallelBuffered = rewiremock.proxy(
- () => require('../../../lib/nodejs/reporters/parallel-buffered'),
+ () => require("../../../lib/nodejs/reporters/parallel-buffered"),
{
- '../../../lib/nodejs/serializer': {
+ "../../../lib/nodejs/serializer": {
SerializableEvent: {
create: (eventName, runnable, err) => ({
eventName,
data: runnable,
error: err,
- __type: 'MockSerializableEvent'
- })
+ __type: "MockSerializableEvent",
+ }),
},
SerializableWorkerResult: {
create: (events, failures) => ({
events,
failures,
- __type: 'MockSerializableWorkerResult'
- })
- }
+ __type: "MockSerializableWorkerResult",
+ }),
+ },
},
- '../../../lib/reporters/base': class MockBase {}
- }
+ "../../../lib/reporters/base": class MockBase {},
+ },
);
});
@@ -59,50 +59,50 @@ describe('ParallelBuffered', function () {
sinon.restore();
});
- describe('constructor', function () {
- it('should listen for Runner events', function () {
+ describe("constructor", function () {
+ it("should listen for Runner events", function () {
// EventEmitter#once calls thru to EventEmitter#on, which
// befouls our assertion below.
- sinon.stub(runner, 'once');
- sinon.stub(runner, 'on');
+ sinon.stub(runner, "once");
+ sinon.stub(runner, "on");
// eslint-disable-next-line no-new
new ParallelBuffered(runner);
- expect(runner.on, 'to have calls satisfying', [
+ expect(runner.on, "to have calls satisfying", [
// via Buffered
- [EVENT_SUITE_BEGIN, expect.it('to be a function')],
- [EVENT_SUITE_END, expect.it('to be a function')],
- [EVENT_TEST_BEGIN, expect.it('to be a function')],
- [EVENT_TEST_PENDING, expect.it('to be a function')],
- [EVENT_TEST_FAIL, expect.it('to be a function')],
- [EVENT_TEST_PASS, expect.it('to be a function')],
- [EVENT_TEST_RETRY, expect.it('to be a function')],
- [EVENT_TEST_END, expect.it('to be a function')],
- [EVENT_HOOK_BEGIN, expect.it('to be a function')],
- [EVENT_HOOK_END, expect.it('to be a function')]
+ [EVENT_SUITE_BEGIN, expect.it("to be a function")],
+ [EVENT_SUITE_END, expect.it("to be a function")],
+ [EVENT_TEST_BEGIN, expect.it("to be a function")],
+ [EVENT_TEST_PENDING, expect.it("to be a function")],
+ [EVENT_TEST_FAIL, expect.it("to be a function")],
+ [EVENT_TEST_PASS, expect.it("to be a function")],
+ [EVENT_TEST_RETRY, expect.it("to be a function")],
+ [EVENT_TEST_END, expect.it("to be a function")],
+ [EVENT_HOOK_BEGIN, expect.it("to be a function")],
+ [EVENT_HOOK_END, expect.it("to be a function")],
]);
});
- it('should listen for Runner events expecting to occur once', function () {
- sinon.stub(runner, 'once');
+ it("should listen for Runner events expecting to occur once", function () {
+ sinon.stub(runner, "once");
// eslint-disable-next-line no-new
new ParallelBuffered(runner);
- expect(runner.once, 'to have calls satisfying', [
- [EVENT_DELAY_BEGIN, expect.it('to be a function')],
- [EVENT_DELAY_END, expect.it('to be a function')],
- [EVENT_RUN_END, expect.it('to be a function')]
+ expect(runner.once, "to have calls satisfying", [
+ [EVENT_DELAY_BEGIN, expect.it("to be a function")],
+ [EVENT_DELAY_END, expect.it("to be a function")],
+ [EVENT_RUN_END, expect.it("to be a function")],
]);
});
});
- describe('event', function () {
+ describe("event", function () {
let reporter;
beforeEach(function () {
reporter = new ParallelBuffered(runner);
});
- describe('on EVENT_RUN_END', function () {
- it('should remove all listeners', function () {
+ describe("on EVENT_RUN_END", function () {
+ it("should remove all listeners", function () {
runner.emit(EVENT_RUN_END);
// Some node versions throw instead of returning `[]` due to a bug
// Fix is in Node ^22.14 and ^24.0, but not yet backported to 20 as of writing
@@ -110,74 +110,74 @@ describe('ParallelBuffered', function () {
// https://github.com/nodejs/node/issues/56263
const nodeVersionThrows = semver.satisfies(
process.versions.node,
- '^20.19.0 || >=22.0.0 <22.14.0'
+ "^20.19.0 || >=22.0.0 <22.14.0",
);
if (nodeVersionThrows) {
- expect(runner.listeners, 'to throw');
+ expect(runner.listeners, "to throw");
} else {
- expect(runner.listeners(), 'to be empty');
+ expect(runner.listeners(), "to be empty");
}
});
});
- describe('on any other event listened for', function () {
- it('should populate its `events` array with SerializableEvents', function () {
+ describe("on any other event listened for", function () {
+ it("should populate its `events` array with SerializableEvents", function () {
const suite = {
- title: 'some suite'
+ title: "some suite",
};
const test = {
- title: 'some test'
+ title: "some test",
};
runner.emit(EVENT_SUITE_BEGIN, suite);
runner.emit(EVENT_TEST_BEGIN, test);
runner.emit(EVENT_TEST_PASS, test);
runner.emit(EVENT_TEST_END, test);
runner.emit(EVENT_SUITE_END, suite);
- expect(reporter.events, 'to equal', [
+ expect(reporter.events, "to equal", [
{
eventName: EVENT_SUITE_BEGIN,
data: suite,
- __type: 'MockSerializableEvent'
+ __type: "MockSerializableEvent",
},
{
eventName: EVENT_TEST_BEGIN,
data: test,
- __type: 'MockSerializableEvent'
+ __type: "MockSerializableEvent",
},
{
eventName: EVENT_TEST_PASS,
data: test,
- __type: 'MockSerializableEvent'
+ __type: "MockSerializableEvent",
},
{
eventName: EVENT_TEST_END,
data: test,
- __type: 'MockSerializableEvent'
+ __type: "MockSerializableEvent",
},
{
eventName: EVENT_SUITE_END,
data: suite,
- __type: 'MockSerializableEvent'
- }
+ __type: "MockSerializableEvent",
+ },
]);
});
});
});
- describe('instance method', function () {
+ describe("instance method", function () {
let reporter;
beforeEach(function () {
reporter = new ParallelBuffered(runner);
});
- describe('done', function () {
- it('should execute its callback with a SerializableWorkerResult', function () {
+ describe("done", function () {
+ it("should execute its callback with a SerializableWorkerResult", function () {
const suite = {
- title: 'some suite'
+ title: "some suite",
};
const test = {
- title: 'some test'
+ title: "some test",
};
runner.emit(EVENT_SUITE_BEGIN, suite);
runner.emit(EVENT_TEST_BEGIN, test);
@@ -186,47 +186,47 @@ describe('ParallelBuffered', function () {
runner.emit(EVENT_SUITE_END, suite);
const cb = sinon.stub();
reporter.done(0, cb);
- expect(cb, 'to have a call satisfying', [
+ expect(cb, "to have a call satisfying", [
{
events: [
{
eventName: EVENT_SUITE_BEGIN,
data: suite,
- __type: 'MockSerializableEvent'
+ __type: "MockSerializableEvent",
},
{
eventName: EVENT_TEST_BEGIN,
data: test,
- __type: 'MockSerializableEvent'
+ __type: "MockSerializableEvent",
},
{
eventName: EVENT_TEST_PASS,
data: test,
- __type: 'MockSerializableEvent'
+ __type: "MockSerializableEvent",
},
{
eventName: EVENT_TEST_END,
data: test,
- __type: 'MockSerializableEvent'
+ __type: "MockSerializableEvent",
},
{
eventName: EVENT_SUITE_END,
data: suite,
- __type: 'MockSerializableEvent'
- }
+ __type: "MockSerializableEvent",
+ },
],
failures: 0,
- __type: 'MockSerializableWorkerResult'
- }
+ __type: "MockSerializableWorkerResult",
+ },
]);
});
- it('should reset its `events` prop', function () {
+ it("should reset its `events` prop", function () {
const suite = {
- title: 'some suite'
+ title: "some suite",
};
const test = {
- title: 'some test'
+ title: "some test",
};
runner.emit(EVENT_SUITE_BEGIN, suite);
runner.emit(EVENT_TEST_BEGIN, test);
@@ -235,7 +235,7 @@ describe('ParallelBuffered', function () {
runner.emit(EVENT_SUITE_END, suite);
const cb = sinon.stub();
reporter.done(0, cb);
- expect(reporter.events, 'to be empty');
+ expect(reporter.events, "to be empty");
});
});
});
diff --git a/test/node-unit/serializer.spec.js b/test/node-unit/serializer.spec.js
index cd43a170..0ad13ee7 100644
--- a/test/node-unit/serializer.spec.js
+++ b/test/node-unit/serializer.spec.js
@@ -1,321 +1,321 @@
-'use strict';
+"use strict";
-const sinon = require('sinon');
+const sinon = require("sinon");
const {
serialize,
deserialize,
SerializableEvent,
- SerializableWorkerResult
-} = require('../../lib/nodejs/serializer');
+ SerializableWorkerResult,
+} = require("../../lib/nodejs/serializer");
-describe('serializer', function () {
+describe("serializer", function () {
afterEach(function () {
sinon.restore();
});
- describe('function', function () {
- describe('serialize', function () {
- describe('when passed a non-object value', function () {
- it('should return the value', function () {
- expect(serialize('knees & toes'), 'to be', 'knees & toes');
+ describe("function", function () {
+ describe("serialize", function () {
+ describe("when passed a non-object value", function () {
+ it("should return the value", function () {
+ expect(serialize("knees & toes"), "to be", "knees & toes");
});
});
- describe('when passed an object value', function () {
- describe('w/o a `serialize` method', function () {
- it('should return the value', function () {
+ describe("when passed an object value", function () {
+ describe("w/o a `serialize` method", function () {
+ it("should return the value", function () {
const obj = {};
- expect(serialize(obj), 'to be', obj);
+ expect(serialize(obj), "to be", obj);
});
});
- describe('having a `serialize` method', function () {
- it('should return the result of the `serialize` method', function () {
- const serializedObj = {foo: 'bar'};
- const obj = {serialize: sinon.stub().returns(serializedObj)};
- expect(serialize(obj), 'to be', serializedObj);
+ describe("having a `serialize` method", function () {
+ it("should return the result of the `serialize` method", function () {
+ const serializedObj = { foo: "bar" };
+ const obj = { serialize: sinon.stub().returns(serializedObj) };
+ expect(serialize(obj), "to be", serializedObj);
});
});
});
- describe('when not passed anything', function () {
- it('should return `undefined`', function () {
- expect(serialize(), 'to be undefined');
+ describe("when not passed anything", function () {
+ it("should return `undefined`", function () {
+ expect(serialize(), "to be undefined");
});
});
});
- describe('deserialize', function () {
- describe('when passed nothing', function () {
- it('should return `undefined`', function () {
- expect(deserialize(), 'to be undefined');
+ describe("deserialize", function () {
+ describe("when passed nothing", function () {
+ it("should return `undefined`", function () {
+ expect(deserialize(), "to be undefined");
});
});
- describe('when passed a non-object value', function () {
- it('should return the value', function () {
- expect(deserialize(500), 'to be', 500);
+ describe("when passed a non-object value", function () {
+ it("should return the value", function () {
+ expect(deserialize(500), "to be", 500);
});
});
- describe('when passed an object value which is not a SerializedWorkerResult', function () {
- it('should return the value', function () {
+ describe("when passed an object value which is not a SerializedWorkerResult", function () {
+ it("should return the value", function () {
const obj = {};
- expect(deserialize(obj), 'to be', obj);
+ expect(deserialize(obj), "to be", obj);
});
});
- describe('when passed a SerializedWorkerResult object', function () {
+ describe("when passed a SerializedWorkerResult object", function () {
// note that SerializedWorkerResult is an interface (typedef), not a class.
- it('should return the result of `SerializableWorkerResult.deserialize` called on the value', function () {
+ it("should return the result of `SerializableWorkerResult.deserialize` called on the value", function () {
const obj = Object.assign({}, SerializableWorkerResult.create());
- sinon.stub(SerializableWorkerResult, 'deserialize').returns('butts');
+ sinon.stub(SerializableWorkerResult, "deserialize").returns("butts");
deserialize(obj);
expect(
SerializableWorkerResult.deserialize,
- 'to have a call satisfying',
+ "to have a call satisfying",
{
args: [obj],
- returned: 'butts'
- }
+ returned: "butts",
+ },
);
});
});
});
});
- describe('SerializableEvent', function () {
- describe('constructor', function () {
- describe('when called without `eventName`', function () {
+ describe("SerializableEvent", function () {
+ describe("constructor", function () {
+ describe("when called without `eventName`", function () {
it('should throw "invalid arg value" error', function () {
- expect(() => new SerializableEvent(), 'to throw', {
- code: 'ERR_MOCHA_INVALID_ARG_TYPE'
+ expect(() => new SerializableEvent(), "to throw", {
+ code: "ERR_MOCHA_INVALID_ARG_TYPE",
});
});
});
- describe('when called with a non-object `rawObject`', function () {
+ describe("when called with a non-object `rawObject`", function () {
it('should throw "invalid arg type" error', function () {
- expect(() => new SerializableEvent('blub', 'glug'), 'to throw', {
- code: 'ERR_MOCHA_INVALID_ARG_TYPE'
+ expect(() => new SerializableEvent("blub", "glug"), "to throw", {
+ code: "ERR_MOCHA_INVALID_ARG_TYPE",
});
});
});
});
- describe('instance method', function () {
- describe('serialize', function () {
- it('should mutate the instance in-place', function () {
- const evt = SerializableEvent.create('foo');
- expect(evt.serialize(), 'to be', evt);
+ describe("instance method", function () {
+ describe("serialize", function () {
+ it("should mutate the instance in-place", function () {
+ const evt = SerializableEvent.create("foo");
+ expect(evt.serialize(), "to be", evt);
});
- it('should freeze the instance', function () {
+ it("should freeze the instance", function () {
expect(
- Object.isFrozen(SerializableEvent.create('foo').serialize()),
- 'to be true'
+ Object.isFrozen(SerializableEvent.create("foo").serialize()),
+ "to be true",
);
});
- describe('when passed an object with a `serialize` method', function () {
- it('should call the `serialize` method', function () {
+ describe("when passed an object with a `serialize` method", function () {
+ it("should call the `serialize` method", function () {
const obj = {
- serialize: sinon.stub()
+ serialize: sinon.stub(),
};
- SerializableEvent.create('some-event', obj).serialize();
- expect(obj.serialize, 'was called once');
+ SerializableEvent.create("some-event", obj).serialize();
+ expect(obj.serialize, "was called once");
});
});
- describe('when passed an object containing an object with a `serialize` method', function () {
- it('should call the `serialize` method', function () {
+ describe("when passed an object containing an object with a `serialize` method", function () {
+ it("should call the `serialize` method", function () {
const stub = sinon.stub();
const obj = {
nested: {
- serialize: stub
- }
+ serialize: stub,
+ },
};
- SerializableEvent.create('some-event', obj).serialize();
- expect(stub, 'was called once');
+ SerializableEvent.create("some-event", obj).serialize();
+ expect(stub, "was called once");
});
});
- describe('when passed an object containing a non-`serialize` method', function () {
- it('should remove the method', function () {
+ describe("when passed an object containing a non-`serialize` method", function () {
+ it("should remove the method", function () {
const obj = {
- func: () => {}
+ func: () => {},
};
expect(
- SerializableEvent.create('some-event', obj).serialize(),
- 'to satisfy',
+ SerializableEvent.create("some-event", obj).serialize(),
+ "to satisfy",
{
- data: expect.it('not to have property', 'func')
- }
+ data: expect.it("not to have property", "func"),
+ },
);
});
});
- describe('when passed an object containing an array', function () {
- it('should serialize the array', function () {
+ describe("when passed an object containing an array", function () {
+ it("should serialize the array", function () {
const obj = {
- list: [{herp: 'derp'}, {bing: 'bong'}]
+ list: [{ herp: "derp" }, { bing: "bong" }],
};
expect(
- SerializableEvent.create('some-event', obj).serialize(),
- 'to satisfy',
- {data: {list: [{herp: 'derp'}, {bing: 'bong'}]}}
+ SerializableEvent.create("some-event", obj).serialize(),
+ "to satisfy",
+ { data: { list: [{ herp: "derp" }, { bing: "bong" }] } },
);
});
});
- describe('when passed an error', function () {
- it('should serialize the error', function () {
+ describe("when passed an error", function () {
+ it("should serialize the error", function () {
const obj = {};
- const err = new Error('monkeypants');
+ const err = new Error("monkeypants");
expect(
- SerializableEvent.create('some-event', obj, err).serialize(),
- 'to satisfy',
+ SerializableEvent.create("some-event", obj, err).serialize(),
+ "to satisfy",
{
- eventName: 'some-event',
+ eventName: "some-event",
error: {
- message: 'monkeypants',
+ message: "monkeypants",
stack: /^Error: monkeypants/,
- __type: 'Error'
+ __type: "Error",
},
- data: obj
- }
+ data: obj,
+ },
);
});
- it('should retain own props', function () {
+ it("should retain own props", function () {
const obj = {};
- const err = new Error('monkeypants');
- err.code = 'MONKEY';
+ const err = new Error("monkeypants");
+ err.code = "MONKEY";
expect(
- SerializableEvent.create('some-event', obj, err).serialize(),
- 'to satisfy',
+ SerializableEvent.create("some-event", obj, err).serialize(),
+ "to satisfy",
{
- eventName: 'some-event',
+ eventName: "some-event",
error: {
- code: 'MONKEY',
- message: 'monkeypants',
+ code: "MONKEY",
+ message: "monkeypants",
stack: /^Error: monkeypants/,
- __type: 'Error'
+ __type: "Error",
},
- data: obj
- }
+ data: obj,
+ },
);
});
- it('should not retain not-own props', function () {
+ it("should not retain not-own props", function () {
const obj = {};
- const err = new Error('monkeypants');
+ const err = new Error("monkeypants");
// eslint-disable-next-line no-proto
- err.__proto__.code = 'MONKEY';
+ err.__proto__.code = "MONKEY";
expect(
- SerializableEvent.create('some-event', obj, err).serialize(),
- 'to satisfy',
+ SerializableEvent.create("some-event", obj, err).serialize(),
+ "to satisfy",
{
- eventName: 'some-event',
+ eventName: "some-event",
error: {
- message: 'monkeypants',
+ message: "monkeypants",
stack: /^Error: monkeypants/,
- __type: 'Error'
+ __type: "Error",
},
- data: obj
- }
+ data: obj,
+ },
);
});
});
- describe('when passed an object containing a top-level prop with an Error value', function () {
- it('should serialize the Error', function () {
+ describe("when passed an object containing a top-level prop with an Error value", function () {
+ it("should serialize the Error", function () {
const obj = {
- monkeyError: new Error('pantsmonkey')
+ monkeyError: new Error("pantsmonkey"),
};
- const evt = SerializableEvent.create('some-event', obj);
- expect(evt.serialize(), 'to satisfy', {
- eventName: 'some-event',
+ const evt = SerializableEvent.create("some-event", obj);
+ expect(evt.serialize(), "to satisfy", {
+ eventName: "some-event",
data: {
monkeyError: {
- message: 'pantsmonkey',
+ message: "pantsmonkey",
stack: /^Error: pantsmonkey/,
- __type: 'Error'
- }
- }
+ __type: "Error",
+ },
+ },
});
});
});
- describe('when passed an object containing a nested prop with an Error value', function () {
- it('should serialize the Error', function () {
+ describe("when passed an object containing a nested prop with an Error value", function () {
+ it("should serialize the Error", function () {
const obj = {
nestedObj: {
- monkeyError: new Error('pantsmonkey')
- }
+ monkeyError: new Error("pantsmonkey"),
+ },
};
- const evt = SerializableEvent.create('some-event', obj);
- expect(evt.serialize(), 'to satisfy', {
- eventName: 'some-event',
+ const evt = SerializableEvent.create("some-event", obj);
+ expect(evt.serialize(), "to satisfy", {
+ eventName: "some-event",
data: {
nestedObj: {
monkeyError: {
- message: 'pantsmonkey',
+ message: "pantsmonkey",
stack: /^Error: pantsmonkey/,
- __type: 'Error'
- }
- }
- }
+ __type: "Error",
+ },
+ },
+ },
});
});
});
});
});
- describe('static method', function () {
- describe('deserialize', function () {
- describe('when passed a falsy parameter', function () {
+ describe("static method", function () {
+ describe("deserialize", function () {
+ describe("when passed a falsy parameter", function () {
it('should throw "invalid arg type" error', function () {
- expect(SerializableEvent.deserialize, 'to throw', {
- code: 'ERR_MOCHA_INVALID_ARG_TYPE'
+ expect(SerializableEvent.deserialize, "to throw", {
+ code: "ERR_MOCHA_INVALID_ARG_TYPE",
});
});
});
- it('should return a new object w/ null prototype', function () {
- const obj = {bob: 'bob'};
- expect(SerializableEvent.deserialize(obj), 'to satisfy', obj)
- .and('not to equal', obj)
- .and('not to have property', 'constructor');
+ it("should return a new object w/ null prototype", function () {
+ const obj = { bob: "bob" };
+ expect(SerializableEvent.deserialize(obj), "to satisfy", obj)
+ .and("not to equal", obj)
+ .and("not to have property", "constructor");
});
- describe('when passed value contains `data` prop', function () {
- it('should ignore __proto__', function () {
+ describe("when passed value contains `data` prop", function () {
+ it("should ignore __proto__", function () {
const obj = {
- data: Object.create(null)
+ data: Object.create(null),
};
// eslint-disable-next-line no-proto
- obj.data.__proto__ = {peaches: 'prunes'};
+ obj.data.__proto__ = { peaches: "prunes" };
const expected = Object.assign(Object.create(null), {
- data: Object.create(null)
+ data: Object.create(null),
});
- expect(SerializableEvent.deserialize(obj), 'to equal', expected);
+ expect(SerializableEvent.deserialize(obj), "to equal", expected);
});
- describe('when `data` prop contains a nested serialized Error prop', function () {
- it('should create an Error instance from the nested serialized Error prop', function () {
- const message = 'problems!';
- const stack = 'problem instructions';
- const code = 'EIEIO';
+ describe("when `data` prop contains a nested serialized Error prop", function () {
+ it("should create an Error instance from the nested serialized Error prop", function () {
+ const message = "problems!";
+ const stack = "problem instructions";
+ const code = "EIEIO";
const expected = Object.assign(Object.create(null), {
data: {
whoops: Object.assign(new Error(message), {
stack,
- code
- })
- }
+ code,
+ }),
+ },
});
expect(
@@ -325,27 +325,27 @@ describe('serializer', function () {
message,
stack,
code,
- __type: 'Error'
- }
- }
+ __type: "Error",
+ },
+ },
}),
- 'to equal',
- expected
+ "to equal",
+ expected,
);
});
});
});
- describe('when passed value contains an `error` prop', function () {
- it('should create an Error instance from the prop', function () {
- const message = 'problems!';
- const stack = 'problem instructions';
- const code = 'EIEIO';
+ describe("when passed value contains an `error` prop", function () {
+ it("should create an Error instance from the prop", function () {
+ const message = "problems!";
+ const stack = "problem instructions";
+ const code = "EIEIO";
const expected = Object.assign(Object.create(null), {
error: Object.assign(new Error(message), {
stack,
- code
- })
+ code,
+ }),
});
expect(
@@ -354,11 +354,11 @@ describe('serializer', function () {
message,
stack,
code,
- __type: 'Error'
- }
+ __type: "Error",
+ },
}),
- 'to equal',
- expected
+ "to equal",
+ expected,
);
});
});
@@ -367,175 +367,175 @@ describe('serializer', function () {
let result;
beforeEach(function () {
- result = SerializableEvent.deserialize({data: {$$foo: 'bar'}});
+ result = SerializableEvent.deserialize({ data: { $$foo: "bar" } });
});
- it('should create a new prop having a function value', function () {
- expect(result, 'to satisfy', {
+ it("should create a new prop having a function value", function () {
+ expect(result, "to satisfy", {
data: {
- foo: expect.it('to be a function')
- }
+ foo: expect.it("to be a function"),
+ },
});
});
- it('should create a new prop returning the original value', function () {
- expect(result.data.foo(), 'to equal', 'bar');
+ it("should create a new prop returning the original value", function () {
+ expect(result.data.foo(), "to equal", "bar");
});
it('should remove the prop with the "$$" prefix', function () {
- expect(result, 'not to have property', '$$foo');
+ expect(result, "not to have property", "$$foo");
});
});
- describe('when the value data contains a prop with an array value', function () {
+ describe("when the value data contains a prop with an array value", function () {
beforeEach(function () {
- sinon.spy(SerializableEvent, '_deserializeObject');
+ sinon.spy(SerializableEvent, "_deserializeObject");
});
- it('should deserialize each prop', function () {
- const obj = {data: {foo: [{bar: 'baz'}]}};
+ it("should deserialize each prop", function () {
+ const obj = { data: { foo: [{ bar: "baz" }] } };
SerializableEvent.deserialize(obj);
expect(
SerializableEvent._deserializeObject,
- 'to have a call satisfying',
+ "to have a call satisfying",
{
- args: [obj.data.foo, 0]
- }
+ args: [obj.data.foo, 0],
+ },
);
});
});
});
- describe('create', function () {
- it('should instantiate a SerializableEvent', function () {
+ describe("create", function () {
+ it("should instantiate a SerializableEvent", function () {
expect(
- SerializableEvent.create('some-event'),
- 'to be a',
- SerializableEvent
+ SerializableEvent.create("some-event"),
+ "to be a",
+ SerializableEvent,
);
});
});
});
});
- describe('SerializableWorkerResult', function () {
- describe('static method', function () {
- describe('create', function () {
- it('should return a new SerializableWorkerResult instance', function () {
+ describe("SerializableWorkerResult", function () {
+ describe("static method", function () {
+ describe("create", function () {
+ it("should return a new SerializableWorkerResult instance", function () {
expect(
SerializableWorkerResult.create(),
- 'to be a',
- SerializableWorkerResult
+ "to be a",
+ SerializableWorkerResult,
);
});
});
- describe('isSerializedWorkerResult', function () {
- describe('when passed an instance', function () {
- it('should return `true`', function () {
+ describe("isSerializedWorkerResult", function () {
+ describe("when passed an instance", function () {
+ it("should return `true`", function () {
expect(
SerializableWorkerResult.isSerializedWorkerResult(
- new SerializableWorkerResult()
+ new SerializableWorkerResult(),
),
- 'to be true'
+ "to be true",
);
});
});
- describe('when passed an object with an appropriate `__type` prop', function () {
- it('should return `true`', function () {
+ describe("when passed an object with an appropriate `__type` prop", function () {
+ it("should return `true`", function () {
// this is the most likely use-case, as the object is transmitted over IPC
// and loses its prototype
const original = new SerializableWorkerResult();
const clone = Object.assign({}, original);
expect(
SerializableWorkerResult.isSerializedWorkerResult(clone),
- 'to be true'
+ "to be true",
);
});
});
- describe('when passed an object without an appropriate `__type` prop', function () {
- it('should return `false`', function () {
+ describe("when passed an object without an appropriate `__type` prop", function () {
+ it("should return `false`", function () {
expect(
SerializableWorkerResult.isSerializedWorkerResult({
- mister: 'mister'
+ mister: "mister",
}),
- 'to be false'
+ "to be false",
);
});
});
});
- describe('deserialize', function () {
+ describe("deserialize", function () {
beforeEach(function () {
- sinon.stub(SerializableEvent, 'deserialize');
+ sinon.stub(SerializableEvent, "deserialize");
});
- it('should call SerializableEvent#deserialize on each item in its `events` prop', function () {
+ it("should call SerializableEvent#deserialize on each item in its `events` prop", function () {
const result = Object.assign(
{},
SerializableWorkerResult.create([
- {eventName: 'foo'},
- {eventName: 'bar'}
- ])
+ { eventName: "foo" },
+ { eventName: "bar" },
+ ]),
);
SerializableWorkerResult.deserialize(result);
- expect(SerializableEvent.deserialize, 'to have calls satisfying', [
- {args: [{eventName: 'foo'}]},
- {args: [{eventName: 'bar'}]}
+ expect(SerializableEvent.deserialize, "to have calls satisfying", [
+ { args: [{ eventName: "foo" }] },
+ { args: [{ eventName: "bar" }] },
]);
});
- it('should return the deserialized value', function () {
+ it("should return the deserialized value", function () {
const result = Object.assign(
{},
SerializableWorkerResult.create([
- {eventName: 'foo'},
- {eventName: 'bar'}
- ])
+ { eventName: "foo" },
+ { eventName: "bar" },
+ ]),
);
expect(
SerializableWorkerResult.deserialize(result),
- 'to equal',
- result
+ "to equal",
+ result,
);
});
});
});
- describe('instance method', function () {
- describe('serialize', function () {
- it('should return a read-only value', function () {
+ describe("instance method", function () {
+ describe("serialize", function () {
+ it("should return a read-only value", function () {
expect(
Object.isFrozen(SerializableWorkerResult.create().serialize()),
- 'to be true'
+ "to be true",
);
});
- it('should call `SerializableEvent#serialize` of each of its events', function () {
- sinon.spy(SerializableEvent.prototype, 'serialize');
+ it("should call `SerializableEvent#serialize` of each of its events", function () {
+ sinon.spy(SerializableEvent.prototype, "serialize");
const events = [
- SerializableEvent.create('foo'),
- SerializableEvent.create('bar')
+ SerializableEvent.create("foo"),
+ SerializableEvent.create("bar"),
];
SerializableWorkerResult.create(events).serialize();
expect(
SerializableEvent.prototype.serialize,
- 'to have calls satisfying',
- [{thisValue: events[0]}, {thisValue: events[1]}]
+ "to have calls satisfying",
+ [{ thisValue: events[0] }, { thisValue: events[1] }],
);
});
});
});
- describe('constructor', function () {
+ describe("constructor", function () {
// the following two tests should be combined into one, but not sure how to express
// as a single assertion
- it('should add a readonly `__type` prop', function () {
+ it("should add a readonly `__type` prop", function () {
expect(
new SerializableWorkerResult(),
- 'to have readonly property',
- '__type'
+ "to have readonly property",
+ "__type",
);
});
});
diff --git a/test/node-unit/stack-trace-filter.spec.js b/test/node-unit/stack-trace-filter.spec.js
index a139c701..c9e98b54 100644
--- a/test/node-unit/stack-trace-filter.spec.js
+++ b/test/node-unit/stack-trace-filter.spec.js
@@ -1,150 +1,150 @@
-'use strict';
+"use strict";
-var path = require('node:path');
-var utils = require('../../lib/utils');
+var path = require("node:path");
+var utils = require("../../lib/utils");
-describe('stackTraceFilter()', function () {
- describe('on node', function () {
+describe("stackTraceFilter()", function () {
+ describe("on node", function () {
var filter = utils.stackTraceFilter();
- describe('on POSIX OS', function () {
+ describe("on POSIX OS", function () {
before(function () {
- if (path.sep !== '/') {
+ if (path.sep !== "/") {
this.skip();
}
});
- it('should get a stack-trace as a string and prettify it', function () {
+ it("should get a stack-trace as a string and prettify it", function () {
var stack = [
- 'AssertionError: foo bar',
- 'at EventEmitter.<anonymous> (/usr/local/dev/test.js:16:12)',
- 'at Context.<anonymous> (/usr/local/dev/test.js:19:5)',
- 'Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:244:7)',
- 'Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:374:10)',
- '/usr/local/lib/node_modules/mocha/lib/runner.js:452:12',
- 'next (/usr/local/lib/node_modules/mocha/lib/runner.js:299:14)',
- '/usr/local/lib/node_modules/mocha/lib/runner.js:309:7',
- 'next (/usr/local/lib/node_modules/mocha/lib/runner.js:248:23)',
- 'Immediate._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:276:5)',
- 'at processImmediate [as _immediateCallback] (timers.js:321:17)'
+ "AssertionError: foo bar",
+ "at EventEmitter.<anonymous> (/usr/local/dev/test.js:16:12)",
+ "at Context.<anonymous> (/usr/local/dev/test.js:19:5)",
+ "Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:244:7)",
+ "Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:374:10)",
+ "/usr/local/lib/node_modules/mocha/lib/runner.js:452:12",
+ "next (/usr/local/lib/node_modules/mocha/lib/runner.js:299:14)",
+ "/usr/local/lib/node_modules/mocha/lib/runner.js:309:7",
+ "next (/usr/local/lib/node_modules/mocha/lib/runner.js:248:23)",
+ "Immediate._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:276:5)",
+ "at processImmediate [as _immediateCallback] (timers.js:321:17)",
];
- expect(filter(stack.join('\n')), 'to be', stack.slice(0, 3).join('\n'));
+ expect(filter(stack.join("\n")), "to be", stack.slice(0, 3).join("\n"));
stack = [
- 'AssertionError: bar baz',
- 'at /usr/local/dev/some-test-file.js:25:8',
- 'at tryCatcher (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/util.js:24:31)',
- 'at Promise._resolveFromResolver (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:439:31)',
- 'at new Promise (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:53:37)',
- 'at yourFunction (/usr/local/dev/own/tmp/test1.js:24:13)',
- 'at Context.<anonymous> (/usr/local/dev/some-test-file:30:4)',
- 'Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:218:15)',
- 'next (/usr/local/lib/node_modules/mocha/lib/runner.js:248:23)',
- 'Immediate._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:276:5)',
- 'at processImmediate [as _immediateCallback] (timers.js:321:17)'
+ "AssertionError: bar baz",
+ "at /usr/local/dev/some-test-file.js:25:8",
+ "at tryCatcher (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/util.js:24:31)",
+ "at Promise._resolveFromResolver (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:439:31)",
+ "at new Promise (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:53:37)",
+ "at yourFunction (/usr/local/dev/own/tmp/test1.js:24:13)",
+ "at Context.<anonymous> (/usr/local/dev/some-test-file:30:4)",
+ "Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:218:15)",
+ "next (/usr/local/lib/node_modules/mocha/lib/runner.js:248:23)",
+ "Immediate._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:276:5)",
+ "at processImmediate [as _immediateCallback] (timers.js:321:17)",
];
- expect(filter(stack.join('\n')), 'to be', stack.slice(0, 7).join('\n'));
+ expect(filter(stack.join("\n")), "to be", stack.slice(0, 7).join("\n"));
});
- it('does not ignore other bower_components and components', function () {
+ it("does not ignore other bower_components and components", function () {
var stack = [
- 'Error: failed',
- 'at assert (index.html:11:26)',
- 'at Context.<anonymous> (test.js:17:18)',
- 'at bower_components/should/should.js:4827:7',
- 'at next (file:///.../bower_components/should/should.js:4766:23)',
- 'at components/should/5.0.0/should.js:4827:7',
- 'at next (file:///.../components/should/5.0.0/should.js:4766:23)',
- 'at file:///.../bower_components/mocha/mocha.js:4794:5',
- 'at timeslice (.../components/mocha/mocha.js:6218:27)',
- 'at Test.require.register.Runnable.run (file:///.../components/mochajs/mocha/2.1.0/mocha.js:4463:15)',
- 'at Runner.require.register.Runner.runTest (file:///.../components/mochajs/mocha/2.1.0/mocha.js:4892:10)',
- 'at file:///.../components/mochajs/mocha/2.1.0/mocha.js:4970:12',
- 'at next (file:///.../components/mochajs/mocha/2.1.0/mocha.js:4817:14)'
+ "Error: failed",
+ "at assert (index.html:11:26)",
+ "at Context.<anonymous> (test.js:17:18)",
+ "at bower_components/should/should.js:4827:7",
+ "at next (file:///.../bower_components/should/should.js:4766:23)",
+ "at components/should/5.0.0/should.js:4827:7",
+ "at next (file:///.../components/should/5.0.0/should.js:4766:23)",
+ "at file:///.../bower_components/mocha/mocha.js:4794:5",
+ "at timeslice (.../components/mocha/mocha.js:6218:27)",
+ "at Test.require.register.Runnable.run (file:///.../components/mochajs/mocha/2.1.0/mocha.js:4463:15)",
+ "at Runner.require.register.Runner.runTest (file:///.../components/mochajs/mocha/2.1.0/mocha.js:4892:10)",
+ "at file:///.../components/mochajs/mocha/2.1.0/mocha.js:4970:12",
+ "at next (file:///.../components/mochajs/mocha/2.1.0/mocha.js:4817:14)",
];
- expect(filter(stack.join('\n')), 'to be', stack.slice(0, 7).join('\n'));
+ expect(filter(stack.join("\n")), "to be", stack.slice(0, 7).join("\n"));
});
- it('should replace absolute with relative paths', function () {
+ it("should replace absolute with relative paths", function () {
var stack = [
- 'Error: ' + process.cwd() + '/bla.js has a problem',
- 'at foo (' + process.cwd() + '/foo/index.js:13:226)',
- 'at bar (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:11:26)'
+ "Error: " + process.cwd() + "/bla.js has a problem",
+ "at foo (" + process.cwd() + "/foo/index.js:13:226)",
+ "at bar (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:11:26)",
];
var expected = [
- 'Error: ' + process.cwd() + '/bla.js has a problem',
- 'at foo (foo/index.js:13:226)',
- 'at bar (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:11:26)'
+ "Error: " + process.cwd() + "/bla.js has a problem",
+ "at foo (foo/index.js:13:226)",
+ "at bar (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:11:26)",
];
- expect(filter(stack.join('\n')), 'to be', expected.join('\n'));
+ expect(filter(stack.join("\n")), "to be", expected.join("\n"));
});
- it('should not replace absolute path which has cwd as infix', function () {
+ it("should not replace absolute path which has cwd as infix", function () {
var stack = [
- 'Error: /www' + process.cwd() + '/bla.js has a problem',
- 'at foo (/www' + process.cwd() + '/foo/index.js:13:226)',
- 'at bar (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:11:26)'
+ "Error: /www" + process.cwd() + "/bla.js has a problem",
+ "at foo (/www" + process.cwd() + "/foo/index.js:13:226)",
+ "at bar (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:11:26)",
];
var expected = [
- 'Error: /www' + process.cwd() + '/bla.js has a problem',
- 'at foo (/www' + process.cwd() + '/foo/index.js:13:226)',
- 'at bar (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:11:26)'
+ "Error: /www" + process.cwd() + "/bla.js has a problem",
+ "at foo (/www" + process.cwd() + "/foo/index.js:13:226)",
+ "at bar (/usr/local/dev/own/tmp/node_modules/bluebird/js/main/promise.js:11:26)",
];
- expect(filter(stack.join('\n')), 'to be', expected.join('\n'));
+ expect(filter(stack.join("\n")), "to be", expected.join("\n"));
});
});
- describe('on Windows', function () {
+ describe("on Windows", function () {
before(function () {
- if (path.sep === '/') {
+ if (path.sep === "/") {
this.skip();
}
});
- it('should work on Windows', function () {
+ it("should work on Windows", function () {
var stack = [
- 'Error: failed',
- 'at Context.<anonymous> (C:\\Users\\ishida\\src\\test\\test\\mytest.js:5:9)',
- 'at callFn (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runnable.js:326:21)',
- 'at Test.Runnable.run (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runnable.js:319:7)',
- 'at Runner.runTest (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:422:10)',
- 'at C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:528:12',
- 'at next (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:342:14)',
- 'at C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:352:7',
- 'at next (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:284:14)',
- 'at Immediate._onImmediate (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:320:5)'
+ "Error: failed",
+ "at Context.<anonymous> (C:\\Users\\ishida\\src\\test\\test\\mytest.js:5:9)",
+ "at callFn (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runnable.js:326:21)",
+ "at Test.Runnable.run (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runnable.js:319:7)",
+ "at Runner.runTest (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:422:10)",
+ "at C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:528:12",
+ "at next (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:342:14)",
+ "at C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:352:7",
+ "at next (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:284:14)",
+ "at Immediate._onImmediate (C:\\Users\\ishida\\src\\test\\node_modules\\mocha\\lib\\runner.js:320:5)",
];
- expect(filter(stack.join('\n')), 'to be', stack.slice(0, 2).join('\n'));
+ expect(filter(stack.join("\n")), "to be", stack.slice(0, 2).join("\n"));
});
});
});
- describe('on browser', function () {
+ describe("on browser", function () {
var filter;
before(function () {
global.document = true;
- global.location = {href: 'localhost:3000/foo/bar/index.html'};
+ global.location = { href: "localhost:3000/foo/bar/index.html" };
filter = utils.stackTraceFilter();
});
- it('does not strip out other bower_components', function () {
+ it("does not strip out other bower_components", function () {
var stack = [
- 'Error: failed',
- 'at assert (index.html:11:26)',
- 'at Context.<anonymous> (test.js:17:18)',
- 'at bower_components/should/should.js:4827:7',
- 'at next (bower_components/should/should.js:4766:23)',
- 'at components/should/5.0.0/should.js:4827:7',
- 'at next (components/should/5.0.0/should.js:4766:23)',
- 'at Runner.require.register.Runner.runTest (node_modules/mocha.js:4892:10)',
- 'at localhost:3000/foo/bar/node_modules/mocha.js:4970:12',
- 'at next (node_modules/mocha.js:4817:14)'
+ "Error: failed",
+ "at assert (index.html:11:26)",
+ "at Context.<anonymous> (test.js:17:18)",
+ "at bower_components/should/should.js:4827:7",
+ "at next (bower_components/should/should.js:4766:23)",
+ "at components/should/5.0.0/should.js:4827:7",
+ "at next (components/should/5.0.0/should.js:4766:23)",
+ "at Runner.require.register.Runner.runTest (node_modules/mocha.js:4892:10)",
+ "at localhost:3000/foo/bar/node_modules/mocha.js:4970:12",
+ "at next (node_modules/mocha.js:4817:14)",
];
- expect(filter(stack.join('\n')), 'to be', stack.slice(0, 7).join('\n'));
+ expect(filter(stack.join("\n")), "to be", stack.slice(0, 7).join("\n"));
});
after(function () {
diff --git a/test/node-unit/utils.spec.js b/test/node-unit/utils.spec.js
index 06fe287b..2ff4e188 100644
--- a/test/node-unit/utils.spec.js
+++ b/test/node-unit/utils.spec.js
@@ -1,68 +1,68 @@
-'use strict';
+"use strict";
-const rewiremock = require('rewiremock/node');
+const rewiremock = require("rewiremock/node");
-describe('utils', function () {
+describe("utils", function () {
let utils;
beforeEach(function () {
// add deps to be mocked as needed to second parameter
- utils = rewiremock.proxy('../../lib/utils', {});
+ utils = rewiremock.proxy("../../lib/utils", {});
});
- describe('function', function () {
- describe('cwd()', function () {
- it('should return the current working directory', function () {
- expect(utils.cwd(), 'to be', process.cwd());
+ describe("function", function () {
+ describe("cwd()", function () {
+ it("should return the current working directory", function () {
+ expect(utils.cwd(), "to be", process.cwd());
});
});
- describe('type()', function () {
+ describe("type()", function () {
it('should return "function" if the parameter is an async function', function () {
expect(
utils.type(async () => {}),
- 'to be',
- 'function'
+ "to be",
+ "function",
);
});
it('should return "error" if the parameter is an Error', function () {
- expect(utils.type(new Error('err')), 'to be', 'error');
+ expect(utils.type(new Error("err")), "to be", "error");
});
});
- describe('canonicalType()', function () {
+ describe("canonicalType()", function () {
it('should return "buffer" if the parameter is a Buffer', function () {
expect(
- utils.canonicalType(Buffer.from('ff', 'hex')),
- 'to be',
- 'buffer'
+ utils.canonicalType(Buffer.from("ff", "hex")),
+ "to be",
+ "buffer",
);
});
it('should return "asyncfunction" if the parameter is an async function', function () {
expect(
utils.canonicalType(async () => {}),
- 'to be',
- 'asyncfunction'
+ "to be",
+ "asyncfunction",
);
});
});
- describe('isNumeric()', function () {
- it('returns true for a number type', function () {
- expect(utils.isNumeric(42), 'to equal', true);
+ describe("isNumeric()", function () {
+ it("returns true for a number type", function () {
+ expect(utils.isNumeric(42), "to equal", true);
});
- it('returns true for a string that can be parsed as a number', function () {
- expect(utils.isNumeric('42'), 'to equal', true);
+ it("returns true for a string that can be parsed as a number", function () {
+ expect(utils.isNumeric("42"), "to equal", true);
});
- it('returns false for a string that cannot be parsed as a number', function () {
- expect(utils.isNumeric('foo'), 'to equal', false);
+ it("returns false for a string that cannot be parsed as a number", function () {
+ expect(utils.isNumeric("foo"), "to equal", false);
});
- it('returns false for empty string', function () {
- expect(utils.isNumeric(''), 'to equal', false);
+ it("returns false for empty string", function () {
+ expect(utils.isNumeric(""), "to equal", false);
});
- it('returns false for empty string with many whitespaces', function () {
- expect(utils.isNumeric(' '), 'to equal', false);
+ it("returns false for empty string with many whitespaces", function () {
+ expect(utils.isNumeric(" "), "to equal", false);
});
- it('returns true for stringified zero', function () {
- expect(utils.isNumeric('0'), 'to equal', true);
+ it("returns true for stringified zero", function () {
+ expect(utils.isNumeric("0"), "to equal", true);
});
});
});
diff --git a/test/node-unit/worker.spec.js b/test/node-unit/worker.spec.js
index 8a7d73dc..551cbb75 100644
--- a/test/node-unit/worker.spec.js
+++ b/test/node-unit/worker.spec.js
@@ -1,13 +1,13 @@
-'use strict';
+"use strict";
-const serializeJavascript = require('serialize-javascript');
-const rewiremock = require('rewiremock/node');
-const {SerializableWorkerResult} = require('../../lib/nodejs/serializer');
-const sinon = require('sinon');
+const serializeJavascript = require("serialize-javascript");
+const rewiremock = require("rewiremock/node");
+const { SerializableWorkerResult } = require("../../lib/nodejs/serializer");
+const sinon = require("sinon");
-const WORKER_PATH = require.resolve('../../lib/nodejs/worker.js');
+const WORKER_PATH = require.resolve("../../lib/nodejs/worker.js");
-describe('worker', function () {
+describe("worker", function () {
let worker;
let stubs;
@@ -15,26 +15,26 @@ describe('worker', function () {
stubs = {
workerpool: {
isMainThread: false,
- worker: sinon.stub()
- }
+ worker: sinon.stub(),
+ },
};
- sinon.spy(process, 'removeAllListeners');
+ sinon.spy(process, "removeAllListeners");
});
- describe('when run as main process', function () {
- it('should throw', function () {
+ describe("when run as main process", function () {
+ it("should throw", function () {
expect(() => {
rewiremock.proxy(WORKER_PATH, {
workerpool: {
isMainThread: true,
- worker: stubs.workerpool.worker
- }
+ worker: stubs.workerpool.worker,
+ },
});
- }, 'to throw');
+ }, "to throw");
});
});
- describe('when run as worker process', function () {
+ describe("when run as worker process", function () {
let mocha;
beforeEach(function () {
@@ -42,93 +42,93 @@ describe('worker', function () {
addFile: sinon.stub().returnsThis(),
loadFilesAsync: sinon.stub().resolves(),
run: sinon.stub().callsArgAsync(0),
- unloadFiles: sinon.stub().returnsThis()
+ unloadFiles: sinon.stub().returnsThis(),
};
stubs.Mocha = Object.assign(sinon.stub().returns(mocha), {
bdd: sinon.stub(),
- interfaces: {}
+ interfaces: {},
});
stubs.serializer = {
- serialize: sinon.stub()
+ serialize: sinon.stub(),
};
stubs.runHelpers = {
handleRequires: sinon.stub().resolves({}),
- validateLegacyPlugin: sinon.stub()
+ validateLegacyPlugin: sinon.stub(),
};
stubs.plugin = {
- aggregateRootHooks: sinon.stub().resolves()
+ aggregateRootHooks: sinon.stub().resolves(),
};
worker = rewiremock.proxy(WORKER_PATH, {
workerpool: stubs.workerpool,
- '../../lib/mocha': stubs.Mocha,
- '../../lib/nodejs/serializer': stubs.serializer,
- '../../lib/cli/run-helpers': stubs.runHelpers,
- '../../lib/plugin-loader': stubs.plugin
+ "../../lib/mocha": stubs.Mocha,
+ "../../lib/nodejs/serializer": stubs.serializer,
+ "../../lib/cli/run-helpers": stubs.runHelpers,
+ "../../lib/plugin-loader": stubs.plugin,
});
});
- it('should register itself with workerpool', function () {
- expect(stubs.workerpool.worker, 'to have a call satisfying', [
- {run: worker.run}
+ it("should register itself with workerpool", function () {
+ expect(stubs.workerpool.worker, "to have a call satisfying", [
+ { run: worker.run },
]);
});
- describe('function', function () {
- describe('run()', function () {
- describe('when called without arguments', function () {
- it('should reject', async function () {
- return expect(worker.run, 'to be rejected with error satisfying', {
- code: 'ERR_MOCHA_INVALID_ARG_TYPE'
+ describe("function", function () {
+ describe("run()", function () {
+ describe("when called without arguments", function () {
+ it("should reject", async function () {
+ return expect(worker.run, "to be rejected with error satisfying", {
+ code: "ERR_MOCHA_INVALID_ARG_TYPE",
});
});
});
- describe('when passed a non-string `options` value', function () {
- it('should reject', async function () {
+ describe("when passed a non-string `options` value", function () {
+ it("should reject", async function () {
return expect(
- () => worker.run('foo.js', 42),
- 'to be rejected with error satisfying',
+ () => worker.run("foo.js", 42),
+ "to be rejected with error satisfying",
{
- code: 'ERR_MOCHA_INVALID_ARG_TYPE'
- }
+ code: "ERR_MOCHA_INVALID_ARG_TYPE",
+ },
);
});
});
- describe('when passed an invalid string `options` value', function () {
- it('should reject', async function () {
+ describe("when passed an invalid string `options` value", function () {
+ it("should reject", async function () {
return expect(
- () => worker.run('foo.js', 'tomfoolery'),
- 'to be rejected with error satisfying',
+ () => worker.run("foo.js", "tomfoolery"),
+ "to be rejected with error satisfying",
{
- code: 'ERR_MOCHA_INVALID_ARG_VALUE'
- }
+ code: "ERR_MOCHA_INVALID_ARG_VALUE",
+ },
);
});
});
describe('when called with empty "filepath" argument', function () {
- it('should reject', async function () {
+ it("should reject", async function () {
return expect(
- () => worker.run(''),
- 'to be rejected with error satisfying',
+ () => worker.run(""),
+ "to be rejected with error satisfying",
{
- code: 'ERR_MOCHA_INVALID_ARG_TYPE'
- }
+ code: "ERR_MOCHA_INVALID_ARG_TYPE",
+ },
);
});
});
describe('when the file at "filepath" argument is unloadable', function () {
- it('should reject', async function () {
+ it("should reject", async function () {
mocha.loadFilesAsync.rejects();
return expect(
- () => worker.run('some-non-existent-file.js'),
- 'to be rejected'
+ () => worker.run("some-non-existent-file.js"),
+ "to be rejected",
);
});
});
@@ -144,81 +144,81 @@ describe('worker', function () {
it('should handle "--require"', async function () {
await worker.run(
- 'some-file.js',
- serializeJavascript({require: 'foo'})
+ "some-file.js",
+ serializeJavascript({ require: "foo" }),
);
expect(
stubs.runHelpers.handleRequires,
- 'to have a call satisfying',
+ "to have a call satisfying",
[
- 'foo',
- {ignoredPlugins: ['mochaGlobalSetup', 'mochaGlobalTeardown']}
- ]
- ).and('was called once');
+ "foo",
+ { ignoredPlugins: ["mochaGlobalSetup", "mochaGlobalTeardown"] },
+ ],
+ ).and("was called once");
});
it('should handle "--ui"', async function () {
- const argv = {foo: 'bar'};
- await worker.run('some-file.js', serializeJavascript(argv));
+ const argv = { foo: "bar" };
+ await worker.run("some-file.js", serializeJavascript(argv));
expect(
stubs.runHelpers.validateLegacyPlugin,
- 'to have a call satisfying',
- [argv, 'ui', stubs.Mocha.interfaces]
- ).and('was called once');
+ "to have a call satisfying",
+ [argv, "ui", stubs.Mocha.interfaces],
+ ).and("was called once");
});
- it('should call Mocha#run', async function () {
- await worker.run('some-file.js');
- expect(mocha.run, 'was called once');
+ it("should call Mocha#run", async function () {
+ await worker.run("some-file.js");
+ expect(mocha.run, "was called once");
});
- it('should remove all uncaughtException listeners', async function () {
- await worker.run('some-file.js');
- expect(process.removeAllListeners, 'to have a call satisfying', [
- 'uncaughtException'
+ it("should remove all uncaughtException listeners", async function () {
+ await worker.run("some-file.js");
+ expect(process.removeAllListeners, "to have a call satisfying", [
+ "uncaughtException",
]);
});
- it('should remove all unhandledRejection listeners', async function () {
- await worker.run('some-file.js');
- expect(process.removeAllListeners, 'to have a call satisfying', [
- 'unhandledRejection'
+ it("should remove all unhandledRejection listeners", async function () {
+ await worker.run("some-file.js");
+ expect(process.removeAllListeners, "to have a call satisfying", [
+ "unhandledRejection",
]);
});
- describe('when serialization succeeds', function () {
+ describe("when serialization succeeds", function () {
beforeEach(function () {
stubs.serializer.serialize.returnsArg(0);
});
- it('should resolve with a SerializedWorkerResult', async function () {
+ it("should resolve with a SerializedWorkerResult", async function () {
return expect(
- worker.run('some-file.js'),
- 'to be fulfilled with',
- result
+ worker.run("some-file.js"),
+ "to be fulfilled with",
+ result,
);
});
});
- describe('when serialization fails', function () {
+ describe("when serialization fails", function () {
beforeEach(function () {
stubs.serializer.serialize.throws();
});
- it('should reject', async function () {
- return expect(worker.run('some-file.js'), 'to be rejected');
+ it("should reject", async function () {
+ return expect(worker.run("some-file.js"), "to be rejected");
});
});
- describe('when run twice', function () {
- it('should initialize only once', async function () {
- await worker.run('some-file.js');
- await worker.run('some-other-file.js');
+ describe("when run twice", function () {
+ it("should initialize only once", async function () {
+ await worker.run("some-file.js");
+ await worker.run("some-other-file.js");
- expect(stubs.runHelpers, 'to satisfy', {
- handleRequires: expect.it('was called once'),
- validateLegacyPlugin: expect.it('was called once')
+ expect(stubs.runHelpers, "to satisfy", {
+ handleRequires: expect.it("was called once"),
+ validateLegacyPlugin: expect.it("was called once"),
});
});
});
@@ -230,6 +230,6 @@ describe('worker', function () {
afterEach(function () {
sinon.restore();
// this is needed due to `require.cache` getting dumped in watch mode
- process.removeAllListeners('beforeExit');
+ process.removeAllListeners("beforeExit");
});
});
diff --git a/test/only/bdd-require.spec.js b/test/only/bdd-require.spec.js
index 68213e9d..1abdf879 100644
--- a/test/only/bdd-require.spec.js
+++ b/test/only/bdd-require.spec.js
@@ -1,6 +1,6 @@
-'use strict';
+"use strict";
-var mocha = require('../../lib/mocha');
+var mocha = require("../../lib/mocha");
var beforeEach = mocha.beforeEach;
var it = mocha.it;
@@ -10,9 +10,9 @@ describe('it.only via require("mocha")', function () {
beforeEach(function () {
this.didRunBeforeEach = true;
});
- describe('nested within a describe/context', function () {
- it.only('should run all enclosing beforeEach hooks', function () {
- require('node:assert').strictEqual(this.didRunBeforeEach, true);
+ describe("nested within a describe/context", function () {
+ it.only("should run all enclosing beforeEach hooks", function () {
+ require("node:assert").strictEqual(this.didRunBeforeEach, true);
});
});
});
diff --git a/test/only/global/bdd.spec.js b/test/only/global/bdd.spec.js
index dfe1c38f..537a220c 100644
--- a/test/only/global/bdd.spec.js
+++ b/test/only/global/bdd.spec.js
@@ -1,14 +1,14 @@
-'use strict';
+"use strict";
// Root-only test cases
-it.only('#Root-Suite, should run this bdd test-case #1', function () {
- expect(true, 'to be', true);
+it.only("#Root-Suite, should run this bdd test-case #1", function () {
+ expect(true, "to be", true);
});
-it('#Root-Suite, should not run this bdd test-case #2', function () {
- expect(false, 'to be', true);
+it("#Root-Suite, should not run this bdd test-case #2", function () {
+ expect(false, "to be", true);
});
-it('#Root-Suite, should not run this bdd test-case #3', function () {
- expect(false, 'to be', true);
+it("#Root-Suite, should not run this bdd test-case #3", function () {
+ expect(false, "to be", true);
});
diff --git a/test/only/global/qunit.spec.js b/test/only/global/qunit.spec.js
index 48e2a1ac..a62e1880 100644
--- a/test/only/global/qunit.spec.js
+++ b/test/only/global/qunit.spec.js
@@ -1,14 +1,14 @@
-'use strict';
+"use strict";
// Root-only test cases
-test.only('#Root-Suite, should run this qunit test-case #1', function () {
- expect(true, 'to be', true);
+test.only("#Root-Suite, should run this qunit test-case #1", function () {
+ expect(true, "to be", true);
});
-test('#Root-Suite, should not run this qunit test-case #2', function () {
- expect(false, 'to be', true);
+test("#Root-Suite, should not run this qunit test-case #2", function () {
+ expect(false, "to be", true);
});
-test('#Root-Suite, should not run this qunit test-case #3', function () {
- expect(false, 'to be', true);
+test("#Root-Suite, should not run this qunit test-case #3", function () {
+ expect(false, "to be", true);
});
diff --git a/test/only/global/tdd.spec.js b/test/only/global/tdd.spec.js
index 655c0225..421bd859 100644
--- a/test/only/global/tdd.spec.js
+++ b/test/only/global/tdd.spec.js
@@ -1,14 +1,14 @@
-'use strict';
+"use strict";
// Root-only test cases
-test.only('#Root-Suite, should run this tdd test-case #1', function () {
- expect(true, 'to be', true);
+test.only("#Root-Suite, should run this tdd test-case #1", function () {
+ expect(true, "to be", true);
});
-test('#Root-Suite, should not run this tdd test-case #2', function () {
- expect(false, 'to be', true);
+test("#Root-Suite, should not run this tdd test-case #2", function () {
+ expect(false, "to be", true);
});
-test('#Root-Suite, should not run this tdd test-case #3', function () {
- expect(false, 'to be', true);
+test("#Root-Suite, should not run this tdd test-case #3", function () {
+ expect(false, "to be", true);
});
diff --git a/test/reporters/base.spec.js b/test/reporters/base.spec.js
index 7289a091..d74e009e 100644
--- a/test/reporters/base.spec.js
+++ b/test/reporters/base.spec.js
@@ -1,20 +1,20 @@
-'use strict';
+"use strict";
-var assert = require('node:assert');
-var chai = require('chai');
-var sinon = require('sinon');
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
+var assert = require("node:assert");
+var chai = require("chai");
+var sinon = require("sinon");
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
var AssertionError = assert.AssertionError;
var Base = reporters.Base;
var chaiExpect = chai.expect;
var createElements = helpers.createElements;
var makeTest = helpers.makeTest;
-var Mocha = require('../../');
+var Mocha = require("../../");
var Suite = Mocha.Suite;
var Runner = Mocha.Runner;
-describe('Base reporter', function () {
+describe("Base reporter", function () {
var stdout;
function list(tests) {
@@ -42,8 +42,8 @@ describe('Base reporter', function () {
};
beforeEach(function () {
- sinon.stub(Base, 'useColors').value(false);
- sinon.stub(process.stdout, 'write').callsFake(gather);
+ sinon.stub(Base, "useColors").value(false);
+ sinon.stub(process.stdout, "write").callsFake(gather);
stdout = [];
});
@@ -51,21 +51,21 @@ describe('Base reporter', function () {
sinon.restore();
});
- describe('showDiff', function () {
+ describe("showDiff", function () {
var err;
beforeEach(function () {
- err = new AssertionError({actual: 'foo', expected: 'bar'});
+ err = new AssertionError({ actual: "foo", expected: "bar" });
});
- it('should show diffs by default', function () {
+ it("should show diffs by default", function () {
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'to match', /- actual/);
- expect(errOut, 'to match', /\+ expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "to match", /- actual/);
+ expect(errOut, "to match", /\+ expected/);
});
it("should show diffs if 'err.showDiff' is true", function () {
@@ -74,9 +74,9 @@ describe('Base reporter', function () {
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'to match', /- actual/);
- expect(errOut, 'to match', /\+ expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "to match", /- actual/);
+ expect(errOut, "to match", /\+ expected/);
});
it("should not show diffs if 'err.showDiff' is false", function () {
@@ -85,201 +85,201 @@ describe('Base reporter', function () {
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'not to match', /- actual/);
- expect(errOut, 'not to match', /\+ expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "not to match", /- actual/);
+ expect(errOut, "not to match", /\+ expected/);
});
it("should not show diffs if 'expected' is not defined", function () {
- var _err = new Error('ouch');
+ var _err = new Error("ouch");
var test = makeTest(_err);
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'not to match', /- actual/);
- expect(errOut, 'not to match', /\+ expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "not to match", /- actual/);
+ expect(errOut, "not to match", /\+ expected/);
});
it("should not show diffs if 'hideDiff' is true", function () {
var test = makeTest(err);
- sinon.stub(Base, 'hideDiff').value(true);
+ sinon.stub(Base, "hideDiff").value(true);
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'not to match', /- actual/);
- expect(errOut, 'not to match', /\+ expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "not to match", /- actual/);
+ expect(errOut, "not to match", /\+ expected/);
});
});
- describe('getting two strings', function () {
+ describe("getting two strings", function () {
// Fix regression V1.2.1(see: issue #1241)
- it('should show strings diff as is', function () {
- var err = new Error('test');
- err.actual = 'foo\nbar';
- err.expected = 'foo\nbaz';
+ it("should show strings diff as is", function () {
+ var err = new Error("test");
+ err.actual = "foo\nbar";
+ err.expected = "foo\nbaz";
err.showDiff = true;
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'not to match', /"foo\\nbar"/);
- expect(errOut, 'to match', /foo/).and('to match', /bar/);
- expect(errOut, 'to match', /test/);
- expect(errOut, 'to match', /actual/);
- expect(errOut, 'to match', /expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "not to match", /"foo\\nbar"/);
+ expect(errOut, "to match", /foo/).and("to match", /bar/);
+ expect(errOut, "to match", /test/);
+ expect(errOut, "to match", /actual/);
+ expect(errOut, "to match", /expected/);
});
});
- describe('diff generation', function () {
+ describe("diff generation", function () {
var inlineDiffsStub;
beforeEach(function () {
- inlineDiffsStub = sinon.stub(Base, 'inlineDiffs').value(false);
+ inlineDiffsStub = sinon.stub(Base, "inlineDiffs").value(false);
});
it("should generate unified diffs if 'inlineDiffs' is false", function () {
- var actual = 'a foo unified diff';
- var expected = 'a bar unified diff';
+ var actual = "a foo unified diff";
+ var expected = "a bar unified diff";
var output = generateDiff(actual, expected);
expect(
output,
- 'to be',
- '\n + expected - actual\n\n -a foo unified diff\n +a bar unified diff\n '
+ "to be",
+ "\n + expected - actual\n\n -a foo unified diff\n +a bar unified diff\n ",
);
});
it("should generate inline diffs if 'inlineDiffs' is true", function () {
- var actual = 'a foo inline diff';
- var expected = 'a bar inline diff';
+ var actual = "a foo inline diff";
+ var expected = "a bar inline diff";
inlineDiffsStub.value(true);
var output = generateDiff(actual, expected);
expect(
output,
- 'to be',
- ' \n actual expected\n \n a foobar inline diff\n '
+ "to be",
+ " \n actual expected\n \n a foobar inline diff\n ",
);
});
it("should truncate overly long 'actual' ", function () {
- var actual = '';
+ var actual = "";
var i = 0;
while (i++ < 500) {
- actual += 'a foo unified diff ';
+ actual += "a foo unified diff ";
}
- var expected = 'a bar unified diff';
+ var expected = "a bar unified diff";
var output = generateDiff(actual, expected);
- expect(output, 'to match', /output truncated/);
+ expect(output, "to match", /output truncated/);
});
it("should truncate overly long 'expected' ", function () {
- var actual = 'a foo unified diff';
- var expected = '';
+ var actual = "a foo unified diff";
+ var expected = "";
var i = 0;
while (i++ < 500) {
- expected += 'a bar unified diff ';
+ expected += "a bar unified diff ";
}
var output = generateDiff(actual, expected);
- expect(output, 'to match', /output truncated/);
+ expect(output, "to match", /output truncated/);
});
it("should not truncate overly long 'actual' if maxDiffSize=0", function () {
- var actual = '';
+ var actual = "";
var i = 0;
while (i++ < 120) {
- actual += 'a bar unified diff ';
+ actual += "a bar unified diff ";
}
- var expected = 'b foo unified diff';
+ var expected = "b foo unified diff";
- sinon.stub(Base, 'maxDiffSize').value(0);
+ sinon.stub(Base, "maxDiffSize").value(0);
var output = generateDiff(actual, expected);
- expect(output, 'not to match', /output truncated/);
+ expect(output, "not to match", /output truncated/);
});
it("should not truncate overly long 'expected' if maxDiffSize=0", function () {
- var actual = 'a foo unified diff';
- var expected = '';
+ var actual = "a foo unified diff";
+ var expected = "";
var i = 0;
while (i++ < 120) {
- expected += 'a bar unified diff ';
+ expected += "a bar unified diff ";
}
- sinon.stub(Base, 'maxDiffSize').value(0);
+ sinon.stub(Base, "maxDiffSize").value(0);
var output = generateDiff(actual, expected);
- expect(output, 'not to match', /output truncated/);
+ expect(output, "not to match", /output truncated/);
});
});
- describe('inline strings diff', function () {
+ describe("inline strings diff", function () {
beforeEach(function () {
- sinon.stub(Base, 'inlineDiffs').value(true);
+ sinon.stub(Base, "inlineDiffs").value(true);
});
it("should show single line diff if 'inlineDiffs' is true", function () {
- var err = new Error('test');
- err.actual = 'a foo inline diff';
- err.expected = 'a bar inline diff';
+ var err = new Error("test");
+ err.actual = "a foo inline diff";
+ err.expected = "a bar inline diff";
err.showDiff = true;
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'to match', /a foobar inline diff/);
- expect(errOut, 'to match', /test/);
- expect(errOut, 'to match', /actual/);
- expect(errOut, 'to match', /expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "to match", /a foobar inline diff/);
+ expect(errOut, "to match", /test/);
+ expect(errOut, "to match", /actual/);
+ expect(errOut, "to match", /expected/);
});
- it('should split lines if string has more than 4 line breaks', function () {
- var err = new Error('test');
- err.actual = 'a\nfoo\ninline\ndiff\nwith\nmultiple lines';
- err.expected = 'a\nbar\ninline\ndiff\nwith\nmultiple lines';
+ it("should split lines if string has more than 4 line breaks", function () {
+ var err = new Error("test");
+ err.actual = "a\nfoo\ninline\ndiff\nwith\nmultiple lines";
+ err.expected = "a\nbar\ninline\ndiff\nwith\nmultiple lines";
err.showDiff = true;
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'to match', /1 \| a/);
- expect(errOut, 'to match', /2 \| foobar/);
- expect(errOut, 'to match', /3 \| inline/);
- expect(errOut, 'to match', /4 \| diff/);
- expect(errOut, 'to match', /5 \| with/);
- expect(errOut, 'to match', /6 \| multiple lines/);
- expect(errOut, 'to match', /test/);
- expect(errOut, 'to match', /actual/);
- expect(errOut, 'to match', /expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "to match", /1 \| a/);
+ expect(errOut, "to match", /2 \| foobar/);
+ expect(errOut, "to match", /3 \| inline/);
+ expect(errOut, "to match", /4 \| diff/);
+ expect(errOut, "to match", /5 \| with/);
+ expect(errOut, "to match", /6 \| multiple lines/);
+ expect(errOut, "to match", /test/);
+ expect(errOut, "to match", /actual/);
+ expect(errOut, "to match", /expected/);
});
});
- describe('unified diff', function () {
+ describe("unified diff", function () {
beforeEach(function () {
- sinon.stub(Base, 'inlineDiffs').value(false);
+ sinon.stub(Base, "inlineDiffs").value(false);
});
- it('should separate diff hunks by two dashes', function () {
- var err = new Error('test');
- err.actual = createElements({from: 2, to: 11});
- err.expected = createElements({from: 1, to: 10});
+ it("should separate diff hunks by two dashes", function () {
+ var err = new Error("test");
+ err.actual = createElements({ from: 2, to: 11 });
+ err.expected = createElements({ from: 1, to: 10 });
err.showDiff = true;
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n');
+ var errOut = stdout.join("\n");
var regexesToMatch = [
/\[/,
@@ -297,11 +297,11 @@ describe('Base reporter', function () {
/]/,
/test/,
/expected/,
- /actual/
+ /actual/,
];
regexesToMatch.forEach(function (aRegex) {
- expect(errOut, 'to match', aRegex);
+ expect(errOut, "to match", aRegex);
});
});
});
@@ -321,35 +321,35 @@ describe('Base reporter', function () {
it("should set 'Base.maxDiffSize' used for truncating diffs", function () {
var options = {
reporterOption: {
- maxDiffSize: 4
- }
+ maxDiffSize: 4,
+ },
};
- var suite = new Suite('Dummy suite', 'root');
+ var suite = new Suite("Dummy suite", "root");
var runner = new Runner(suite);
// eslint-disable-next-line no-unused-vars
var base = new Base(runner, options);
- expect(Base.maxDiffSize, 'to be', 4);
+ expect(Base.maxDiffSize, "to be", 4);
});
});
- it('should stringify objects', function () {
- var err = new Error('test');
- err.actual = {key: 'a1'};
- err.expected = {key: 'e1'};
+ it("should stringify objects", function () {
+ var err = new Error("test");
+ err.actual = { key: "a1" };
+ err.expected = { key: "e1" };
err.showDiff = true;
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'to match', /"key"/);
- expect(errOut, 'to match', /test/);
- expect(errOut, 'to match', /- actual/);
- expect(errOut, 'to match', /\+ expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "to match", /"key"/);
+ expect(errOut, "to match", /test/);
+ expect(errOut, "to match", /- actual/);
+ expect(errOut, "to match", /\+ expected/);
});
- it('should stringify Object.create(null)', function () {
- var err = new Error('test');
+ it("should stringify Object.create(null)", function () {
+ var err = new Error("test");
err.actual = Object.create(null);
err.actual.hasOwnProperty = 1;
@@ -360,14 +360,14 @@ describe('Base reporter', function () {
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'to match', /"hasOwnProperty"/);
- expect(errOut, 'to match', /test/);
- expect(errOut, 'to match', /- actual/);
- expect(errOut, 'to match', /\+ expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "to match", /"hasOwnProperty"/);
+ expect(errOut, "to match", /test/);
+ expect(errOut, "to match", /- actual/);
+ expect(errOut, "to match", /\+ expected/);
});
- it('should handle error messages that are not strings', function () {
+ it("should handle error messages that are not strings", function () {
try {
assert(false, true);
} catch (err) {
@@ -378,11 +378,11 @@ describe('Base reporter', function () {
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'to match', /\+true/);
- expect(errOut, 'to match', /-false/);
- expect(errOut, 'to match', /- actual/);
- expect(errOut, 'to match', /\+ expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "to match", /\+true/);
+ expect(errOut, "to match", /-false/);
+ expect(errOut, "to match", /- actual/);
+ expect(errOut, "to match", /\+ expected/);
}
});
@@ -391,7 +391,7 @@ describe('Base reporter', function () {
var expected = 42;
try {
- chaiExpect(actual, 'custom error message').to.equal(expected);
+ chaiExpect(actual, "custom error message").to.equal(expected);
} catch (err) {
err.actual = actual;
err.expected = expected;
@@ -400,12 +400,12 @@ describe('Base reporter', function () {
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'to match', /custom error message\n/)
- .and('to match', /\+42/)
- .and('to match', /-43/)
- .and('to match', /- actual/)
- .and('to match', /\+ expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "to match", /custom error message\n/)
+ .and("to match", /\+42/)
+ .and("to match", /-43/)
+ .and("to match", /- actual/)
+ .and("to match", /\+ expected/);
}
});
@@ -414,7 +414,7 @@ describe('Base reporter', function () {
var expected = 42;
try {
- assert.strictEqual(actual, expected, 'custom error message');
+ assert.strictEqual(actual, expected, "custom error message");
// AssertionError: custom error message: expected 43 to equal 42.
// assert.equal(43, 42, 'custom error message: expected 43 to equal 42.');
} catch (err) {
@@ -425,112 +425,112 @@ describe('Base reporter', function () {
list([test]);
- var errOut = stdout.join('\n');
- expect(errOut, 'to match', /custom error message\n/);
- expect(errOut, 'to match', /\+42/);
- expect(errOut, 'to match', /-43/);
- expect(errOut, 'to match', /- actual/);
- expect(errOut, 'to match', /\+ expected/);
+ var errOut = stdout.join("\n");
+ expect(errOut, "to match", /custom error message\n/);
+ expect(errOut, "to match", /\+42/);
+ expect(errOut, "to match", /-43/);
+ expect(errOut, "to match", /- actual/);
+ expect(errOut, "to match", /\+ expected/);
}
});
- it('should remove message from stack', function () {
+ it("should remove message from stack", function () {
var err = {
- message: 'Error',
- stack: 'Error\nfoo\nbar',
- showDiff: false
+ message: "Error",
+ stack: "Error\nfoo\nbar",
+ showDiff: false,
};
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n').trim();
- expect(errOut, 'to be', '1) test title:\n Error\n foo\n bar');
+ var errOut = stdout.join("\n").trim();
+ expect(errOut, "to be", "1) test title:\n Error\n foo\n bar");
});
it("should use 'inspect' if 'inspect' and 'message' are set", function () {
- var err = new Error('test');
+ var err = new Error("test");
err.showDiff = false;
- err.message = 'error message';
+ err.message = "error message";
err.inspect = function () {
- return 'Inspect Error';
+ return "Inspect Error";
};
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n').trim();
+ var errOut = stdout.join("\n").trim();
- expect(errOut, 'to contain', 'Inspect Error');
+ expect(errOut, "to contain", "Inspect Error");
});
it("should set an empty message if neither 'inspect' nor 'message' is set", function () {
var err = {
- showDiff: false
+ showDiff: false,
};
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n').trim();
- expect(errOut, 'to be', '1) test title:');
+ var errOut = stdout.join("\n").trim();
+ expect(errOut, "to be", "1) test title:");
});
- it('should not modify stack if it does not contain message', function () {
+ it("should not modify stack if it does not contain message", function () {
var err = {
- message: 'Error',
- stack: 'foo\nbar',
- showDiff: false
+ message: "Error",
+ stack: "foo\nbar",
+ showDiff: false,
};
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n').trim();
- expect(errOut, 'to be', '1) test title:\n Error\n foo\n bar');
+ var errOut = stdout.join("\n").trim();
+ expect(errOut, "to be", "1) test title:\n Error\n foo\n bar");
});
- describe('error causes', function () {
- it('should append any error cause trail to stack traces', function () {
+ describe("error causes", function () {
+ it("should append any error cause trail to stack traces", function () {
var err = {
- message: 'Error',
- stack: 'Error\nfoo\nbar',
+ message: "Error",
+ stack: "Error\nfoo\nbar",
showDiff: false,
cause: {
- message: 'Cause1',
- stack: 'Cause1\nbar\nfoo',
+ message: "Cause1",
+ stack: "Cause1\nbar\nfoo",
showDiff: false,
cause: {
- message: 'Cause2',
- stack: 'Cause2\nabc\nxyz',
- showDiff: false
- }
- }
+ message: "Cause2",
+ stack: "Cause2\nabc\nxyz",
+ showDiff: false,
+ },
+ },
};
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n').trim();
+ var errOut = stdout.join("\n").trim();
expect(
errOut,
- 'to be',
- '1) test title:\n Error\n foo\n bar\n Caused by: Cause1\n bar\n foo\n Caused by: Cause2\n abc\n xyz'
+ "to be",
+ "1) test title:\n Error\n foo\n bar\n Caused by: Cause1\n bar\n foo\n Caused by: Cause2\n abc\n xyz",
);
});
- it('should not get stuck in a hypothetical circular error cause trail', function () {
+ it("should not get stuck in a hypothetical circular error cause trail", function () {
var err1 = {
- message: 'Error',
- stack: 'Error\nfoo\nbar',
- showDiff: false
+ message: "Error",
+ stack: "Error\nfoo\nbar",
+ showDiff: false,
};
var err2 = {
- message: 'Cause1',
- stack: 'Cause1\nbar\nfoo',
+ message: "Cause1",
+ stack: "Cause1\nbar\nfoo",
showDiff: false,
- cause: err1
+ cause: err1,
};
err1.cause = err2;
@@ -538,92 +538,92 @@ describe('Base reporter', function () {
list([test]);
- var errOut = stdout.join('\n').trim();
+ var errOut = stdout.join("\n").trim();
expect(
errOut,
- 'to be',
- '1) test title:\n Error\n foo\n bar\n Caused by: Cause1\n bar\n foo\n Caused by: <circular>'
+ "to be",
+ "1) test title:\n Error\n foo\n bar\n Caused by: Cause1\n bar\n foo\n Caused by: <circular>",
);
});
it("should set an empty cause if neither 'inspect' nor 'message' is set", function () {
var err = {
- message: 'Error',
- stack: 'Error\nfoo\nbar',
+ message: "Error",
+ stack: "Error\nfoo\nbar",
showDiff: false,
cause: {
- showDiff: false
- }
+ showDiff: false,
+ },
};
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n').trim();
+ var errOut = stdout.join("\n").trim();
expect(
errOut,
- 'to be',
- '1) test title:\n Error\n foo\n bar\n Caused by:'
+ "to be",
+ "1) test title:\n Error\n foo\n bar\n Caused by:",
);
});
- it('should not add cause trail if error does not contain message', function () {
+ it("should not add cause trail if error does not contain message", function () {
var err = {
- message: 'Error',
- stack: 'foo\nbar',
+ message: "Error",
+ stack: "foo\nbar",
showDiff: false,
cause: {
- message: 'Cause1',
- stack: 'Cause1\nbar\nfoo',
+ message: "Cause1",
+ stack: "Cause1\nbar\nfoo",
showDiff: false,
cause: {
- message: 'Cause2',
- stack: 'Cause2\nabc\nxyz',
- showDiff: false
- }
- }
+ message: "Cause2",
+ stack: "Cause2\nabc\nxyz",
+ showDiff: false,
+ },
+ },
};
var test = makeTest(err);
list([test]);
- var errOut = stdout.join('\n').trim();
- expect(errOut, 'to be', '1) test title:\n Error\n foo\n bar');
+ var errOut = stdout.join("\n").trim();
+ expect(errOut, "to be", "1) test title:\n Error\n foo\n bar");
});
});
- it('should list multiple Errors per test', function () {
- var err = new Error('First Error');
- err.multiple = [new Error('Second Error - same test')];
+ it("should list multiple Errors per test", function () {
+ var err = new Error("First Error");
+ err.multiple = [new Error("Second Error - same test")];
var test = makeTest(err);
list([test, test]);
- var errOut = stdout.join('\n').trim();
+ var errOut = stdout.join("\n").trim();
expect(
errOut,
- 'to contain',
- 'Error: First Error',
- 'Error: Second Error - same test'
+ "to contain",
+ "Error: First Error",
+ "Error: Second Error - same test",
);
});
- describe('when reporter output immune to user test changes', function () {
+ describe("when reporter output immune to user test changes", function () {
var baseConsoleLog;
beforeEach(function () {
sinon.restore();
- sinon.stub(console, 'log');
- baseConsoleLog = sinon.stub(Base, 'consoleLog');
+ sinon.stub(console, "log");
+ baseConsoleLog = sinon.stub(Base, "consoleLog");
});
- it('should let you stub out console.log without effecting reporters output', function () {
+ it("should let you stub out console.log without effecting reporters output", function () {
Base.list([]);
baseConsoleLog.restore();
- expect(baseConsoleLog, 'was called');
- expect(console.log, 'was not called');
+ expect(baseConsoleLog, "was called");
+ expect(console.log, "was not called");
});
});
});
diff --git a/test/reporters/doc.spec.js b/test/reporters/doc.spec.js
index 331ac1d8..ac55de55 100644
--- a/test/reporters/doc.spec.js
+++ b/test/reporters/doc.spec.js
@@ -1,8 +1,8 @@
-'use strict';
+"use strict";
-var events = require('../../').Runner.constants;
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
+var events = require("../../").Runner.constants;
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
var Doc = reporters.Doc;
var createMockRunner = helpers.createMockRunner;
@@ -13,7 +13,7 @@ var EVENT_SUITE_END = events.EVENT_SUITE_END;
var EVENT_TEST_FAIL = events.EVENT_TEST_FAIL;
var EVENT_TEST_PASS = events.EVENT_TEST_PASS;
-describe('Doc reporter', function () {
+describe("Doc reporter", function () {
var runner;
var options = {};
var runReporter = makeRunReporter(Doc);
@@ -22,235 +22,235 @@ describe('Doc reporter', function () {
runner = null;
});
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'suite' event", function () {
- describe('when suite root does not exist', function () {
- var expectedTitle = 'expectedTitle';
- var unescapedTitle = '<div>' + expectedTitle + '</div>';
+ describe("when suite root does not exist", function () {
+ var expectedTitle = "expectedTitle";
+ var unescapedTitle = "<div>" + expectedTitle + "</div>";
var suite = {
root: false,
- title: expectedTitle
+ title: expectedTitle,
};
- it('should log html with indents and expected title', function () {
+ it("should log html with indents and expected title", function () {
runner = createMockRunner(
- 'suite',
+ "suite",
EVENT_SUITE_BEGIN,
null,
null,
- suite
+ suite,
);
var stdout = runReporter(this, runner, options);
var expectedArray = [
' <section class="suite">\n',
- ' <h1>' + expectedTitle + '</h1>\n',
- ' <dl>\n'
+ " <h1>" + expectedTitle + "</h1>\n",
+ " <dl>\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
- it('should escape title where necessary', function () {
+ it("should escape title where necessary", function () {
var suite = {
root: false,
- title: unescapedTitle
+ title: unescapedTitle,
};
expectedTitle =
- '&#x3C;div&#x3E;' + expectedTitle + '&#x3C;/div&#x3E;';
+ "&#x3C;div&#x3E;" + expectedTitle + "&#x3C;/div&#x3E;";
runner = createMockRunner(
- 'suite',
+ "suite",
EVENT_SUITE_BEGIN,
null,
null,
- suite
+ suite,
);
var stdout = runReporter(this, runner, options);
var expectedArray = [
' <section class="suite">\n',
- ' <h1>' + expectedTitle + '</h1>\n',
- ' <dl>\n'
+ " <h1>" + expectedTitle + "</h1>\n",
+ " <dl>\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
- describe('when suite root exists', function () {
+ describe("when suite root exists", function () {
var suite = {
- root: true
+ root: true,
};
- it('should not log any html', function () {
+ it("should not log any html", function () {
runner = createMockRunner(
- 'suite',
+ "suite",
EVENT_SUITE_BEGIN,
null,
null,
- suite
+ suite,
);
var stdout = runReporter(this, runner, options);
- expect(stdout, 'to be empty');
+ expect(stdout, "to be empty");
});
});
});
describe("on 'suite end' event", function () {
- describe('when suite root does not exist', function () {
+ describe("when suite root does not exist", function () {
var suite = {
- root: false
+ root: false,
};
- it('should log expected html with indents', function () {
+ it("should log expected html with indents", function () {
runner = createMockRunner(
- 'suite end',
+ "suite end",
EVENT_SUITE_END,
null,
null,
- suite
+ suite,
);
var stdout = runReporter(this, runner, options);
- var expectedArray = [' </dl>\n', '</section>\n'];
- expect(stdout, 'to equal', expectedArray);
+ var expectedArray = [" </dl>\n", "</section>\n"];
+ expect(stdout, "to equal", expectedArray);
});
});
- describe('when suite root exists', function () {
+ describe("when suite root exists", function () {
var suite = {
- root: true
+ root: true,
};
- it('should not log any html', function () {
+ it("should not log any html", function () {
runner = createMockRunner(
- 'suite end',
+ "suite end",
EVENT_SUITE_END,
null,
null,
- suite
+ suite,
);
var stdout = runReporter(this, runner, options);
- expect(stdout, 'to be empty');
+ expect(stdout, "to be empty");
});
});
});
describe("on 'pass' event", function () {
- var expectedTitle = 'some tite';
- var expectedFile = 'testFile.spec.js';
- var expectedBody = 'some body';
+ var expectedTitle = "some tite";
+ var expectedFile = "testFile.spec.js";
+ var expectedBody = "some body";
var test = {
title: expectedTitle,
file: expectedFile,
body: expectedBody,
slow: function () {
- return '';
- }
+ return "";
+ },
};
- it('should log html with indents, expected title, and body', function () {
- runner = createMockRunner('pass', EVENT_TEST_PASS, null, null, test);
+ it("should log html with indents, expected title, and body", function () {
+ runner = createMockRunner("pass", EVENT_TEST_PASS, null, null, test);
var stdout = runReporter(this, runner, options);
var expectedArray = [
- ' <dt>' + expectedTitle + '</dt>\n',
- ' <dt>' + expectedFile + '</dt>\n',
- ' <dd><pre><code>' + expectedBody + '</code></pre></dd>\n'
+ " <dt>" + expectedTitle + "</dt>\n",
+ " <dt>" + expectedFile + "</dt>\n",
+ " <dd><pre><code>" + expectedBody + "</code></pre></dd>\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
- it('should escape title and body where necessary', function () {
- var unescapedTitle = '<div>' + expectedTitle + '</div>';
- var unescapedFile = '<div>' + expectedFile + '</div>';
- var unescapedBody = '<div>' + expectedBody + '</div>';
+ it("should escape title and body where necessary", function () {
+ var unescapedTitle = "<div>" + expectedTitle + "</div>";
+ var unescapedFile = "<div>" + expectedFile + "</div>";
+ var unescapedBody = "<div>" + expectedBody + "</div>";
test.title = unescapedTitle;
test.file = unescapedFile;
test.body = unescapedBody;
var expectedEscapedTitle =
- '&#x3C;div&#x3E;' + expectedTitle + '&#x3C;/div&#x3E;';
+ "&#x3C;div&#x3E;" + expectedTitle + "&#x3C;/div&#x3E;";
var expectedEscapedFile =
- '&#x3C;div&#x3E;' + expectedFile + '&#x3C;/div&#x3E;';
+ "&#x3C;div&#x3E;" + expectedFile + "&#x3C;/div&#x3E;";
var expectedEscapedBody =
- '&#x3C;div&#x3E;' + expectedBody + '&#x3C;/div&#x3E;';
- runner = createMockRunner('pass', EVENT_TEST_PASS, null, null, test);
+ "&#x3C;div&#x3E;" + expectedBody + "&#x3C;/div&#x3E;";
+ runner = createMockRunner("pass", EVENT_TEST_PASS, null, null, test);
var stdout = runReporter(this, runner, options);
var expectedArray = [
- ' <dt>' + expectedEscapedTitle + '</dt>\n',
- ' <dt>' + expectedEscapedFile + '</dt>\n',
- ' <dd><pre><code>' + expectedEscapedBody + '</code></pre></dd>\n'
+ " <dt>" + expectedEscapedTitle + "</dt>\n",
+ " <dt>" + expectedEscapedFile + "</dt>\n",
+ " <dd><pre><code>" + expectedEscapedBody + "</code></pre></dd>\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
describe("on 'fail' event", function () {
- var expectedTitle = 'some tite';
- var expectedFile = 'testFile.spec.js';
- var expectedBody = 'some body';
- var expectedError = 'some error';
+ var expectedTitle = "some tite";
+ var expectedFile = "testFile.spec.js";
+ var expectedBody = "some body";
+ var expectedError = "some error";
var test = {
title: expectedTitle,
file: expectedFile,
body: expectedBody,
slow: function () {
- return '';
- }
+ return "";
+ },
};
- it('should log html with indents, expected title, body, and error', function () {
+ it("should log html with indents, expected title, body, and error", function () {
runner = createMockRunner(
- 'fail two args',
+ "fail two args",
EVENT_TEST_FAIL,
null,
null,
test,
- expectedError
+ expectedError,
);
var stdout = runReporter(this, runner, options);
var expectedArray = [
- ' <dt class="error">' + expectedTitle + '</dt>\n',
- ' <dt class="error">' + expectedFile + '</dt>\n',
+ ' <dt class="error">' + expectedTitle + "</dt>\n",
+ ' <dt class="error">' + expectedFile + "</dt>\n",
' <dd class="error"><pre><code>' +
expectedBody +
- '</code></pre></dd>\n',
- ' <dd class="error">' + expectedError + '</dd>\n'
+ "</code></pre></dd>\n",
+ ' <dd class="error">' + expectedError + "</dd>\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
- it('should escape title, body, and error where necessary', function () {
- var unescapedTitle = '<div>' + expectedTitle + '</div>';
- var unescapedFile = '<div>' + expectedFile + '</div>';
- var unescapedBody = '<div>' + expectedBody + '</div>';
- var unescapedError = '<div>' + expectedError + '</div>';
+ it("should escape title, body, and error where necessary", function () {
+ var unescapedTitle = "<div>" + expectedTitle + "</div>";
+ var unescapedFile = "<div>" + expectedFile + "</div>";
+ var unescapedBody = "<div>" + expectedBody + "</div>";
+ var unescapedError = "<div>" + expectedError + "</div>";
test.title = unescapedTitle;
test.file = unescapedFile;
test.body = unescapedBody;
var expectedEscapedTitle =
- '&#x3C;div&#x3E;' + expectedTitle + '&#x3C;/div&#x3E;';
+ "&#x3C;div&#x3E;" + expectedTitle + "&#x3C;/div&#x3E;";
var expectedEscapedFile =
- '&#x3C;div&#x3E;' + expectedFile + '&#x3C;/div&#x3E;';
+ "&#x3C;div&#x3E;" + expectedFile + "&#x3C;/div&#x3E;";
var expectedEscapedBody =
- '&#x3C;div&#x3E;' + expectedBody + '&#x3C;/div&#x3E;';
+ "&#x3C;div&#x3E;" + expectedBody + "&#x3C;/div&#x3E;";
var expectedEscapedError =
- '&#x3C;div&#x3E;' + expectedError + '&#x3C;/div&#x3E;';
+ "&#x3C;div&#x3E;" + expectedError + "&#x3C;/div&#x3E;";
runner = createMockRunner(
- 'fail two args',
+ "fail two args",
EVENT_TEST_FAIL,
null,
null,
test,
- unescapedError
+ unescapedError,
);
var stdout = runReporter(this, runner, options);
var expectedArray = [
- ' <dt class="error">' + expectedEscapedTitle + '</dt>\n',
- ' <dt class="error">' + expectedEscapedFile + '</dt>\n',
+ ' <dt class="error">' + expectedEscapedTitle + "</dt>\n",
+ ' <dt class="error">' + expectedEscapedFile + "</dt>\n",
' <dd class="error"><pre><code>' +
expectedEscapedBody +
- '</code></pre></dd>\n',
- ' <dd class="error">' + expectedEscapedError + '</dd>\n'
+ "</code></pre></dd>\n",
+ ' <dd class="error">' + expectedEscapedError + "</dd>\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
});
diff --git a/test/reporters/dot.spec.js b/test/reporters/dot.spec.js
index 4f37d575..c04827ff 100644
--- a/test/reporters/dot.spec.js
+++ b/test/reporters/dot.spec.js
@@ -1,9 +1,9 @@
-'use strict';
+"use strict";
-var sinon = require('sinon');
-var events = require('../../').Runner.constants;
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
+var sinon = require("sinon");
+var events = require("../../").Runner.constants;
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
var Base = reporters.Base;
var Dot = reporters.Dot;
@@ -16,16 +16,16 @@ var EVENT_TEST_FAIL = events.EVENT_TEST_FAIL;
var EVENT_TEST_PASS = events.EVENT_TEST_PASS;
var EVENT_TEST_PENDING = events.EVENT_TEST_PENDING;
-describe('Dot reporter', function () {
+describe("Dot reporter", function () {
var windowWidthStub;
var runReporter = makeRunReporter(Dot);
var noop = function () {};
beforeEach(function () {
- windowWidthStub = sinon.stub(Base.window, 'width').value(0);
- sinon.stub(Base, 'useColors').value(false);
- sinon.stub(Base, 'color').callsFake(function (type, str) {
- return type.replace(/ /g, '-') + '_' + str;
+ windowWidthStub = sinon.stub(Base.window, "width").value(0);
+ sinon.stub(Base, "useColors").value(false);
+ sinon.stub(Base, "color").callsFake(function (type, str) {
+ return type.replace(/ /g, "-") + "_" + str;
});
});
@@ -33,45 +33,45 @@ describe('Dot reporter', function () {
sinon.restore();
});
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'start' event", function () {
- it('should write a newline', function () {
- var runner = createMockRunner('start', EVENT_RUN_BEGIN);
+ it("should write a newline", function () {
+ var runner = createMockRunner("start", EVENT_RUN_BEGIN);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
- var expectedArray = ['\n'];
- expect(stdout, 'to equal', expectedArray);
+ var expectedArray = ["\n"];
+ expect(stdout, "to equal", expectedArray);
});
});
describe("on 'pending' event", function () {
- describe('when window width is greater than 1', function () {
+ describe("when window width is greater than 1", function () {
beforeEach(function () {
windowWidthStub.value(2);
});
- it('should write a newline followed by a comma', function () {
- var runner = createMockRunner('pending', EVENT_TEST_PENDING);
+ it("should write a newline followed by a comma", function () {
+ var runner = createMockRunner("pending", EVENT_TEST_PENDING);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
- var expectedArray = ['\n ', 'pending_' + Base.symbols.comma];
- expect(stdout, 'to equal', expectedArray);
+ var expectedArray = ["\n ", "pending_" + Base.symbols.comma];
+ expect(stdout, "to equal", expectedArray);
});
});
- describe('when window width is less than or equal to 1', function () {
- it('should write a comma', function () {
- var runner = createMockRunner('pending', EVENT_TEST_PENDING);
+ describe("when window width is less than or equal to 1", function () {
+ it("should write a comma", function () {
+ var runner = createMockRunner("pending", EVENT_TEST_PENDING);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
- var expectedArray = ['pending_' + Base.symbols.comma];
- expect(stdout, 'to equal', expectedArray);
+ var expectedArray = ["pending_" + Base.symbols.comma];
+ expect(stdout, "to equal", expectedArray);
});
});
});
@@ -81,91 +81,91 @@ describe('Dot reporter', function () {
duration: 1,
slow: function () {
return 2;
- }
+ },
};
- describe('when window width is greater than 1', function () {
+ describe("when window width is greater than 1", function () {
beforeEach(function () {
windowWidthStub.value(2);
});
- describe('when test speed is fast', function () {
- it('should write a newline followed by a dot', function () {
+ describe("when test speed is fast", function () {
+ it("should write a newline followed by a dot", function () {
var runner = createMockRunner(
- 'pass',
+ "pass",
EVENT_TEST_PASS,
null,
null,
- test
+ test,
);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
- expect(test.speed, 'to equal', 'fast');
- var expectedArray = ['\n ', 'fast_' + Base.symbols.dot];
- expect(stdout, 'to equal', expectedArray);
+ expect(test.speed, "to equal", "fast");
+ var expectedArray = ["\n ", "fast_" + Base.symbols.dot];
+ expect(stdout, "to equal", expectedArray);
});
});
});
- describe('when window width is less than or equal to 1', function () {
- describe('when test speed is fast', function () {
- it('should write a grey dot', function () {
+ describe("when window width is less than or equal to 1", function () {
+ describe("when test speed is fast", function () {
+ it("should write a grey dot", function () {
var runner = createMockRunner(
- 'pass',
+ "pass",
EVENT_TEST_PASS,
null,
null,
- test
+ test,
);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
- expect(test.speed, 'to equal', 'fast');
- var expectedArray = ['fast_' + Base.symbols.dot];
- expect(stdout, 'to equal', expectedArray);
+ expect(test.speed, "to equal", "fast");
+ var expectedArray = ["fast_" + Base.symbols.dot];
+ expect(stdout, "to equal", expectedArray);
});
});
- describe('when test speed is medium', function () {
- it('should write a yellow dot', function () {
+ describe("when test speed is medium", function () {
+ it("should write a yellow dot", function () {
test.duration = 2;
var runner = createMockRunner(
- 'pass',
+ "pass",
EVENT_TEST_PASS,
null,
null,
- test
+ test,
);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
- expect(test.speed, 'to equal', 'medium');
- var expectedArray = ['medium_' + Base.symbols.dot];
- expect(stdout, 'to equal', expectedArray);
+ expect(test.speed, "to equal", "medium");
+ var expectedArray = ["medium_" + Base.symbols.dot];
+ expect(stdout, "to equal", expectedArray);
});
});
- describe('when test speed is slow', function () {
- it('should write a bright yellow dot', function () {
+ describe("when test speed is slow", function () {
+ it("should write a bright yellow dot", function () {
test.duration = 3;
var runner = createMockRunner(
- 'pass',
+ "pass",
EVENT_TEST_PASS,
null,
null,
- test
+ test,
);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
- expect(test.speed, 'to equal', 'slow');
- var expectedArray = ['bright-yellow_' + Base.symbols.dot];
- expect(stdout, 'to equal', expectedArray);
+ expect(test.speed, "to equal", "slow");
+ var expectedArray = ["bright-yellow_" + Base.symbols.dot];
+ expect(stdout, "to equal", expectedArray);
});
});
});
@@ -174,62 +174,62 @@ describe('Dot reporter', function () {
describe("on 'fail' event", function () {
var test = {
test: {
- err: 'some error'
- }
+ err: "some error",
+ },
};
- describe('when window width is greater than 1', function () {
+ describe("when window width is greater than 1", function () {
beforeEach(function () {
windowWidthStub.value(2);
});
- it('should write a newline followed by an exclamation mark', function () {
+ it("should write a newline followed by an exclamation mark", function () {
var runner = createMockRunner(
- 'fail',
+ "fail",
EVENT_TEST_FAIL,
null,
null,
- test
+ test,
);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
- var expectedArray = ['\n ', 'fail_' + Base.symbols.bang];
- expect(stdout, 'to equal', expectedArray);
+ var expectedArray = ["\n ", "fail_" + Base.symbols.bang];
+ expect(stdout, "to equal", expectedArray);
});
});
- describe('when window width is less than or equal to 1', function () {
- it('should write an exclamation mark', function () {
+ describe("when window width is less than or equal to 1", function () {
+ it("should write an exclamation mark", function () {
var runner = createMockRunner(
- 'fail',
+ "fail",
EVENT_TEST_FAIL,
null,
null,
- test
+ test,
);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
- var expectedArray = ['fail_' + Base.symbols.bang];
- expect(stdout, 'to equal', expectedArray);
+ var expectedArray = ["fail_" + Base.symbols.bang];
+ expect(stdout, "to equal", expectedArray);
});
});
});
describe("on 'end' event", function () {
- it('should call epilogue', function () {
- var runner = createMockRunner('end', EVENT_RUN_END);
+ it("should call epilogue", function () {
+ var runner = createMockRunner("end", EVENT_RUN_END);
var fakeThis = {
- epilogue: sinon.stub()
+ epilogue: sinon.stub(),
};
var options = {};
runReporter(fakeThis, runner, options);
sinon.restore();
- expect(fakeThis.epilogue.called, 'to be true');
+ expect(fakeThis.epilogue.called, "to be true");
});
});
});
diff --git a/test/reporters/helpers.js b/test/reporters/helpers.js
index 92725204..e7eabf30 100644
--- a/test/reporters/helpers.js
+++ b/test/reporters/helpers.js
@@ -1,8 +1,8 @@
-'use strict';
+"use strict";
-var sinon = require('sinon');
-var errors = require('../../lib/errors');
-var createStatsCollector = require('../../lib/stats-collector');
+var sinon = require("sinon");
+var errors = require("../../lib/errors");
+var createStatsCollector = require("../../lib/stats-collector");
var createUnsupportedError = errors.createUnsupportedError;
@@ -24,11 +24,11 @@ function createMockRunner(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {
ifStr2,
ifStr3,
arg1,
- arg2
+ arg2,
);
var mockRunner = {
on: runnerFunction,
- once: runnerFunction
+ once: runnerFunction,
};
createStatsCollector(mockRunner);
return mockRunner;
@@ -51,27 +51,27 @@ function createMockRunner(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {
function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {
var test = null;
switch (runStr) {
- case 'start':
- case 'pending':
- case 'end':
+ case "start":
+ case "pending":
+ case "end":
return function (event, callback) {
if (event === ifStr1) {
callback();
}
};
- case 'pending test':
- case 'pass':
- case 'fail':
- case 'suite':
- case 'suite end':
- case 'test end':
+ case "pending test":
+ case "pass":
+ case "fail":
+ case "suite":
+ case "suite end":
+ case "test end":
test = arg1;
return function (event, callback) {
if (event === ifStr1) {
callback(test);
}
};
- case 'fail two args':
+ case "fail two args":
test = arg1;
var expectedError = arg2;
return function (event, callback) {
@@ -79,7 +79,7 @@ function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {
callback(test, expectedError);
}
};
- case 'start test':
+ case "start test":
test = arg1;
return function (event, callback) {
if (event === ifStr1) {
@@ -89,7 +89,7 @@ function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {
callback(test);
}
};
- case 'suite suite end':
+ case "suite suite end":
var expectedSuite = arg1;
return function (event, callback) {
if (event === ifStr1) {
@@ -102,7 +102,7 @@ function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {
callback();
}
};
- case 'pass end':
+ case "pass end":
test = arg1;
return function (event, callback) {
if (event === ifStr1) {
@@ -112,7 +112,7 @@ function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {
callback();
}
};
- case 'test end fail':
+ case "test end fail":
test = arg1;
var error = arg2;
return function (event, callback) {
@@ -123,7 +123,7 @@ function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {
callback(test, error);
}
};
- case 'fail end pass':
+ case "fail end pass":
return function (event, callback) {
test = arg1;
if (event === ifStr1) {
@@ -138,7 +138,7 @@ function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {
};
default:
throw createUnsupportedError(
- 'This function does not support the runner string specified.'
+ "This function does not support the runner string specified.",
);
}
}
@@ -147,15 +147,15 @@ function makeTest(err) {
return {
err,
titlePath: function () {
- return ['test title'];
- }
+ return ["test title"];
+ },
};
}
function createElements(argObj) {
var res = [];
for (var i = argObj.from; i <= argObj.to; i++) {
- res.push('element ' + i);
+ res.push("element " + i);
}
return res;
}
@@ -165,7 +165,7 @@ function makeExpectedTest(
expectedFullTitle,
expectedFile,
expectedDuration,
- currentRetry
+ currentRetry,
) {
return {
title: expectedTitle,
@@ -177,7 +177,7 @@ function makeExpectedTest(
currentRetry: function () {
return currentRetry;
},
- slow: function () {}
+ slow: function () {},
};
}
@@ -199,7 +199,7 @@ function createRunReporterFunction(ctor) {
*/
var runReporter = function (stubSelf, runner, options, tee) {
var origStdoutWrite = process.stdout.write;
- var stdoutWriteStub = sinon.stub(process.stdout, 'write');
+ var stdoutWriteStub = sinon.stub(process.stdout, "write");
var stdout = [];
var gather = function (chunk) {
@@ -235,5 +235,5 @@ module.exports = {
createMockRunner,
createRunReporterFunction,
makeExpectedTest,
- makeTest
+ makeTest,
};
diff --git a/test/reporters/json-stream.spec.js b/test/reporters/json-stream.spec.js
index b0b9b814..67954865 100644
--- a/test/reporters/json-stream.spec.js
+++ b/test/reporters/json-stream.spec.js
@@ -1,8 +1,8 @@
-'use strict';
+"use strict";
-var events = require('../../').Runner.constants;
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
+var events = require("../../").Runner.constants;
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
var JSONStream = reporters.JSONStream;
var createMockRunner = helpers.createMockRunner;
@@ -14,32 +14,32 @@ var EVENT_RUN_END = events.EVENT_RUN_END;
var EVENT_TEST_FAIL = events.EVENT_TEST_FAIL;
var EVENT_TEST_PASS = events.EVENT_TEST_PASS;
-describe('JSON Stream reporter', function () {
+describe("JSON Stream reporter", function () {
var runReporter = makeRunReporter(JSONStream);
- var expectedTitle = 'some title';
- var expectedFullTitle = 'full title';
- var expectedFile = 'someTest.spec.js';
+ var expectedTitle = "some title";
+ var expectedFullTitle = "full title";
+ var expectedFile = "someTest.spec.js";
var expectedDuration = 1000;
var currentRetry = 1;
- var expectedSpeed = 'fast';
+ var expectedSpeed = "fast";
var expectedTest = makeExpectedTest(
expectedTitle,
expectedFullTitle,
expectedFile,
expectedDuration,
currentRetry,
- expectedSpeed
+ expectedSpeed,
);
- var expectedErrorMessage = 'error message';
- var expectedErrorStack = 'error stack';
+ var expectedErrorMessage = "error message";
+ var expectedErrorStack = "error stack";
var expectedError = {
- message: expectedErrorMessage
+ message: expectedErrorMessage,
};
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'start' event", function () {
- it('should write stringified start with expected total', function () {
- var runner = createMockRunner('start', EVENT_RUN_BEGIN);
+ it("should write stringified start with expected total", function () {
+ var runner = createMockRunner("start", EVENT_RUN_BEGIN);
var expectedTotal = 12;
runner.total = expectedTotal;
var options = {};
@@ -47,27 +47,27 @@ describe('JSON Stream reporter', function () {
expect(
stdout[0],
- 'to equal',
- '["start",{"total":' + expectedTotal + '}]\n'
+ "to equal",
+ '["start",{"total":' + expectedTotal + "}]\n",
);
});
});
describe("on 'pass' event", function () {
- it('should write stringified test data', function () {
+ it("should write stringified test data", function () {
var runner = createMockRunner(
- 'pass',
+ "pass",
EVENT_TEST_PASS,
null,
null,
- expectedTest
+ expectedTest,
);
var options = {};
var stdout = runReporter({}, runner, options);
expect(
stdout[0],
- 'to equal',
+ "to equal",
'["pass",{"title":' +
`"${expectedTitle}"` +
',"fullTitle":' +
@@ -80,29 +80,29 @@ describe('JSON Stream reporter', function () {
currentRetry +
',"speed":' +
`"${expectedSpeed}"` +
- '}]\n'
+ "}]\n",
);
});
});
describe("on 'fail' event", function () {
- describe('when error stack exists', function () {
- it('should write stringified test data with error data', function () {
+ describe("when error stack exists", function () {
+ it("should write stringified test data with error data", function () {
expectedError.stack = expectedErrorStack;
var runner = createMockRunner(
- 'fail two args',
+ "fail two args",
EVENT_TEST_FAIL,
null,
null,
expectedTest,
- expectedError
+ expectedError,
);
var options = {};
var stdout = runReporter({}, runner, options);
expect(
stdout[0],
- 'to equal',
+ "to equal",
'["fail",{"title":' +
`"${expectedTitle}"` +
',"fullTitle":' +
@@ -119,28 +119,28 @@ describe('JSON Stream reporter', function () {
`"${expectedErrorMessage}"` +
',"stack":' +
`"${expectedErrorStack}"` +
- '}]\n'
+ "}]\n",
);
});
});
- describe('when error stack does not exist', function () {
- it('should write stringified test data with error data', function () {
+ describe("when error stack does not exist", function () {
+ it("should write stringified test data with error data", function () {
expectedError.stack = null;
var runner = createMockRunner(
- 'fail two args',
+ "fail two args",
EVENT_TEST_FAIL,
null,
null,
expectedTest,
- expectedError
+ expectedError,
);
var options = {};
var stdout = runReporter(this, runner, options);
expect(
stdout[0],
- 'to equal',
+ "to equal",
'["fail",{"title":' +
`"${expectedTitle}"` +
',"fullTitle":' +
@@ -155,18 +155,18 @@ describe('JSON Stream reporter', function () {
`"${expectedSpeed}"` +
',"err":' +
`"${expectedErrorMessage}"` +
- ',"stack":null}]\n'
+ ',"stack":null}]\n',
);
});
});
});
describe("on 'end' event", function () {
- it('should write summary statistics', function () {
- var runner = createMockRunner('end', EVENT_RUN_END);
+ it("should write summary statistics", function () {
+ var runner = createMockRunner("end", EVENT_RUN_END);
var options = {};
var stdout = runReporter(this, runner, options);
- expect(stdout[0], 'to match', /end/);
+ expect(stdout[0], "to match", /end/);
});
});
});
diff --git a/test/reporters/json.spec.js b/test/reporters/json.spec.js
index 823bd692..3cb53fe7 100644
--- a/test/reporters/json.spec.js
+++ b/test/reporters/json.spec.js
@@ -1,27 +1,27 @@
-'use strict';
+"use strict";
-var fs = require('node:fs');
-var sinon = require('sinon');
-var JSONReporter = require('../../lib/reporters/json');
-var utils = require('../../lib/utils');
-var Mocha = require('../../');
+var fs = require("node:fs");
+var sinon = require("sinon");
+var JSONReporter = require("../../lib/reporters/json");
+var utils = require("../../lib/utils");
+var Mocha = require("../../");
var Suite = Mocha.Suite;
var Runner = Mocha.Runner;
var Test = Mocha.Test;
-describe('JSON reporter', function () {
+describe("JSON reporter", function () {
var mocha;
var suite;
var runner;
- var testTitle = 'json test 1';
- var testFile = 'someTest.spec.js';
+ var testTitle = "json test 1";
+ var testFile = "someTest.spec.js";
var noop = function () {};
beforeEach(function () {
mocha = new Mocha({
- reporter: 'json'
+ reporter: "json",
});
- suite = new Suite('JSON suite', 'root');
+ suite = new Suite("JSON suite", "root");
runner = new Runner(suite);
});
@@ -29,7 +29,7 @@ describe('JSON reporter', function () {
sinon.restore();
});
- describe('test results', function () {
+ describe("test results", function () {
beforeEach(function () {
var options = {};
/* eslint no-unused-vars: off */
@@ -37,11 +37,11 @@ describe('JSON reporter', function () {
});
beforeEach(function () {
- sinon.stub(process.stdout, 'write').callsFake(noop);
+ sinon.stub(process.stdout, "write").callsFake(noop);
});
- it('should have 1 test failure', function (done) {
- var error = {message: 'oh shit'};
+ it("should have 1 test failure", function (done) {
+ var error = { message: "oh shit" };
var test = new Test(testTitle, function (done) {
done(new Error(error.message));
@@ -52,47 +52,47 @@ describe('JSON reporter', function () {
runner.run(function (failureCount) {
sinon.restore();
- expect(runner, 'to satisfy', {
+ expect(runner, "to satisfy", {
testResults: {
failures: [
{
title: testTitle,
file: testFile,
err: {
- message: error.message
- }
- }
- ]
- }
+ message: error.message,
+ },
+ },
+ ],
+ },
});
- expect(failureCount, 'to be', 1);
+ expect(failureCount, "to be", 1);
done();
});
});
- it('should have 1 test pending', function (done) {
+ it("should have 1 test pending", function (done) {
var test = new Test(testTitle);
test.file = testFile;
suite.addTest(test);
runner.run(function (failureCount) {
sinon.restore();
- expect(runner, 'to satisfy', {
+ expect(runner, "to satisfy", {
testResults: {
pending: [
{
title: testTitle,
- file: testFile
- }
- ]
- }
+ file: testFile,
+ },
+ ],
+ },
});
- expect(failureCount, 'to be', 0);
+ expect(failureCount, "to be", 0);
done();
});
});
- it('should have 1 test pass', function (done) {
+ it("should have 1 test pass", function (done) {
const test = new Test(testTitle, () => {});
test.file = testFile;
@@ -100,26 +100,26 @@ describe('JSON reporter', function () {
runner.run(function (failureCount) {
sinon.restore();
- expect(runner, 'to satisfy', {
+ expect(runner, "to satisfy", {
testResults: {
passes: [
{
title: testTitle,
file: testFile,
- speed: /(slow|medium|fast)/
- }
- ]
- }
+ speed: /(slow|medium|fast)/,
+ },
+ ],
+ },
});
- expect(failureCount, 'to be', 0);
+ expect(failureCount, "to be", 0);
done();
});
});
- it('should handle circular objects in errors', function (done) {
- var testTitle = 'json test 1';
+ it("should handle circular objects in errors", function (done) {
+ var testTitle = "json test 1";
function CircleError() {
- this.message = 'oh shit';
+ this.message = "oh shit";
this.circular = this;
}
var error = new CircleError();
@@ -133,32 +133,32 @@ describe('JSON reporter', function () {
runner.run(function (failureCount) {
sinon.restore();
- expect(runner, 'to satisfy', {
+ expect(runner, "to satisfy", {
testResults: {
failures: [
{
title: testTitle,
file: testFile,
err: {
- message: error.message
- }
- }
- ]
- }
+ message: error.message,
+ },
+ },
+ ],
+ },
});
- expect(failureCount, 'to be', 1);
+ expect(failureCount, "to be", 1);
done();
});
});
});
describe('when "reporterOption.output" is provided', function () {
- var expectedDirName = 'reports';
- var expectedFileName = 'reports/test-results.json';
+ var expectedDirName = "reports";
+ var expectedFileName = "reports/test-results.json";
var options = {
reporterOption: {
- output: expectedFileName
- }
+ output: expectedFileName,
+ },
};
beforeEach(function () {
@@ -173,60 +173,60 @@ describe('JSON reporter', function () {
suite.addTest(test);
});
- it('should write test results to file', function (done) {
- const fsMkdirSync = sinon.stub(fs, 'mkdirSync');
- const fsWriteFileSync = sinon.stub(fs, 'writeFileSync');
+ it("should write test results to file", function (done) {
+ const fsMkdirSync = sinon.stub(fs, "mkdirSync");
+ const fsWriteFileSync = sinon.stub(fs, "writeFileSync");
fsWriteFileSync.callsFake(function (filename, content) {
const expectedJson = JSON.stringify(runner.testResults, null, 2);
- expect(expectedFileName, 'to be', filename);
- expect(content, 'to be', expectedJson);
+ expect(expectedFileName, "to be", filename);
+ expect(content, "to be", expectedJson);
});
runner.run(function () {
expect(
- fsMkdirSync.calledWith(expectedDirName, {recursive: true}),
- 'to be true'
+ fsMkdirSync.calledWith(expectedDirName, { recursive: true }),
+ "to be true",
);
- expect(fsWriteFileSync.calledOnce, 'to be true');
+ expect(fsWriteFileSync.calledOnce, "to be true");
done();
});
});
- it('should warn and write test results to console', function (done) {
- const fsMkdirSync = sinon.stub(fs, 'mkdirSync');
- const fsWriteFileSync = sinon.stub(fs, 'writeFileSync');
+ it("should warn and write test results to console", function (done) {
+ const fsMkdirSync = sinon.stub(fs, "mkdirSync");
+ const fsWriteFileSync = sinon.stub(fs, "writeFileSync");
- fsWriteFileSync.throws('unable to write file');
+ fsWriteFileSync.throws("unable to write file");
const outLog = [];
- const fake = chunk => outLog.push(chunk);
- sinon.stub(process.stderr, 'write').callsFake(fake);
- sinon.stub(process.stdout, 'write').callsFake(fake);
+ const fake = (chunk) => outLog.push(chunk);
+ sinon.stub(process.stderr, "write").callsFake(fake);
+ sinon.stub(process.stdout, "write").callsFake(fake);
runner.run(function () {
sinon.restore();
expect(
- fsMkdirSync.calledWith(expectedDirName, {recursive: true}),
- 'to be true'
+ fsMkdirSync.calledWith(expectedDirName, { recursive: true }),
+ "to be true",
);
- expect(fsWriteFileSync.calledOnce, 'to be true');
+ expect(fsWriteFileSync.calledOnce, "to be true");
expect(
outLog[0],
- 'to contain',
- `[mocha] writing output to "${expectedFileName}" failed:`
+ "to contain",
+ `[mocha] writing output to "${expectedFileName}" failed:`,
);
- expect(outLog[1], 'to match', /"fullTitle": "JSON suite json test 1"/);
+ expect(outLog[1], "to match", /"fullTitle": "JSON suite json test 1"/);
done();
});
});
it('should throw "unsupported error" in browser', function () {
- sinon.stub(utils, 'isBrowser').callsFake(() => true);
+ sinon.stub(utils, "isBrowser").callsFake(() => true);
expect(
() => new JSONReporter(runner, options),
- 'to throw',
- 'file output not supported in browser'
+ "to throw",
+ "file output not supported in browser",
);
});
});
diff --git a/test/reporters/landing.spec.js b/test/reporters/landing.spec.js
index dc335188..1635a3ee 100644
--- a/test/reporters/landing.spec.js
+++ b/test/reporters/landing.spec.js
@@ -1,10 +1,10 @@
-'use strict';
+"use strict";
-var sinon = require('sinon');
-var events = require('../../').Runner.constants;
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
-var states = require('../../').Runnable.constants;
+var sinon = require("sinon");
+var events = require("../../").Runner.constants;
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
+var states = require("../../").Runnable.constants;
var Base = reporters.Base;
var Landing = reporters.Landing;
@@ -18,111 +18,111 @@ var EVENT_TEST_END = events.EVENT_TEST_END;
var STATE_FAILED = states.STATE_FAILED;
var STATE_PASSED = states.STATE_PASSED;
-describe('Landing reporter', function () {
+describe("Landing reporter", function () {
var runReporter = makeRunReporter(Landing);
- var resetCode = '\u001b[0m';
+ var resetCode = "\u001b[0m";
var expectedArray = [
- '\u001b[1D\u001b[2A',
- ' ',
- '\n ',
- '',
- '✈',
- '\n',
- ' ',
- resetCode
+ "\u001b[1D\u001b[2A",
+ " ",
+ "\n ",
+ "",
+ "✈",
+ "\n",
+ " ",
+ resetCode,
];
beforeEach(function () {
- sinon.stub(Base, 'useColors').value(false);
- sinon.stub(Base.window, 'width').value(1);
+ sinon.stub(Base, "useColors").value(false);
+ sinon.stub(Base.window, "width").value(1);
});
afterEach(function () {
sinon.restore();
});
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'start' event", function () {
- it('should write newlines', function () {
- sinon.stub(Base.cursor, 'hide');
+ it("should write newlines", function () {
+ sinon.stub(Base.cursor, "hide");
- var runner = createMockRunner('start', EVENT_RUN_BEGIN);
+ var runner = createMockRunner("start", EVENT_RUN_BEGIN);
var options = {};
var stdout = runReporter({}, runner, options);
sinon.restore();
- expect(stdout[0], 'to equal', '\n\n\n ');
+ expect(stdout[0], "to equal", "\n\n\n ");
});
- it('should call cursor hide', function () {
- var hideCursorStub = sinon.stub(Base.cursor, 'hide');
+ it("should call cursor hide", function () {
+ var hideCursorStub = sinon.stub(Base.cursor, "hide");
- var runner = createMockRunner('start', EVENT_RUN_BEGIN);
+ var runner = createMockRunner("start", EVENT_RUN_BEGIN);
var options = {};
runReporter({}, runner, options);
sinon.restore();
- expect(hideCursorStub.called, 'to be true');
+ expect(hideCursorStub.called, "to be true");
});
});
describe("on 'test end' event", function () {
- describe('when test passes', function () {
- it('should write expected landing strip', function () {
+ describe("when test passes", function () {
+ it("should write expected landing strip", function () {
var test = {
- state: STATE_PASSED
+ state: STATE_PASSED,
};
var runner = createMockRunner(
- 'test end',
+ "test end",
EVENT_TEST_END,
null,
null,
- test
+ test,
);
var options = {};
var stdout = runReporter({}, runner, options);
sinon.restore();
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
- describe('when test fails', function () {
- it('should write expected landing strip', function () {
+ describe("when test fails", function () {
+ it("should write expected landing strip", function () {
var test = {
- state: STATE_FAILED
+ state: STATE_FAILED,
};
var runner = createMockRunner(
- 'test end',
+ "test end",
EVENT_TEST_END,
null,
null,
- test
+ test,
);
runner.total = 12;
var options = {};
var stdout = runReporter({}, runner, options);
sinon.restore();
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
});
describe("on 'end' event", function () {
- it('should call cursor show and epilogue', function () {
- var showCursorStub = sinon.stub(Base.cursor, 'show');
+ it("should call cursor show and epilogue", function () {
+ var showCursorStub = sinon.stub(Base.cursor, "show");
var fakeThis = {
- epilogue: sinon.spy()
+ epilogue: sinon.spy(),
};
- var runner = createMockRunner('end', EVENT_RUN_END);
+ var runner = createMockRunner("end", EVENT_RUN_END);
var options = {};
runReporter(fakeThis, runner, options);
sinon.restore();
- expect(fakeThis.epilogue.calledOnce, 'to be true');
- expect(showCursorStub.called, 'to be true');
+ expect(fakeThis.epilogue.calledOnce, "to be true");
+ expect(showCursorStub.called, "to be true");
});
});
});
diff --git a/test/reporters/list.spec.js b/test/reporters/list.spec.js
index b704f77c..8bff0c57 100644
--- a/test/reporters/list.spec.js
+++ b/test/reporters/list.spec.js
@@ -1,9 +1,9 @@
-'use strict';
+"use strict";
-var sinon = require('sinon');
-var events = require('../../').Runner.constants;
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
+var sinon = require("sinon");
+var events = require("../../").Runner.constants;
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
var Base = reporters.Base;
var List = reporters.List;
@@ -17,9 +17,9 @@ var EVENT_TEST_FAIL = events.EVENT_TEST_FAIL;
var EVENT_TEST_PASS = events.EVENT_TEST_PASS;
var EVENT_TEST_PENDING = events.EVENT_TEST_PENDING;
-describe('List reporter', function () {
+describe("List reporter", function () {
var runReporter = makeRunReporter(List);
- var expectedTitle = 'some title';
+ var expectedTitle = "some title";
var expectedDuration = 100;
var noop = function () {};
var test = {
@@ -27,58 +27,58 @@ describe('List reporter', function () {
return expectedTitle;
},
duration: expectedDuration,
- slow: noop
+ slow: noop,
};
beforeEach(function () {
- sinon.stub(Base, 'useColors').value(false);
+ sinon.stub(Base, "useColors").value(false);
});
afterEach(function () {
sinon.restore();
});
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'start' and 'test' events", function () {
- it('should write expected newline and title', function () {
+ it("should write expected newline and title", function () {
var runner = createMockRunner(
- 'start test',
+ "start test",
EVENT_RUN_BEGIN,
EVENT_TEST_BEGIN,
null,
- test
+ test,
);
var options = {};
var fakeThis = {
- epilogue: noop
+ epilogue: noop,
};
var stdout = runReporter(fakeThis, runner, options);
sinon.restore();
- var startString = '\n';
- var testString = ' ' + expectedTitle + ': ';
+ var startString = "\n";
+ var testString = " " + expectedTitle + ": ";
var expectedArray = [startString, testString];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
describe("on 'pending' event", function () {
- it('should write expected title', function () {
+ it("should write expected title", function () {
var runner = createMockRunner(
- 'pending test',
+ "pending test",
EVENT_TEST_PENDING,
null,
null,
- test
+ test,
);
var options = {};
var fakeThis = {
- epilogue: noop
+ epilogue: noop,
};
var stdout = runReporter(fakeThis, runner, options);
sinon.restore();
- expect(stdout[0], 'to equal', ' - ' + expectedTitle + '\n');
+ expect(stdout[0], "to equal", " - " + expectedTitle + "\n");
});
});
@@ -86,55 +86,55 @@ describe('List reporter', function () {
var crStub;
beforeEach(function () {
- crStub = sinon.stub(Base.cursor, 'CR').callsFake(noop);
+ crStub = sinon.stub(Base.cursor, "CR").callsFake(noop);
});
- it('should call cursor CR', function () {
+ it("should call cursor CR", function () {
var runner = createMockRunner(
- 'pass',
+ "pass",
EVENT_TEST_PASS,
null,
null,
- test
+ test,
);
var options = {};
var fakeThis = {
- epilogue: noop
+ epilogue: noop,
};
runReporter(fakeThis, runner, options);
sinon.restore();
- expect(crStub.called, 'to be true');
+ expect(crStub.called, "to be true");
});
- it('should write expected symbol, title, and duration', function () {
- var expectedOkSymbol = 'OK';
- sinon.stub(Base.symbols, 'ok').value(expectedOkSymbol);
+ it("should write expected symbol, title, and duration", function () {
+ var expectedOkSymbol = "OK";
+ sinon.stub(Base.symbols, "ok").value(expectedOkSymbol);
var runner = createMockRunner(
- 'pass',
+ "pass",
EVENT_TEST_PASS,
null,
null,
- test
+ test,
);
var options = {};
var fakeThis = {
- epilogue: noop
+ epilogue: noop,
};
var stdout = runReporter(fakeThis, runner, options);
sinon.restore();
expect(
stdout[0],
- 'to be',
- ' ' +
+ "to be",
+ " " +
expectedOkSymbol +
- ' ' +
+ " " +
expectedTitle +
- ': ' +
+ ": " +
expectedDuration +
- 'ms\n'
+ "ms\n",
);
});
});
@@ -143,71 +143,71 @@ describe('List reporter', function () {
var crStub;
beforeEach(function () {
- crStub = sinon.stub(Base.cursor, 'CR').callsFake(noop);
+ crStub = sinon.stub(Base.cursor, "CR").callsFake(noop);
});
- it('should call cursor CR', function () {
+ it("should call cursor CR", function () {
var runner = createMockRunner(
- 'fail',
+ "fail",
EVENT_TEST_FAIL,
null,
null,
- test
+ test,
);
var options = {};
var fakeThis = {
- epilogue: noop
+ epilogue: noop,
};
runReporter(fakeThis, runner, options);
sinon.restore();
- expect(crStub.called, 'to be true');
+ expect(crStub.called, "to be true");
});
- it('should write expected error number and title', function () {
+ it("should write expected error number and title", function () {
var expectedErrorCount = 1;
var runner = createMockRunner(
- 'fail',
+ "fail",
EVENT_TEST_FAIL,
null,
null,
- test
+ test,
);
var options = {};
var fakeThis = {
- epilogue: noop
+ epilogue: noop,
};
var stdout = runReporter(fakeThis, runner, options);
sinon.restore();
expect(
stdout[0],
- 'to be',
- ' ' + expectedErrorCount + ') ' + expectedTitle + '\n'
+ "to be",
+ " " + expectedErrorCount + ") " + expectedTitle + "\n",
);
});
- it('should immediately construct fail strings', function () {
- var actual = {a: 'actual'};
- var expected = {a: 'expected'};
+ it("should immediately construct fail strings", function () {
+ var actual = { a: "actual" };
+ var expected = { a: "expected" };
var checked = false;
var err;
test = {};
var runner = createMockRunner(
- 'fail',
+ "fail",
EVENT_TEST_FAIL,
null,
null,
- test
+ test,
);
runner.on = runner.once = function (event, callback) {
if (
!checked &&
- event === 'fail' &&
- callback.toString().includes('stringifyDiffObjs') // target correct fail event callback
+ event === "fail" &&
+ callback.toString().includes("stringifyDiffObjs") // target correct fail event callback
) {
- err = new Error('fake failure object with actual/expected');
+ err = new Error("fake failure object with actual/expected");
err.actual = actual;
err.expected = expected;
err.showDiff = true;
@@ -217,27 +217,27 @@ describe('List reporter', function () {
};
var options = {};
var fakeThis = {
- epilogue: noop
+ epilogue: noop,
};
runReporter(fakeThis, runner, options);
sinon.restore();
- expect(typeof err.actual, 'to be', 'string');
- expect(typeof err.expected, 'to be', 'string');
+ expect(typeof err.actual, "to be", "string");
+ expect(typeof err.expected, "to be", "string");
});
});
describe("on 'end' event", function () {
- it('should call epilogue', function () {
- var runner = createMockRunner('end', EVENT_RUN_END);
+ it("should call epilogue", function () {
+ var runner = createMockRunner("end", EVENT_RUN_END);
var options = {};
var fakeThis = {
- epilogue: sinon.spy()
+ epilogue: sinon.spy(),
};
runReporter(fakeThis, runner, options);
sinon.restore();
- expect(fakeThis.epilogue.calledOnce, 'to be true');
+ expect(fakeThis.epilogue.calledOnce, "to be true");
});
});
});
diff --git a/test/reporters/markdown.spec.js b/test/reporters/markdown.spec.js
index c81632a1..c46a563f 100644
--- a/test/reporters/markdown.spec.js
+++ b/test/reporters/markdown.spec.js
@@ -1,8 +1,8 @@
-'use strict';
+"use strict";
-var events = require('../../').Runner.constants;
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
+var events = require("../../").Runner.constants;
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
var Markdown = reporters.Markdown;
var createMockRunner = helpers.createMockRunner;
@@ -13,14 +13,14 @@ var EVENT_SUITE_BEGIN = events.EVENT_SUITE_BEGIN;
var EVENT_SUITE_END = events.EVENT_SUITE_END;
var EVENT_TEST_PASS = events.EVENT_TEST_PASS;
-describe('Markdown reporter', function () {
+describe("Markdown reporter", function () {
var runReporter = makeRunReporter(Markdown);
- var expectedTitle = 'expected title';
- var expectedFullTitle = 'full title';
- var sluggedFullTitle = 'full-title';
+ var expectedTitle = "expected title";
+ var expectedFullTitle = "full title";
+ var sluggedFullTitle = "full-title";
var noop = function () {};
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'suite' event", function () {
it("should write expected slugged titles on 'end' event", function () {
var expectedSuite = {
@@ -34,36 +34,36 @@ describe('Markdown reporter', function () {
fullTitle: function () {
return expectedFullTitle;
},
- suites: []
- }
- ]
+ suites: [],
+ },
+ ],
};
var runner = createMockRunner(
- 'suite suite end',
+ "suite suite end",
EVENT_SUITE_BEGIN,
EVENT_SUITE_END,
EVENT_RUN_END,
- expectedSuite
+ expectedSuite,
);
runner.suite = expectedSuite;
var options = {};
var stdout = runReporter({}, runner, options);
var expectedArray = [
- '# TOC\n',
- ' - [' +
+ "# TOC\n",
+ " - [" +
expectedTitle +
- '](#' +
+ "](#" +
sluggedFullTitle +
- ')\n - [' +
+ ")\n - [" +
expectedTitle +
- '](#' +
+ "](#" +
sluggedFullTitle +
- ')\n',
- '<a name="' + sluggedFullTitle + '"></a>\n ' + expectedTitle + '\n'
+ ")\n",
+ '<a name="' + sluggedFullTitle + '"></a>\n ' + expectedTitle + "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
@@ -74,11 +74,11 @@ describe('Markdown reporter', function () {
fullTitle: function () {
return expectedFullTitle;
},
- suites: []
+ suites: [],
};
var expectedDuration = 1000;
var currentRetry = 1;
- var expectedBody = 'some body';
+ var expectedBody = "some body";
var expectedTest = {
title: expectedTitle,
fullTitle: function () {
@@ -89,26 +89,26 @@ describe('Markdown reporter', function () {
return currentRetry;
},
slow: noop,
- body: expectedBody
+ body: expectedBody,
};
var runner = createMockRunner(
- 'pass end',
+ "pass end",
EVENT_TEST_PASS,
EVENT_RUN_END,
null,
- expectedTest
+ expectedTest,
);
runner.suite = expectedSuite;
var options = {};
var stdout = runReporter({}, runner, options);
var expectedArray = [
- '# TOC\n',
- ' - [' + expectedTitle + '](#' + sluggedFullTitle + ')\n',
- expectedTitle + '.\n\n```js\n' + expectedBody + '\n```\n\n'
+ "# TOC\n",
+ " - [" + expectedTitle + "](#" + sluggedFullTitle + ")\n",
+ expectedTitle + ".\n\n```js\n" + expectedBody + "\n```\n\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
});
diff --git a/test/reporters/min.spec.js b/test/reporters/min.spec.js
index 65fc6320..521ba9a5 100644
--- a/test/reporters/min.spec.js
+++ b/test/reporters/min.spec.js
@@ -1,9 +1,9 @@
-'use strict';
+"use strict";
-var sinon = require('sinon');
-var events = require('../../').Runner.constants;
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
+var sinon = require("sinon");
+var events = require("../../").Runner.constants;
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
var Min = reporters.Min;
var createMockRunner = helpers.createMockRunner;
@@ -12,35 +12,35 @@ var makeRunReporter = helpers.createRunReporterFunction;
var EVENT_RUN_BEGIN = events.EVENT_RUN_BEGIN;
var EVENT_RUN_END = events.EVENT_RUN_END;
-describe('Min reporter', function () {
+describe("Min reporter", function () {
var runReporter = makeRunReporter(Min);
var noop = function () {};
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'start' event", function () {
- it('should clear screen then set cursor position', function () {
- var runner = createMockRunner('start', EVENT_RUN_BEGIN);
+ it("should clear screen then set cursor position", function () {
+ var runner = createMockRunner("start", EVENT_RUN_BEGIN);
var options = {};
var fakeThis = {
- epilogue: noop
+ epilogue: noop,
};
var stdout = runReporter(fakeThis, runner, options);
- var expectedArray = ['\u001b[2J', '\u001b[1;3H'];
- expect(stdout, 'to equal', expectedArray);
+ var expectedArray = ["\u001b[2J", "\u001b[1;3H"];
+ expect(stdout, "to equal", expectedArray);
});
});
describe("on 'end' event", function () {
- it('should call epilogue', function () {
+ it("should call epilogue", function () {
var fakeThis = {
- epilogue: sinon.stub().callsFake(noop)
+ epilogue: sinon.stub().callsFake(noop),
};
- var runner = createMockRunner('end', EVENT_RUN_END);
+ var runner = createMockRunner("end", EVENT_RUN_END);
var options = {};
runReporter(fakeThis, runner, options);
- expect(fakeThis.epilogue.called, 'to be true');
+ expect(fakeThis.epilogue.called, "to be true");
});
});
});
diff --git a/test/reporters/nyan.spec.js b/test/reporters/nyan.spec.js
index faed2588..aac0fd47 100644
--- a/test/reporters/nyan.spec.js
+++ b/test/reporters/nyan.spec.js
@@ -1,9 +1,9 @@
-'use strict';
+"use strict";
-var sinon = require('sinon');
-var events = require('../../').Runner.constants;
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
+var sinon = require("sinon");
+var events = require("../../").Runner.constants;
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
var Base = reporters.Base;
var NyanCat = reporters.Nyan;
@@ -16,151 +16,151 @@ var EVENT_TEST_FAIL = events.EVENT_TEST_FAIL;
var EVENT_TEST_PASS = events.EVENT_TEST_PASS;
var EVENT_TEST_PENDING = events.EVENT_TEST_PENDING;
-describe('Nyan reporter', function () {
+describe("Nyan reporter", function () {
var noop = function () {};
afterEach(function () {
sinon.restore();
});
- describe('event handlers', function () {
+ describe("event handlers", function () {
var runReporter = makeRunReporter(NyanCat);
describe("on 'start' event", function () {
- it('should call draw', function () {
+ it("should call draw", function () {
var fakeThis = {
draw: sinon.stub().callsFake(noop),
- generateColors: noop
+ generateColors: noop,
};
- var runner = createMockRunner('start', EVENT_RUN_BEGIN);
+ var runner = createMockRunner("start", EVENT_RUN_BEGIN);
var options = {};
runReporter(fakeThis, runner, options);
- expect(fakeThis.draw.called, 'to be true');
+ expect(fakeThis.draw.called, "to be true");
});
});
describe("on 'pending' event", function () {
- it('should call draw', function () {
+ it("should call draw", function () {
var fakeThis = {
draw: sinon.stub().callsFake(noop),
- generateColors: noop
+ generateColors: noop,
};
- var runner = createMockRunner('pending', EVENT_TEST_PENDING);
+ var runner = createMockRunner("pending", EVENT_TEST_PENDING);
var options = {};
runReporter(fakeThis, runner, options);
- expect(fakeThis.draw.called, 'to be true');
+ expect(fakeThis.draw.called, "to be true");
});
});
describe("on 'pass' event", function () {
- it('should call draw', function () {
+ it("should call draw", function () {
var test = {
- duration: '',
- slow: noop
+ duration: "",
+ slow: noop,
};
var fakeThis = {
draw: sinon.stub().callsFake(noop),
- generateColors: noop
+ generateColors: noop,
};
var runner = createMockRunner(
- 'pass',
+ "pass",
EVENT_TEST_PASS,
null,
null,
- test
+ test,
);
var options = {};
runReporter(fakeThis, runner, options);
- expect(fakeThis.draw.called, 'to be true');
+ expect(fakeThis.draw.called, "to be true");
});
});
describe("on 'fail' event", function () {
- it('should call draw', function () {
+ it("should call draw", function () {
var test = {
- err: ''
+ err: "",
};
var fakeThis = {
draw: sinon.stub().callsFake(noop),
- generateColors: noop
+ generateColors: noop,
};
var runner = createMockRunner(
- 'fail',
+ "fail",
EVENT_TEST_FAIL,
null,
null,
- test
+ test,
);
var options = {};
runReporter(fakeThis, runner, options);
- expect(fakeThis.draw.called, 'to be true');
+ expect(fakeThis.draw.called, "to be true");
});
});
describe("on 'end' event", function () {
- it('should call epilogue', function () {
+ it("should call epilogue", function () {
var fakeThis = {
draw: noop,
epilogue: sinon.stub().callsFake(noop),
- generateColors: noop
+ generateColors: noop,
};
- var runner = createMockRunner('end', EVENT_RUN_END);
+ var runner = createMockRunner("end", EVENT_RUN_END);
var options = {};
runReporter(fakeThis, runner, options);
- expect(fakeThis.epilogue.called, 'to be true');
+ expect(fakeThis.epilogue.called, "to be true");
});
- it('should write numberOfLines amount of newlines', function () {
+ it("should write numberOfLines amount of newlines", function () {
var expectedNumberOfLines = 4;
var fakeThis = {
draw: noop,
epilogue: noop,
- generateColors: noop
+ generateColors: noop,
};
- var runner = createMockRunner('end', EVENT_RUN_END);
+ var runner = createMockRunner("end", EVENT_RUN_END);
var options = {};
var stdout = runReporter(fakeThis, runner, options);
var isBlankLine = function (value) {
- return value === '\n';
+ return value === "\n";
};
expect(
stdout.filter(isBlankLine),
- 'to have length',
- expectedNumberOfLines
+ "to have length",
+ expectedNumberOfLines,
);
});
- it('should call Base show', function () {
- var showCursorStub = sinon.stub(Base.cursor, 'show');
+ it("should call Base show", function () {
+ var showCursorStub = sinon.stub(Base.cursor, "show");
var fakeThis = {
draw: noop,
epilogue: noop,
- generateColors: noop
+ generateColors: noop,
};
- var runner = createMockRunner('end', EVENT_RUN_END);
+ var runner = createMockRunner("end", EVENT_RUN_END);
var options = {};
runReporter(fakeThis, runner, options);
sinon.restore();
- expect(showCursorStub.called, 'to be true');
+ expect(showCursorStub.called, "to be true");
});
});
});
- describe('#draw', function () {
+ describe("#draw", function () {
var stdoutWriteStub;
var stdout;
beforeEach(function () {
- stdoutWriteStub = sinon.stub(process.stdout, 'write');
+ stdoutWriteStub = sinon.stub(process.stdout, "write");
stdoutWriteStub.callsFake(function (chunk) {
stdout.push(chunk);
});
@@ -168,11 +168,11 @@ describe('Nyan reporter', function () {
});
describe("when 'tick' is false", function () {
- it('should draw face with expected spaces, _ and ^', function () {
- var runner = {on: noop, once: noop};
+ it("should draw face with expected spaces, _ and ^", function () {
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
- nyanCat.stats = {passes: 2, pending: 1, failures: 0};
+ nyanCat.stats = { passes: 2, pending: 1, failures: 0 };
var fakeThis = {
tick: false,
appendRainbow: noop,
@@ -183,7 +183,7 @@ describe('Nyan reporter', function () {
scoreboardWidth: 0,
trajectories: [[]],
face: noop,
- cursorUp: noop
+ cursorUp: noop,
};
try {
@@ -193,29 +193,29 @@ describe('Nyan reporter', function () {
}
var expectedArray = [
- '\u001b[0C',
- '_,------,',
- '\n',
- '\u001b[0C',
- '_| /\\_/\\ ',
- '\n',
- '\u001b[0C',
- '^|__undefined ',
- '\n',
- '\u001b[0C',
+ "\u001b[0C",
+ "_,------,",
+ "\n",
+ "\u001b[0C",
+ "_| /\\_/\\ ",
+ "\n",
+ "\u001b[0C",
+ "^|__undefined ",
+ "\n",
+ "\u001b[0C",
' "" "" ',
- '\n'
+ "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
describe("when 'tick' is true", function () {
- it('should draw face with expected spaces, _ and ~', function () {
- var runner = {on: noop, once: noop};
+ it("should draw face with expected spaces, _ and ~", function () {
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
- nyanCat.stats = {passes: 2, pending: 1, failures: 0};
+ nyanCat.stats = { passes: 2, pending: 1, failures: 0 };
var fakeThis = {
tick: true,
appendRainbow: noop,
@@ -226,7 +226,7 @@ describe('Nyan reporter', function () {
scoreboardWidth: 0,
trajectories: [[]],
face: noop,
- cursorUp: noop
+ cursorUp: noop,
};
try {
@@ -236,38 +236,38 @@ describe('Nyan reporter', function () {
}
var expectedArray = [
- '\u001b[0C',
- '_,------,',
- '\n',
- '\u001b[0C',
- '_| /\\_/\\ ',
- '\n',
- '\u001b[0C',
- '~|_undefined ',
- '\n',
- '\u001b[0C',
+ "\u001b[0C",
+ "_,------,",
+ "\n",
+ "\u001b[0C",
+ "_| /\\_/\\ ",
+ "\n",
+ "\u001b[0C",
+ "~|_undefined ",
+ "\n",
+ "\u001b[0C",
' "" "" ',
- '\n'
+ "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
});
- describe('#cursorDown', function () {
+ describe("#cursorDown", function () {
var stdoutWriteStub;
var stdout;
beforeEach(function () {
- stdoutWriteStub = sinon.stub(process.stdout, 'write');
+ stdoutWriteStub = sinon.stub(process.stdout, "write");
stdoutWriteStub.callsFake(function (chunk) {
stdout.push(chunk);
});
stdout = [];
});
- it('should write cursor down interaction with expected number', function () {
- var runner = {on: noop, once: noop};
+ it("should write cursor down interaction with expected number", function () {
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
var expectedNumber = 25;
@@ -278,25 +278,25 @@ describe('Nyan reporter', function () {
sinon.restore();
}
- var expectedArray = ['\u001b[' + expectedNumber + 'B'];
- expect(stdout, 'to equal', expectedArray);
+ var expectedArray = ["\u001b[" + expectedNumber + "B"];
+ expect(stdout, "to equal", expectedArray);
});
});
- describe('#cursorUp', function () {
+ describe("#cursorUp", function () {
var stdoutWriteStub;
var stdout;
beforeEach(function () {
- stdoutWriteStub = sinon.stub(process.stdout, 'write');
+ stdoutWriteStub = sinon.stub(process.stdout, "write");
stdoutWriteStub.callsFake(function (chunk) {
stdout.push(chunk);
});
stdout = [];
});
- it('should write cursor up interaction with expected number', function () {
- var runner = {on: noop, once: noop};
+ it("should write cursor up interaction with expected number", function () {
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
var expectedNumber = 25;
@@ -307,16 +307,16 @@ describe('Nyan reporter', function () {
sinon.restore();
}
- var expectedArray = ['\u001b[' + expectedNumber + 'A'];
- expect(stdout, 'to equal', expectedArray);
+ var expectedArray = ["\u001b[" + expectedNumber + "A"];
+ expect(stdout, "to equal", expectedArray);
});
});
- describe('#rainbowify', function () {
+ describe("#rainbowify", function () {
var useColorsStub;
beforeEach(function () {
- useColorsStub = sinon.stub(Base, 'useColors');
+ useColorsStub = sinon.stub(Base, "useColors");
});
afterEach(function () {
@@ -328,17 +328,17 @@ describe('Nyan reporter', function () {
useColorsStub.value(false);
});
- it('should return argument string', function () {
- var runner = {on: noop, once: noop};
+ it("should return argument string", function () {
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
- var inputString = 'hello';
+ var inputString = "hello";
var outputString = nyanCat.rainbowify(inputString);
sinon.restore();
var expectedString = inputString;
- expect(outputString, 'to be', expectedString);
+ expect(outputString, "to be", expectedString);
});
});
@@ -347,33 +347,33 @@ describe('Nyan reporter', function () {
useColorsStub.value(true);
});
- it('should return rainbowified string from the given string and predefined codes', function () {
- var runner = {on: noop, once: noop};
+ it("should return rainbowified string from the given string and predefined codes", function () {
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
- var inputString = 'hello';
- var colorCode = 'somecode';
+ var inputString = "hello";
+ var colorCode = "somecode";
var fakeThis = {
rainbowColors: [colorCode],
- colorIndex: 0
+ colorIndex: 0,
};
var outputString = nyanCat.rainbowify.call(fakeThis, inputString);
sinon.restore();
- var startCode = '\u001b[38;5;';
- var endCode = '\u001b[0m';
+ var startCode = "\u001b[38;5;";
+ var endCode = "\u001b[0m";
var expectedString =
- startCode + colorCode + 'm' + inputString + endCode;
- expect(outputString, 'to be', expectedString);
+ startCode + colorCode + "m" + inputString + endCode;
+ expect(outputString, "to be", expectedString);
});
});
});
- describe('#appendRainbow', function () {
+ describe("#appendRainbow", function () {
describe("when 'tick' is true", function () {
- it('should set an underscore segment', function () {
- var runner = {on: noop, once: noop};
+ it("should set an underscore segment", function () {
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
var expectedSegment;
@@ -386,26 +386,26 @@ describe('Nyan reporter', function () {
},
numberOfLines: 4,
trajectoryWidthMax: 0,
- trajectories
+ trajectories,
});
- expect(expectedSegment, 'to be', '_');
+ expect(expectedSegment, "to be", "_");
});
- it('should shift each trajectory item if its length is greater than or equal to its max width', function () {
- var runner = {on: noop, once: noop};
+ it("should shift each trajectory item if its length is greater than or equal to its max width", function () {
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
- var rainbowifyResult = 'rainbowify';
- var inputArray = ['itemToShify'];
+ var rainbowifyResult = "rainbowify";
+ var inputArray = ["itemToShify"];
var trajectories = [inputArray, inputArray, inputArray, inputArray];
var expectedArray = [rainbowifyResult];
var expectedTrajectories = [
expectedArray,
expectedArray,
expectedArray,
- expectedArray
+ expectedArray,
];
nyanCat.appendRainbow.call({
tick: true,
@@ -414,16 +414,16 @@ describe('Nyan reporter', function () {
},
numberOfLines: 4,
trajectoryWidthMax: 0,
- trajectories
+ trajectories,
});
- expect(trajectories, 'to equal', expectedTrajectories);
+ expect(trajectories, "to equal", expectedTrajectories);
});
});
describe("when 'tick' is false", function () {
- it('should set a dash segment', function () {
- var runner = {on: noop, once: noop};
+ it("should set a dash segment", function () {
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
var expectedSegment;
@@ -436,30 +436,30 @@ describe('Nyan reporter', function () {
},
numberOfLines: 4,
trajectoryWidthMax: 5,
- trajectories
+ trajectories,
});
- expect(expectedSegment, 'to equal', '-');
+ expect(expectedSegment, "to equal", "-");
});
});
});
- describe('#drawScoreboard', function () {
+ describe("#drawScoreboard", function () {
var stdout;
beforeEach(function () {
- sinon.stub(Base, 'color').callsFake(function (type, n) {
+ sinon.stub(Base, "color").callsFake(function (type, n) {
return type + n;
});
- var stdoutWriteStub = sinon.stub(process.stdout, 'write');
+ var stdoutWriteStub = sinon.stub(process.stdout, "write");
stdoutWriteStub.callsFake(function (chunk) {
stdout.push(chunk);
});
stdout = [];
});
- it('should write scoreboard with color set with each stat', function () {
- var runner = {on: noop, once: noop};
+ it("should write scoreboard with color set with each stat", function () {
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
@@ -469,8 +469,8 @@ describe('Nyan reporter', function () {
var fakeThis = {
cursorUp: noop,
- stats: {passes, pending, failures},
- numberOfLines: 4
+ stats: { passes, pending, failures },
+ numberOfLines: 4,
};
try {
@@ -480,30 +480,30 @@ describe('Nyan reporter', function () {
}
var expectedArray = [
- ' ',
- 'green' + passes,
- '\n',
- ' ',
- 'fail' + failures,
- '\n',
- ' ',
- 'pending' + pending,
- '\n',
- '\n'
+ " ",
+ "green" + passes,
+ "\n",
+ " ",
+ "fail" + failures,
+ "\n",
+ " ",
+ "pending" + pending,
+ "\n",
+ "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
- it('should call cursorUp with given numberOfLines', function () {
+ it("should call cursorUp with given numberOfLines", function () {
var expectedNumberOfLines = 1000;
- var runner = {on: noop, once: noop};
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
var fakeThis = {
cursorUp: sinon.spy(),
- stats: {passes: 0, pending: 0, failures: 0},
- numberOfLines: expectedNumberOfLines
+ stats: { passes: 0, pending: 0, failures: 0 },
+ numberOfLines: expectedNumberOfLines,
};
try {
@@ -512,35 +512,35 @@ describe('Nyan reporter', function () {
sinon.restore();
}
- expect(fakeThis.cursorUp.calledWith(expectedNumberOfLines), 'to be true');
+ expect(fakeThis.cursorUp.calledWith(expectedNumberOfLines), "to be true");
});
});
- describe('#drawRainbow', function () {
+ describe("#drawRainbow", function () {
var stdout;
beforeEach(function () {
- var stdoutWriteStub = sinon.stub(process.stdout, 'write');
+ var stdoutWriteStub = sinon.stub(process.stdout, "write");
stdoutWriteStub.callsFake(function (chunk) {
stdout.push(chunk);
});
stdout = [];
});
- it('should write width, contents and newline for each trajectory', function () {
+ it("should write width, contents and newline for each trajectory", function () {
var expectedWidth = 444;
- var expectedContents = 'input';
+ var expectedContents = "input";
var inputArray = [expectedContents];
var trajectories = [inputArray];
- var runner = {on: noop, once: noop};
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
var fakeThis = {
cursorUp: noop,
trajectories,
scoreboardWidth: expectedWidth,
- numberOfLines: 1
+ numberOfLines: 1,
};
try {
@@ -550,27 +550,27 @@ describe('Nyan reporter', function () {
}
var expectedArray = [
- '\u001b[' + expectedWidth + 'C',
+ "\u001b[" + expectedWidth + "C",
expectedContents,
- '\n'
+ "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
- it('should call cursorUp with given numberOfLines', function () {
+ it("should call cursorUp with given numberOfLines", function () {
var expectedCursorArgument = null;
var expectedNumberOfLines = 1000;
- var runner = {on: noop, once: noop};
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
var fakeThis = {
cursorUp: function (lines) {
expectedCursorArgument = lines;
},
- trajectories: [['input']],
+ trajectories: [["input"]],
scoreboardWidth: 1,
- numberOfLines: expectedNumberOfLines
+ numberOfLines: expectedNumberOfLines,
};
try {
@@ -579,45 +579,45 @@ describe('Nyan reporter', function () {
sinon.restore();
}
- expect(expectedCursorArgument, 'to be', expectedNumberOfLines);
+ expect(expectedCursorArgument, "to be", expectedNumberOfLines);
});
});
- describe('#face', function () {
+ describe("#face", function () {
it('should expect "( x .x)" if any failures', function () {
- var runner = {on: noop, once: noop};
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
- nyanCat.stats = {passes: 2, pending: 1, failures: 1};
+ nyanCat.stats = { passes: 2, pending: 1, failures: 1 };
- expect(nyanCat.face(), 'to be', '( x .x)');
+ expect(nyanCat.face(), "to be", "( x .x)");
});
it('should expect "( o .o)" if any pending but none failing', function () {
- var runner = {on: noop, once: noop};
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
- nyanCat.stats = {passes: 2, pending: 1, failures: 0};
+ nyanCat.stats = { passes: 2, pending: 1, failures: 0 };
- expect(nyanCat.face(), 'to be', '( o .o)');
+ expect(nyanCat.face(), "to be", "( o .o)");
});
it('should expect "( ^ .^)" if all passing', function () {
- var runner = {on: noop, once: noop};
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
- nyanCat.stats = {passes: 1, pending: 0, failures: 0};
+ nyanCat.stats = { passes: 1, pending: 0, failures: 0 };
- expect(nyanCat.face(), 'to be', '( ^ .^)');
+ expect(nyanCat.face(), "to be", "( ^ .^)");
});
it('should expect "( - .-)" otherwise', function (done) {
- var runner = {on: noop, once: noop};
+ var runner = { on: noop, once: noop };
var options = {};
var nyanCat = new NyanCat(runner, options);
- nyanCat.stats = {passes: 0, pending: 0, failures: 0};
+ nyanCat.stats = { passes: 0, pending: 0, failures: 0 };
- expect(nyanCat.face(), 'to be', '( - .-)');
+ expect(nyanCat.face(), "to be", "( - .-)");
done();
});
});
diff --git a/test/reporters/progress.spec.js b/test/reporters/progress.spec.js
index a0c593e2..b4ee7a57 100644
--- a/test/reporters/progress.spec.js
+++ b/test/reporters/progress.spec.js
@@ -1,9 +1,9 @@
-'use strict';
+"use strict";
-var sinon = require('sinon');
-var events = require('../../').Runner.constants;
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
+var sinon = require("sinon");
+var events = require("../../").Runner.constants;
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
var Base = reporters.Base;
var Progress = reporters.Progress;
@@ -14,7 +14,7 @@ var EVENT_RUN_BEGIN = events.EVENT_RUN_BEGIN;
var EVENT_RUN_END = events.EVENT_RUN_END;
var EVENT_TEST_END = events.EVENT_TEST_END;
-describe('Progress reporter', function () {
+describe("Progress reporter", function () {
var runReporter = makeRunReporter(Progress);
var noop = function () {};
@@ -22,90 +22,90 @@ describe('Progress reporter', function () {
sinon.restore();
});
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'start' event", function () {
- it('should call cursor hide', function () {
- var hideCursorStub = sinon.stub(Base.cursor, 'hide');
+ it("should call cursor hide", function () {
+ var hideCursorStub = sinon.stub(Base.cursor, "hide");
- var runner = createMockRunner('start', EVENT_RUN_BEGIN);
+ var runner = createMockRunner("start", EVENT_RUN_BEGIN);
var options = {};
runReporter({}, runner, options);
sinon.restore();
- expect(hideCursorStub.called, 'to be true');
+ expect(hideCursorStub.called, "to be true");
});
});
describe("on 'test end' event", function () {
- describe('when line has changed', function () {
- it('should write expected progress of open and close options', function () {
- var crCursorStub = sinon.stub(Base.cursor, 'CR').callsFake(noop);
- sinon.stub(Base, 'useColors').value(false);
- sinon.stub(Base.window, 'width').value(5);
+ describe("when line has changed", function () {
+ it("should write expected progress of open and close options", function () {
+ var crCursorStub = sinon.stub(Base.cursor, "CR").callsFake(noop);
+ sinon.stub(Base, "useColors").value(false);
+ sinon.stub(Base.window, "width").value(5);
var expectedTotal = 12;
- var expectedOpen = 'OpEn';
- var expectedClose = 'cLoSe';
- var expectedIncomplete = 'iNcOmPlEtE';
+ var expectedOpen = "OpEn";
+ var expectedClose = "cLoSe";
+ var expectedIncomplete = "iNcOmPlEtE";
var expectedOptions = {
open: expectedOpen,
- complete: 'cOmPlEtE',
+ complete: "cOmPlEtE",
incomplete: expectedIncomplete,
- close: expectedClose
+ close: expectedClose,
};
- var runner = createMockRunner('test end', EVENT_TEST_END);
+ var runner = createMockRunner("test end", EVENT_TEST_END);
runner.total = expectedTotal;
var options = {
- reporterOptions: expectedOptions
+ reporterOptions: expectedOptions,
};
var stdout = runReporter({}, runner, options);
sinon.restore();
var expectedArray = [
- '\u001b[J',
- ' ' + expectedOpen,
- '',
+ "\u001b[J",
+ " " + expectedOpen,
+ "",
expectedIncomplete,
- expectedClose
+ expectedClose,
];
- expect(crCursorStub.called, 'to be true');
- expect(stdout, 'to equal', expectedArray);
+ expect(crCursorStub.called, "to be true");
+ expect(stdout, "to equal", expectedArray);
});
});
- describe('when line has not changed', function () {
- it('should not write anything', function () {
- sinon.stub(Base, 'useColors').value(false);
- sinon.stub(Base.cursor, 'CR').callsFake(noop);
- sinon.stub(Base.window, 'width').value(-3);
+ describe("when line has not changed", function () {
+ it("should not write anything", function () {
+ sinon.stub(Base, "useColors").value(false);
+ sinon.stub(Base.cursor, "CR").callsFake(noop);
+ sinon.stub(Base.window, "width").value(-3);
var expectedTotal = 1;
- var runner = createMockRunner('test end', EVENT_TEST_END);
+ var runner = createMockRunner("test end", EVENT_TEST_END);
runner.total = expectedTotal;
var options = {};
var stdout = runReporter({}, runner, options);
sinon.restore();
- expect(stdout, 'to equal', []);
+ expect(stdout, "to equal", []);
});
});
});
describe("on 'end' event", function () {
- it('should call cursor show and epilogue', function () {
- var showCursorStub = sinon.stub(Base.cursor, 'show');
+ it("should call cursor show and epilogue", function () {
+ var showCursorStub = sinon.stub(Base.cursor, "show");
var fakeThis = {
- epilogue: sinon.spy()
+ epilogue: sinon.spy(),
};
- var runner = createMockRunner('end', EVENT_RUN_END);
+ var runner = createMockRunner("end", EVENT_RUN_END);
var options = {};
runReporter(fakeThis, runner, options);
sinon.restore();
- expect(fakeThis.epilogue.calledOnce, 'to be true');
- expect(showCursorStub.called, 'to be true');
+ expect(fakeThis.epilogue.calledOnce, "to be true");
+ expect(showCursorStub.called, "to be true");
});
});
});
diff --git a/test/reporters/spec.spec.js b/test/reporters/spec.spec.js
index 39115ffa..1a0dacdf 100644
--- a/test/reporters/spec.spec.js
+++ b/test/reporters/spec.spec.js
@@ -1,9 +1,9 @@
-'use strict';
+"use strict";
-var sinon = require('sinon');
-var events = require('../../').Runner.constants;
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
+var sinon = require("sinon");
+var events = require("../../").Runner.constants;
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
var Base = reporters.Base;
var Spec = reporters.Spec;
@@ -15,146 +15,146 @@ var EVENT_TEST_FAIL = events.EVENT_TEST_FAIL;
var EVENT_TEST_PASS = events.EVENT_TEST_PASS;
var EVENT_TEST_PENDING = events.EVENT_TEST_PENDING;
-describe('Spec reporter', function () {
+describe("Spec reporter", function () {
var runReporter = makeRunReporter(Spec);
- var expectedTitle = 'expectedTitle';
+ var expectedTitle = "expectedTitle";
var noop = function () {};
beforeEach(function () {
- sinon.stub(Base, 'useColors').value(false);
+ sinon.stub(Base, "useColors").value(false);
});
afterEach(function () {
sinon.restore();
});
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'suite' event", function () {
- it('should return title', function () {
+ it("should return title", function () {
var suite = {
- title: expectedTitle
+ title: expectedTitle,
};
var runner = createMockRunner(
- 'suite',
+ "suite",
EVENT_SUITE_BEGIN,
null,
null,
- suite
+ suite,
);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
- var expectedArray = [expectedTitle + '\n'];
- expect(stdout, 'to equal', expectedArray);
+ var expectedArray = [expectedTitle + "\n"];
+ expect(stdout, "to equal", expectedArray);
});
});
describe("on 'pending' event", function () {
- it('should return title', function () {
+ it("should return title", function () {
var suite = {
- title: expectedTitle
+ title: expectedTitle,
};
var runner = createMockRunner(
- 'pending test',
+ "pending test",
EVENT_TEST_PENDING,
null,
null,
- suite
+ suite,
);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
- var expectedArray = [' - ' + expectedTitle + '\n'];
- expect(stdout, 'to equal', expectedArray);
+ var expectedArray = [" - " + expectedTitle + "\n"];
+ expect(stdout, "to equal", expectedArray);
});
});
describe("on 'pass' event", function () {
- describe('when test speed is slow', function () {
- it('should return expected tick, title, and duration', function () {
+ describe("when test speed is slow", function () {
+ it("should return expected tick, title, and duration", function () {
var expectedDuration = 2;
var test = {
title: expectedTitle,
duration: expectedDuration,
slow: function () {
return 1;
- }
+ },
};
var runner = createMockRunner(
- 'pass',
+ "pass",
EVENT_TEST_PASS,
null,
null,
- test
+ test,
);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
var expectedString =
- ' ' +
+ " " +
Base.symbols.ok +
- ' ' +
+ " " +
expectedTitle +
- ' (' +
+ " (" +
expectedDuration +
- 'ms)' +
- '\n';
- expect(stdout[0], 'to be', expectedString);
+ "ms)" +
+ "\n";
+ expect(stdout[0], "to be", expectedString);
});
});
- describe('when test speed is fast', function () {
- it('should return expected tick, title without a duration', function () {
+ describe("when test speed is fast", function () {
+ it("should return expected tick, title without a duration", function () {
var expectedDuration = 1;
var test = {
title: expectedTitle,
duration: expectedDuration,
slow: function () {
return 2;
- }
+ },
};
var runner = createMockRunner(
- 'pass',
+ "pass",
EVENT_TEST_PASS,
null,
null,
- test
+ test,
);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
var expectedString =
- ' ' + Base.symbols.ok + ' ' + expectedTitle + '\n';
- expect(stdout[0], 'to be', expectedString);
+ " " + Base.symbols.ok + " " + expectedTitle + "\n";
+ expect(stdout[0], "to be", expectedString);
});
});
});
describe("on 'fail' event", function () {
- it('should return title and function count', function () {
+ it("should return title and function count", function () {
var functionCount = 1;
var test = {
- title: expectedTitle
+ title: expectedTitle,
};
var runner = createMockRunner(
- 'fail',
+ "fail",
EVENT_TEST_FAIL,
null,
null,
- test
+ test,
);
var options = {};
- var stdout = runReporter({epilogue: noop}, runner, options);
+ var stdout = runReporter({ epilogue: noop }, runner, options);
sinon.restore();
var expectedArray = [
- ' ' + functionCount + ') ' + expectedTitle + '\n'
+ " " + functionCount + ") " + expectedTitle + "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
});
diff --git a/test/reporters/tap.spec.js b/test/reporters/tap.spec.js
index 9e341e84..fdd2ced2 100644
--- a/test/reporters/tap.spec.js
+++ b/test/reporters/tap.spec.js
@@ -1,8 +1,8 @@
-'use strict';
+"use strict";
-var events = require('../../').Runner.constants;
-var helpers = require('./helpers');
-var reporters = require('../../').reporters;
+var events = require("../../").Runner.constants;
+var helpers = require("./helpers");
+var reporters = require("../../").reporters;
var TAP = reporters.TAP;
var createMockRunner = helpers.createMockRunner;
@@ -15,9 +15,9 @@ var EVENT_TEST_FAIL = events.EVENT_TEST_FAIL;
var EVENT_TEST_PASS = events.EVENT_TEST_PASS;
var EVENT_TEST_PENDING = events.EVENT_TEST_PENDING;
-describe('TAP reporter', function () {
+describe("TAP reporter", function () {
var runReporter = makeRunReporter(TAP);
- var expectedTitle = 'some title';
+ var expectedTitle = "some title";
var countAfterTestEnd = 2;
var noop = function () {};
@@ -26,30 +26,30 @@ describe('TAP reporter', function () {
fullTitle: function () {
return expectedTitle;
},
- slow: noop
+ slow: noop,
};
}
- describe('TAP12 spec', function () {
+ describe("TAP12 spec", function () {
var options = {
reporterOptions: {
- tapVersion: '12'
- }
+ tapVersion: "12",
+ },
};
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'start' event", function () {
- var expectedSuite = 'some suite';
+ var expectedSuite = "some suite";
var stdout = [];
before(function () {
- var runner = createMockRunner('start', EVENT_RUN_BEGIN);
+ var runner = createMockRunner("start", EVENT_RUN_BEGIN);
runner.suite = expectedSuite;
stdout = runReporter({}, runner, options);
});
- it('should not write a TAP specification version', function () {
- expect(stdout, 'not to contain', 'TAP version');
+ it("should not write a TAP specification version", function () {
+ expect(stdout, "not to contain", "TAP version");
});
});
@@ -59,20 +59,20 @@ describe('TAP reporter', function () {
before(function () {
var test = createTest();
var runner = createMockRunner(
- 'start test',
+ "start test",
EVENT_TEST_END,
EVENT_TEST_PENDING,
null,
- test
+ test,
);
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message including count and title', function () {
+ it("should write expected message including count and title", function () {
var expectedMessage =
- 'ok ' + countAfterTestEnd + ' ' + expectedTitle + ' # SKIP -\n';
- expect(stdout[0], 'to equal', expectedMessage);
+ "ok " + countAfterTestEnd + " " + expectedTitle + " # SKIP -\n";
+ expect(stdout[0], "to equal", expectedMessage);
});
});
@@ -82,26 +82,26 @@ describe('TAP reporter', function () {
before(function () {
var test = createTest();
var runner = createMockRunner(
- 'start test',
+ "start test",
EVENT_TEST_END,
EVENT_TEST_PASS,
null,
- test
+ test,
);
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message including count and title', function () {
+ it("should write expected message including count and title", function () {
var expectedMessage =
- 'ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n';
- expect(stdout[0], 'to equal', expectedMessage);
+ "ok " + countAfterTestEnd + " " + expectedTitle + "\n";
+ expect(stdout[0], "to equal", expectedMessage);
});
});
describe("on 'fail' event", function () {
- var expectedErrorMessage = 'some error';
- var expectedStack = 'some stack';
+ var expectedErrorMessage = "some error";
+ var expectedStack = "some stack";
describe("when 'error' has only message", function () {
var stdout;
@@ -109,15 +109,15 @@ describe('TAP reporter', function () {
before(function () {
var test = createTest();
var error = {
- message: expectedErrorMessage
+ message: expectedErrorMessage,
};
var runner = createMockRunner(
- 'test end fail',
+ "test end fail",
EVENT_TEST_END,
EVENT_TEST_FAIL,
null,
test,
- error
+ error,
);
runner.on = function (event, callback) {
if (event === EVENT_TEST_END) {
@@ -126,16 +126,16 @@ describe('TAP reporter', function () {
callback(test, error);
}
};
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message and error message', function () {
+ it("should write expected message and error message", function () {
var expectedArray = [
- 'not ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n',
- ' ' + expectedErrorMessage + '\n'
+ "not ok " + countAfterTestEnd + " " + expectedTitle + "\n",
+ " " + expectedErrorMessage + "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
@@ -145,26 +145,26 @@ describe('TAP reporter', function () {
before(function () {
var test = createTest();
var error = {
- stack: expectedStack
+ stack: expectedStack,
};
var runner = createMockRunner(
- 'test end fail',
+ "test end fail",
EVENT_TEST_END,
EVENT_TEST_FAIL,
null,
test,
- error
+ error,
);
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message and stack', function () {
+ it("should write expected message and stack", function () {
var expectedArray = [
- 'not ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n',
- ' ' + expectedStack + '\n'
+ "not ok " + countAfterTestEnd + " " + expectedTitle + "\n",
+ " " + expectedStack + "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
@@ -175,15 +175,15 @@ describe('TAP reporter', function () {
var test = createTest();
var error = {
stack: expectedStack,
- message: expectedErrorMessage
+ message: expectedErrorMessage,
};
var runner = createMockRunner(
- 'test end fail',
+ "test end fail",
EVENT_TEST_END,
EVENT_TEST_FAIL,
null,
test,
- error
+ error,
);
runner.on = function (event, callback) {
if (event === EVENT_TEST_END) {
@@ -192,17 +192,17 @@ describe('TAP reporter', function () {
callback(test, error);
}
};
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message, error message, and stack', function () {
+ it("should write expected message, error message, and stack", function () {
var expectedArray = [
- 'not ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n',
- ' ' + expectedErrorMessage + '\n',
- ' ' + expectedStack + '\n'
+ "not ok " + countAfterTestEnd + " " + expectedTitle + "\n",
+ " " + expectedErrorMessage + "\n",
+ " " + expectedStack + "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
@@ -213,12 +213,12 @@ describe('TAP reporter', function () {
var test = createTest();
var error = {};
var runner = createMockRunner(
- 'test end fail',
+ "test end fail",
EVENT_TEST_END,
EVENT_TEST_FAIL,
null,
test,
- error
+ error,
);
runner.on = runner.once = function (event, callback) {
if (event === EVENT_TEST_END) {
@@ -227,15 +227,15 @@ describe('TAP reporter', function () {
callback(test, error);
}
};
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message only', function () {
+ it("should write expected message only", function () {
var expectedArray = [
- 'not ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n'
+ "not ok " + countAfterTestEnd + " " + expectedTitle + "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
});
@@ -246,56 +246,56 @@ describe('TAP reporter', function () {
before(function () {
var test = createTest();
var runner = createMockRunner(
- 'fail end pass',
+ "fail end pass",
EVENT_TEST_FAIL,
EVENT_RUN_END,
EVENT_TEST_PASS,
- test
+ test,
);
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write total tests, passes, failures, & plan', function () {
+ it("should write total tests, passes, failures, & plan", function () {
var numberOfPasses = 1;
var numberOfFails = 1;
var totalTests = numberOfPasses + numberOfFails;
var expectedArray = [
- 'ok ' + numberOfPasses + ' ' + expectedTitle + '\n',
- 'not ok ' + numberOfFails + ' ' + expectedTitle + '\n',
- '# tests ' + totalTests + '\n',
- '# pass ' + numberOfPasses + '\n',
- '# fail ' + numberOfFails + '\n',
- '1..' + totalTests + '\n'
+ "ok " + numberOfPasses + " " + expectedTitle + "\n",
+ "not ok " + numberOfFails + " " + expectedTitle + "\n",
+ "# tests " + totalTests + "\n",
+ "# pass " + numberOfPasses + "\n",
+ "# fail " + numberOfFails + "\n",
+ "1.." + totalTests + "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
});
});
- describe('TAP13 spec', function () {
+ describe("TAP13 spec", function () {
var options = {
reporterOptions: {
- tapVersion: '13'
- }
+ tapVersion: "13",
+ },
};
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'start' event", function () {
- var expectedSuite = 'some suite';
+ var expectedSuite = "some suite";
var stdout;
before(function () {
- var runner = createMockRunner('start', EVENT_RUN_BEGIN);
+ var runner = createMockRunner("start", EVENT_RUN_BEGIN);
runner.suite = expectedSuite;
stdout = runReporter({}, runner, options);
});
- it('should write the TAP specification version', function () {
+ it("should write the TAP specification version", function () {
var tapVersion = options.reporterOptions.tapVersion;
- var expectedFirstLine = 'TAP version ' + tapVersion + '\n';
- expect(stdout[0], 'to equal', expectedFirstLine);
+ var expectedFirstLine = "TAP version " + tapVersion + "\n";
+ expect(stdout[0], "to equal", expectedFirstLine);
});
});
@@ -305,20 +305,20 @@ describe('TAP reporter', function () {
before(function () {
var test = createTest();
var runner = createMockRunner(
- 'start test',
+ "start test",
EVENT_TEST_END,
EVENT_TEST_PENDING,
null,
- test
+ test,
);
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message including count and title', function () {
+ it("should write expected message including count and title", function () {
var expectedMessage =
- 'ok ' + countAfterTestEnd + ' ' + expectedTitle + ' # SKIP -\n';
- expect(stdout[0], 'to equal', expectedMessage);
+ "ok " + countAfterTestEnd + " " + expectedTitle + " # SKIP -\n";
+ expect(stdout[0], "to equal", expectedMessage);
});
});
@@ -328,26 +328,26 @@ describe('TAP reporter', function () {
before(function () {
var test = createTest();
var runner = createMockRunner(
- 'start test',
+ "start test",
EVENT_TEST_END,
EVENT_TEST_PASS,
null,
- test
+ test,
);
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message including count and title', function () {
+ it("should write expected message including count and title", function () {
var expectedMessage =
- 'ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n';
- expect(stdout[0], 'to equal', expectedMessage);
+ "ok " + countAfterTestEnd + " " + expectedTitle + "\n";
+ expect(stdout[0], "to equal", expectedMessage);
});
});
describe("on 'fail' event", function () {
- var expectedErrorMessage = 'some error';
- var expectedStack = 'some stack';
+ var expectedErrorMessage = "some error";
+ var expectedStack = "some stack";
describe("when 'error' has only message", function () {
var stdout;
@@ -355,15 +355,15 @@ describe('TAP reporter', function () {
before(function () {
var test = createTest();
var error = {
- message: expectedErrorMessage
+ message: expectedErrorMessage,
};
var runner = createMockRunner(
- 'test end fail',
+ "test end fail",
EVENT_TEST_END,
EVENT_TEST_FAIL,
null,
test,
- error
+ error,
);
runner.on = function (event, callback) {
if (event === EVENT_TEST_END) {
@@ -372,19 +372,19 @@ describe('TAP reporter', function () {
callback(test, error);
}
};
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message and error message', function () {
+ it("should write expected message and error message", function () {
var expectedArray = [
- 'not ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n',
- ' ---\n',
- ' message: |-\n',
- ' ' + expectedErrorMessage + '\n',
- ' ...\n'
+ "not ok " + countAfterTestEnd + " " + expectedTitle + "\n",
+ " ---\n",
+ " message: |-\n",
+ " " + expectedErrorMessage + "\n",
+ " ...\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
@@ -394,29 +394,29 @@ describe('TAP reporter', function () {
before(function () {
var test = createTest();
var error = {
- stack: expectedStack
+ stack: expectedStack,
};
var runner = createMockRunner(
- 'test end fail',
+ "test end fail",
EVENT_TEST_END,
EVENT_TEST_FAIL,
null,
test,
- error
+ error,
);
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message and stack', function () {
+ it("should write expected message and stack", function () {
var expectedArray = [
- 'not ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n',
- ' ---\n',
- ' stack: |-\n',
- ' ' + expectedStack + '\n',
- ' ...\n'
+ "not ok " + countAfterTestEnd + " " + expectedTitle + "\n",
+ " ---\n",
+ " stack: |-\n",
+ " " + expectedStack + "\n",
+ " ...\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
@@ -427,15 +427,15 @@ describe('TAP reporter', function () {
var test = createTest();
var error = {
stack: expectedStack,
- message: expectedErrorMessage
+ message: expectedErrorMessage,
};
var runner = createMockRunner(
- 'test end fail',
+ "test end fail",
EVENT_TEST_END,
EVENT_TEST_FAIL,
null,
test,
- error
+ error,
);
runner.on = function (event, callback) {
if (event === EVENT_TEST_END) {
@@ -444,21 +444,21 @@ describe('TAP reporter', function () {
callback(test, error);
}
};
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message, error message, and stack', function () {
+ it("should write expected message, error message, and stack", function () {
var expectedArray = [
- 'not ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n',
- ' ---\n',
- ' message: |-\n',
- ' ' + expectedErrorMessage + '\n',
- ' stack: |-\n',
- ' ' + expectedStack + '\n',
- ' ...\n'
+ "not ok " + countAfterTestEnd + " " + expectedTitle + "\n",
+ " ---\n",
+ " message: |-\n",
+ " " + expectedErrorMessage + "\n",
+ " stack: |-\n",
+ " " + expectedStack + "\n",
+ " ...\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
@@ -469,12 +469,12 @@ describe('TAP reporter', function () {
var test = createTest();
var error = {};
var runner = createMockRunner(
- 'test end fail',
+ "test end fail",
EVENT_TEST_END,
EVENT_TEST_FAIL,
null,
test,
- error
+ error,
);
runner.on = runner.once = function (event, callback) {
if (event === EVENT_TEST_END) {
@@ -483,15 +483,15 @@ describe('TAP reporter', function () {
callback(test, error);
}
};
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write expected message only', function () {
+ it("should write expected message only", function () {
var expectedArray = [
- 'not ok ' + countAfterTestEnd + ' ' + expectedTitle + '\n'
+ "not ok " + countAfterTestEnd + " " + expectedTitle + "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
});
@@ -502,29 +502,29 @@ describe('TAP reporter', function () {
before(function () {
var test = createTest();
var runner = createMockRunner(
- 'fail end pass',
+ "fail end pass",
EVENT_TEST_FAIL,
EVENT_RUN_END,
EVENT_TEST_PASS,
- test
+ test,
);
- runner.suite = '';
+ runner.suite = "";
stdout = runReporter({}, runner, options);
});
- it('should write total tests, passes, failures & plan', function () {
+ it("should write total tests, passes, failures & plan", function () {
var numberOfPasses = 1;
var numberOfFails = 1;
var totalTests = numberOfPasses + numberOfFails;
var expectedArray = [
- 'ok ' + numberOfPasses + ' ' + expectedTitle + '\n',
- 'not ok ' + numberOfFails + ' ' + expectedTitle + '\n',
- '# tests ' + totalTests + '\n',
- '# pass ' + numberOfPasses + '\n',
- '# fail ' + numberOfFails + '\n',
- '1..' + totalTests + '\n'
+ "ok " + numberOfPasses + " " + expectedTitle + "\n",
+ "not ok " + numberOfFails + " " + expectedTitle + "\n",
+ "# tests " + totalTests + "\n",
+ "# pass " + numberOfPasses + "\n",
+ "# fail " + numberOfFails + "\n",
+ "1.." + totalTests + "\n",
];
- expect(stdout, 'to equal', expectedArray);
+ expect(stdout, "to equal", expectedArray);
});
});
});
diff --git a/test/reporters/xunit.spec.js b/test/reporters/xunit.spec.js
index e00ee9ec..e291a2ec 100644
--- a/test/reporters/xunit.spec.js
+++ b/test/reporters/xunit.spec.js
@@ -1,15 +1,15 @@
-'use strict';
+"use strict";
-var EventEmitter = require('node:events').EventEmitter;
-var fs = require('node:fs');
-var path = require('node:path');
-var sinon = require('sinon');
-var createStatsCollector = require('../../lib/stats-collector');
-var events = require('../../').Runner.constants;
-var reporters = require('../../').reporters;
-var states = require('../../').Runnable.constants;
+var EventEmitter = require("node:events").EventEmitter;
+var fs = require("node:fs");
+var path = require("node:path");
+var sinon = require("sinon");
+var createStatsCollector = require("../../lib/stats-collector");
+var events = require("../../").Runner.constants;
+var reporters = require("../../").reporters;
+var states = require("../../").Runnable.constants;
-const {createTempDir, touchFile} = require('../integration/helpers');
+const { createTempDir, touchFile } = require("../integration/helpers");
var Base = reporters.Base;
var XUnit = reporters.XUnit;
@@ -23,56 +23,56 @@ var EVENT_TEST_PENDING = events.EVENT_TEST_PENDING;
var STATE_FAILED = states.STATE_FAILED;
var STATE_PASSED = states.STATE_PASSED;
-describe('XUnit reporter', function () {
+describe("XUnit reporter", function () {
var runner;
var noop = function () {};
- var expectedLine = 'some-line';
- var expectedClassName = 'fullTitle';
- var expectedTitle = 'some title';
- var expectedFile = 'testFile.spec.js';
- var expectedMessage = 'some message';
+ var expectedLine = "some-line";
+ var expectedClassName = "fullTitle";
+ var expectedTitle = "some title";
+ var expectedFile = "testFile.spec.js";
+ var expectedMessage = "some message";
var expectedDiff =
- '\n + expected - actual\n\n -foo\n +bar\n ';
- var expectedStack = 'some-stack';
+ "\n + expected - actual\n\n -foo\n +bar\n ";
+ var expectedStack = "some-stack";
beforeEach(function () {
- runner = {on: noop, once: noop};
+ runner = { on: noop, once: noop };
createStatsCollector(runner);
});
describe("when 'reporterOptions.output' is provided", function () {
- var expectedOutput = path.join(path.sep, 'path', 'to', 'some-output');
+ var expectedOutput = path.join(path.sep, "path", "to", "some-output");
var options = {
reporterOptions: {
- output: expectedOutput
- }
+ output: expectedOutput,
+ },
};
- describe('when fileStream can be created', function () {
+ describe("when fileStream can be created", function () {
var fsMkdirSync;
var fsCreateWriteStream;
beforeEach(function () {
- fsMkdirSync = sinon.stub(fs, 'mkdirSync');
- fsCreateWriteStream = sinon.stub(fs, 'createWriteStream');
+ fsMkdirSync = sinon.stub(fs, "mkdirSync");
+ fsCreateWriteStream = sinon.stub(fs, "createWriteStream");
});
- it('should open given file for writing, recursively creating directories in pathname', function () {
+ it("should open given file for writing, recursively creating directories in pathname", function () {
var fakeThis = {
- fileStream: null
+ fileStream: null,
};
XUnit.call(fakeThis, runner, options);
var expectedDirectory = path.dirname(expectedOutput);
expect(
fsMkdirSync.calledWith(expectedDirectory, {
- recursive: true
+ recursive: true,
}),
- 'to be true'
+ "to be true",
);
- expect(fsCreateWriteStream.calledWith(expectedOutput), 'to be true');
+ expect(fsCreateWriteStream.calledWith(expectedOutput), "to be true");
});
afterEach(function () {
@@ -80,8 +80,8 @@ describe('XUnit reporter', function () {
});
});
- describe('when fileStream cannot be created', function () {
- describe('when given an invalid pathname', function () {
+ describe("when fileStream cannot be created", function () {
+ describe("when given an invalid pathname", function () {
/**
* @type {string}
*/
@@ -94,34 +94,34 @@ describe('XUnit reporter', function () {
var invalidPath;
beforeEach(async function () {
- const {dirpath, removeTempDir} = await createTempDir();
+ const { dirpath, removeTempDir } = await createTempDir();
tmpdir = dirpath;
cleanup = removeTempDir;
// Create path where file 'some-file' used as directory
invalidPath = path.join(
tmpdir,
- 'some-file',
- path.basename(expectedOutput)
+ "some-file",
+ path.basename(expectedOutput),
);
touchFile(path.dirname(invalidPath));
});
- it('should throw system error', function () {
+ it("should throw system error", function () {
var options = {
reporterOptions: {
- output: invalidPath
- }
+ output: invalidPath,
+ },
};
var boundXUnit = XUnit.bind({}, runner, options);
expect(
boundXUnit,
- 'to throw',
- expect.it('to be an', Error).and('to satisfy', {
- syscall: 'mkdir',
- code: 'EEXIST',
- path: path.dirname(invalidPath)
- })
+ "to throw",
+ expect.it("to be an", Error).and("to satisfy", {
+ syscall: "mkdir",
+ code: "EEXIST",
+ path: path.dirname(invalidPath),
+ }),
);
});
@@ -130,17 +130,17 @@ describe('XUnit reporter', function () {
});
});
- describe('when run in browser', function () {
+ describe("when run in browser", function () {
beforeEach(function () {
- sinon.stub(fs, 'createWriteStream').value(false);
+ sinon.stub(fs, "createWriteStream").value(false);
});
- it('should throw unsupported error', function () {
+ it("should throw unsupported error", function () {
var boundXUnit = XUnit.bind({}, runner, options);
expect(
boundXUnit,
- 'to throw',
- 'file output not supported in browser'
+ "to throw",
+ "file output not supported in browser",
);
});
@@ -151,20 +151,20 @@ describe('XUnit reporter', function () {
});
});
- describe('event handlers', function () {
+ describe("event handlers", function () {
describe("on 'pending', 'pass' and 'fail' events", function () {
it("should add test to tests called on 'end' event", function () {
var pendingTest = {
- name: 'pending',
- slow: noop
+ name: "pending",
+ slow: noop,
};
var failTest = {
- name: 'fail',
- slow: noop
+ name: "fail",
+ slow: noop,
};
var passTest = {
- name: 'pass',
- slow: noop
+ name: "pass",
+ slow: noop,
};
runner.on = runner.once = function (event, callback) {
if (event === EVENT_TEST_PENDING) {
@@ -183,20 +183,20 @@ describe('XUnit reporter', function () {
write: noop,
test: function (test) {
calledTests.push(test);
- }
+ },
};
XUnit.call(fakeThis, runner);
var expectedCalledTests = [pendingTest, passTest, failTest];
- expect(calledTests, 'to equal', expectedCalledTests);
+ expect(calledTests, "to equal", expectedCalledTests);
});
});
});
- describe('#done', function () {
+ describe("#done", function () {
var xunit;
var options = {
- reporterOptions: {}
+ reporterOptions: {},
};
var expectedNFailures = 13;
var callback;
@@ -211,7 +211,7 @@ describe('XUnit reporter', function () {
sinon.restore();
});
- describe('when output directed to file', function () {
+ describe("when output directed to file", function () {
var fakeThis;
beforeEach(function () {
@@ -220,26 +220,26 @@ describe('XUnit reporter', function () {
fakeThis = {
fileStream: {
end: sinon.stub().callsFake(function (chunk, encoding, cb) {
- if (typeof arguments[0] === 'function') {
+ if (typeof arguments[0] === "function") {
cb = arguments[0];
}
cb();
}),
- write: function () {}
- }
+ write: function () {},
+ },
};
});
it("should run completion callback via 'fileStream.end'", function () {
xunit.done.call(fakeThis, expectedNFailures, callback);
- expect(fakeThis.fileStream.end.calledOnce, 'to be true');
- expect(callback.calledOnce, 'to be true');
- expect(callback.calledWith(expectedNFailures), 'to be true');
+ expect(fakeThis.fileStream.end.calledOnce, "to be true");
+ expect(callback.calledOnce, "to be true");
+ expect(callback.calledWith(expectedNFailures), "to be true");
});
});
- describe('when output directed to stdout (or console)', function () {
+ describe("when output directed to stdout (or console)", function () {
var fakeThis;
beforeEach(function () {
@@ -247,72 +247,72 @@ describe('XUnit reporter', function () {
fakeThis = {};
});
- it('should run completion callback', function () {
+ it("should run completion callback", function () {
xunit.done.call(fakeThis, expectedNFailures, callback);
- expect(callback.calledOnce, 'to be true');
- expect(callback.calledWith(expectedNFailures), 'to be true');
+ expect(callback.calledOnce, "to be true");
+ expect(callback.calledWith(expectedNFailures), "to be true");
});
});
});
- describe('#write', function () {
+ describe("#write", function () {
// :TODO: Method should be named 'writeln', not 'write'
- describe('when output directed to file', function () {
+ describe("when output directed to file", function () {
var fileStream = {
- write: sinon.spy()
+ write: sinon.spy(),
};
it("should call 'fileStream.write' with line and newline", function () {
var xunit = new XUnit(runner);
- var fakeThis = {fileStream};
+ var fakeThis = { fileStream };
xunit.write.call(fakeThis, expectedLine);
- expect(fileStream.write.calledWith(expectedLine + '\n'), 'to be true');
+ expect(fileStream.write.calledWith(expectedLine + "\n"), "to be true");
});
});
- describe('when output directed to stdout', function () {
+ describe("when output directed to stdout", function () {
it("should call 'process.stdout.write' with line and newline", function () {
var xunit = new XUnit(runner);
- var fakeThis = {fileStream: false};
- var stdoutWriteStub = sinon.stub(process.stdout, 'write');
+ var fakeThis = { fileStream: false };
+ var stdoutWriteStub = sinon.stub(process.stdout, "write");
xunit.write.call(fakeThis, expectedLine);
stdoutWriteStub.restore();
- expect(stdoutWriteStub.calledWith(expectedLine + '\n'), 'to be true');
+ expect(stdoutWriteStub.calledWith(expectedLine + "\n"), "to be true");
});
});
- describe('when output directed to console', function () {
+ describe("when output directed to console", function () {
it("should call 'Base.consoleLog' with line", function () {
// :TODO: XUnit needs a trivially testable means to force console.log()
var realProcess = process;
process = false; // eslint-disable-line no-native-reassign, no-global-assign
var xunit = new XUnit(runner);
- var fakeThis = {fileStream: false};
- var consoleLogStub = sinon.stub(Base, 'consoleLog');
+ var fakeThis = { fileStream: false };
+ var consoleLogStub = sinon.stub(Base, "consoleLog");
xunit.write.call(fakeThis, expectedLine);
consoleLogStub.restore();
process = realProcess; // eslint-disable-line no-native-reassign, no-global-assign
- expect(consoleLogStub.calledWith(expectedLine), 'to be true');
+ expect(consoleLogStub.calledWith(expectedLine), "to be true");
});
});
});
- describe('#test', function () {
+ describe("#test", function () {
var expectedWrite;
var fakeThis = {
write: function (str) {
expectedWrite = str;
- }
+ },
};
beforeEach(function () {
- sinon.stub(Base, 'useColors').value(false);
+ sinon.stub(Base, "useColors").value(false);
});
afterEach(function () {
@@ -320,8 +320,8 @@ describe('XUnit reporter', function () {
expectedWrite = null;
});
- describe('on test failure', function () {
- it('should write expected tag with error details', function () {
+ describe("on test failure", function () {
+ it("should write expected tag with error details", function () {
var xunit = new XUnit(runner);
var expectedTest = {
state: STATE_FAILED,
@@ -330,15 +330,15 @@ describe('XUnit reporter', function () {
parent: {
fullTitle: function () {
return expectedClassName;
- }
+ },
},
duration: 1000,
err: {
- actual: 'foo',
- expected: 'bar',
+ actual: "foo",
+ expected: "bar",
message: expectedMessage,
- stack: expectedStack
- }
+ stack: expectedStack,
+ },
};
xunit.test.call(fakeThis, expectedTest);
@@ -353,15 +353,15 @@ describe('XUnit reporter', function () {
expectedFile +
'" time="1"><failure>' +
expectedMessage +
- '\n' +
+ "\n" +
expectedDiff +
- '\n' +
+ "\n" +
expectedStack +
- '</failure></testcase>';
- expect(expectedWrite, 'to be', expectedTag);
+ "</failure></testcase>";
+ expect(expectedWrite, "to be", expectedTag);
});
- it('should handle non-string diff values', function () {
+ it("should handle non-string diff values", function () {
var runner = new EventEmitter();
createStatsCollector(runner);
var xunit = new XUnit(runner);
@@ -373,18 +373,18 @@ describe('XUnit reporter', function () {
parent: {
fullTitle: function () {
return expectedClassName;
- }
+ },
},
duration: 1000,
err: {
actual: 1,
expected: 2,
message: expectedMessage,
- stack: expectedStack
- }
+ stack: expectedStack,
+ },
};
- sinon.stub(xunit, 'write').callsFake(function (str) {
+ sinon.stub(xunit, "write").callsFake(function (str) {
expectedWrite += str;
});
@@ -393,14 +393,14 @@ describe('XUnit reporter', function () {
sinon.restore();
var expectedDiff =
- '\n + expected - actual\n\n -1\n +2\n ';
+ "\n + expected - actual\n\n -1\n +2\n ";
- expect(expectedWrite, 'to contain', expectedDiff);
+ expect(expectedWrite, "to contain", expectedDiff);
});
});
- describe('on test pending', function () {
- it('should write expected tag', function () {
+ describe("on test pending", function () {
+ it("should write expected tag", function () {
var xunit = new XUnit(runner);
var expectedTest = {
isPending: function () {
@@ -411,9 +411,9 @@ describe('XUnit reporter', function () {
parent: {
fullTitle: function () {
return expectedClassName;
- }
+ },
},
- duration: 1000
+ duration: 1000,
};
xunit.test.call(fakeThis, expectedTest);
@@ -427,12 +427,12 @@ describe('XUnit reporter', function () {
'" file="' +
expectedFile +
'" time="1"><skipped/></testcase>';
- expect(expectedWrite, 'to be', expectedTag);
+ expect(expectedWrite, "to be", expectedTag);
});
});
- describe('on test in any other state', function () {
- it('should write expected tag', function () {
+ describe("on test in any other state", function () {
+ it("should write expected tag", function () {
var xunit = new XUnit(runner);
var expectedTest = {
isPending: function () {
@@ -443,9 +443,9 @@ describe('XUnit reporter', function () {
parent: {
fullTitle: function () {
return expectedClassName;
- }
+ },
},
- duration: false
+ duration: false,
};
xunit.test.call(fakeThis, expectedTest);
@@ -459,19 +459,19 @@ describe('XUnit reporter', function () {
'" file="' +
expectedFile +
'" time="0"/>';
- expect(expectedWrite, 'to be', expectedTag);
+ expect(expectedWrite, "to be", expectedTag);
});
});
- it('should write expected summary statistics', function () {
+ it("should write expected summary statistics", function () {
var numTests = 0;
var numPass = 0;
var numFail = 0;
var simpleError = {
- actual: 'foo',
- expected: 'bar',
+ actual: "foo",
+ expected: "bar",
message: expectedMessage,
- stack: expectedStack
+ stack: expectedStack,
};
var generateTest = function (passed) {
numTests++;
@@ -481,7 +481,7 @@ describe('XUnit reporter', function () {
numFail++;
}
return {
- title: [expectedTitle, numTests].join(': '),
+ title: [expectedTitle, numTests].join(": "),
state: passed ? STATE_PASSED : STATE_FAILED,
isPending: function () {
return false;
@@ -492,17 +492,17 @@ describe('XUnit reporter', function () {
parent: {
fullTitle: function () {
return expectedClassName;
- }
+ },
},
- duration: 1000
+ duration: 1000,
};
};
var runner = new EventEmitter();
createStatsCollector(runner);
var xunit = new XUnit(runner);
- expectedWrite = '';
- sinon.stub(xunit, 'write').callsFake(function (str) {
+ expectedWrite = "";
+ sinon.stub(xunit, "write").callsFake(function (str) {
expectedWrite += str;
});
@@ -521,20 +521,20 @@ describe('XUnit reporter', function () {
var expectedNumFail = 2;
var expectedNumTests = 3;
- expect(expectedNumPass, 'to be', numPass);
- expect(expectedNumFail, 'to be', numFail);
- expect(expectedNumTests, 'to be', numTests);
+ expect(expectedNumPass, "to be", numPass);
+ expect(expectedNumFail, "to be", numFail);
+ expect(expectedNumTests, "to be", numTests);
// :NOTE: Mocha test "fail" is an XUnit "error"
var expectedTag =
'<testsuite name="Mocha Tests" tests="3" failures="0" errors="2" skipped="0"';
- expect(expectedWrite, 'to contain', expectedTag);
- expect(expectedWrite, 'to contain', '</testsuite>');
+ expect(expectedWrite, "to contain", expectedTag);
+ expect(expectedWrite, "to contain", "</testsuite>");
});
});
- describe('suite name', function () {
+ describe("suite name", function () {
// Capture the events that the reporter subscribes to
var events = {};
// Capture output lines (will contain the resulting XML of XUnit reporter)
@@ -546,7 +546,7 @@ describe('XUnit reporter', function () {
fileStream = {
write: function (chunk) {
lines.push(chunk);
- }
+ },
};
});
@@ -560,12 +560,12 @@ describe('XUnit reporter', function () {
};
});
- it('should use custom name if provided via reporter options', function () {
- var customSuiteName = 'Mocha Is Great!';
+ it("should use custom name if provided via reporter options", function () {
+ var customSuiteName = "Mocha Is Great!";
var options = {
reporterOptions: {
- suiteName: customSuiteName
- }
+ suiteName: customSuiteName,
+ },
};
var xunit = new XUnit(runner, options);
@@ -574,13 +574,13 @@ describe('XUnit reporter', function () {
// Trigger end event to force XUnit reporter to write its output
events[EVENT_RUN_END]();
- expect(lines[0], 'to contain', customSuiteName);
+ expect(lines[0], "to contain", customSuiteName);
});
- it('should use default name otherwise', function () {
- var defaultSuiteName = 'Mocha Tests';
+ it("should use default name otherwise", function () {
+ var defaultSuiteName = "Mocha Tests";
var options = {
- reporterOptions: {}
+ reporterOptions: {},
};
var xunit = new XUnit(runner, options);
@@ -589,20 +589,20 @@ describe('XUnit reporter', function () {
// Trigger end event to force XUnit reporter to write its output
events[EVENT_RUN_END]();
- expect(lines[0], 'to contain', defaultSuiteName);
+ expect(lines[0], "to contain", defaultSuiteName);
});
});
- describe('showRelativePaths reporter option', function () {
- const projectPath = path.join('home', 'username', 'demo-project');
- const relativeTestPath = path.join('tests', 'demo-test.spec.js');
+ describe("showRelativePaths reporter option", function () {
+ const projectPath = path.join("home", "username", "demo-project");
+ const relativeTestPath = path.join("tests", "demo-test.spec.js");
const absoluteTestPath = path.join(projectPath, relativeTestPath);
- var expectedWrite = '';
+ var expectedWrite = "";
const fakeThis = {
write: function (str) {
expectedWrite = expectedWrite + str;
- }
+ },
};
const failingTest = {
@@ -612,49 +612,49 @@ describe('XUnit reporter', function () {
parent: {
fullTitle: function () {
return expectedClassName;
- }
+ },
},
duration: 1000,
err: {
- actual: 'foo',
- expected: 'bar',
+ actual: "foo",
+ expected: "bar",
message: expectedMessage,
- stack: expectedStack
- }
+ stack: expectedStack,
+ },
};
beforeEach(function () {
- sinon.stub(process, 'cwd').returns(projectPath);
+ sinon.stub(process, "cwd").returns(projectPath);
});
afterEach(function () {
sinon.restore();
- expectedWrite = '';
+ expectedWrite = "";
});
- it('shows relative paths for tests if showRelativePaths reporter option is set', function () {
+ it("shows relative paths for tests if showRelativePaths reporter option is set", function () {
const options = {
reporterOptions: {
- showRelativePaths: true
- }
+ showRelativePaths: true,
+ },
};
const xunit = new XUnit(runner, options);
xunit.test.call(fakeThis, failingTest, options);
- expect(expectedWrite, 'not to contain', absoluteTestPath);
- expect(expectedWrite, 'to contain', relativeTestPath);
+ expect(expectedWrite, "not to contain", absoluteTestPath);
+ expect(expectedWrite, "to contain", relativeTestPath);
});
- it('shows absolute paths for tests by default', function () {
+ it("shows absolute paths for tests by default", function () {
const options = {};
const xunit = new XUnit(runner);
xunit.test.call(fakeThis, failingTest, options);
- expect(expectedWrite, 'to contain', absoluteTestPath);
+ expect(expectedWrite, "to contain", absoluteTestPath);
// Double quote included to ensure printed paths don't start with relative path. Example printed line: <testcase classname="suite" name="test" file="some/tesfile.js" time="0"/>
- expect(expectedWrite, 'not to contain', `"${relativeTestPath}`);
+ expect(expectedWrite, "not to contain", `"${relativeTestPath}`);
});
});
});
diff --git a/test/require/a.js b/test/require/a.js
index 30725999..684bbf83 100644
--- a/test/require/a.js
+++ b/test/require/a.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
global.required = global.required || [];
-global.required.push('a.js');
+global.required.push("a.js");
diff --git a/test/require/c.js b/test/require/c.js
index 277664d5..b40624aa 100644
--- a/test/require/c.js
+++ b/test/require/c.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
global.required = global.required || [];
-global.required.push('c.js');
+global.required.push("c.js");
diff --git a/test/require/require.spec.js b/test/require/require.spec.js
index c48f90f3..5e000f00 100644
--- a/test/require/require.spec.js
+++ b/test/require/require.spec.js
@@ -1,11 +1,11 @@
-'use strict';
+"use strict";
-describe('require test', function () {
- it('should require args in order', function () {
+describe("require test", function () {
+ it("should require args in order", function () {
var req = global.required;
- expect(req.indexOf('a.js'), 'to be', 0);
- expect(req.indexOf('b.coffee'), 'to be', 1);
- expect(req.indexOf('c.js'), 'to be', 2);
- expect(req.indexOf('d.coffee'), 'to be', 3);
+ expect(req.indexOf("a.js"), "to be", 0);
+ expect(req.indexOf("b.coffee"), "to be", 1);
+ expect(req.indexOf("c.js"), "to be", 2);
+ expect(req.indexOf("d.coffee"), "to be", 3);
});
});
diff --git a/test/setup.js b/test/setup.js
index a979858a..0e3bc04a 100644
--- a/test/setup.js
+++ b/test/setup.js
@@ -1,11 +1,11 @@
-'use strict';
+"use strict";
-const unexpected = require('unexpected');
+const unexpected = require("unexpected");
global.expect = unexpected
.clone()
- .use(require('unexpected-sinon'))
- .use(require('unexpected-eventemitter'))
- .use(require('unexpected-map'))
- .use(require('unexpected-set'))
- .use(require('./assertions'));
+ .use(require("unexpected-sinon"))
+ .use(require("unexpected-eventemitter"))
+ .use(require("unexpected-map"))
+ .use(require("unexpected-set"))
+ .use(require("./assertions"));
diff --git a/test/smoke/smoke.spec.js b/test/smoke/smoke.spec.js
index c5ad721a..9176e5bc 100644
--- a/test/smoke/smoke.spec.js
+++ b/test/smoke/smoke.spec.js
@@ -1,4 +1,4 @@
-'use strict';
+"use strict";
// This test ensures Mocha's dependencies are properly in place,
// and is intended to be run after an `npm install --production` in a clean
@@ -6,10 +6,10 @@
// in `devDependencies` or otherwise in the wrong place.
// It does not ensure that all files are present in the published package!
-var assert = require('node:assert');
+var assert = require("node:assert");
-describe('a production installation of Mocha', function () {
- it('should be able to execute a test', function () {
+describe("a production installation of Mocha", function () {
+ it("should be able to execute a test", function () {
assert.ok(true);
});
});
diff --git a/test/unit/context.spec.js b/test/unit/context.spec.js
index 783219d1..819dff8f 100644
--- a/test/unit/context.spec.js
+++ b/test/unit/context.spec.js
@@ -1,98 +1,98 @@
-'use strict';
+"use strict";
-describe('Context', function () {
+describe("Context", function () {
beforeEach(function () {
- this.calls = ['before'];
+ this.calls = ["before"];
});
- describe('nested', function () {
+ describe("nested", function () {
beforeEach(function () {
- this.calls.push('before two');
+ this.calls.push("before two");
});
- it('should work', function () {
- expect(this.calls, 'to equal', ['before', 'before two']);
- this.calls.push('test');
+ it("should work", function () {
+ expect(this.calls, "to equal", ["before", "before two"]);
+ this.calls.push("test");
});
after(function () {
- expect(this.calls, 'to equal', ['before', 'before two', 'test']);
- this.calls.push('after two');
+ expect(this.calls, "to equal", ["before", "before two", "test"]);
+ this.calls.push("after two");
});
});
after(function () {
- expect(this.calls, 'to equal', [
- 'before',
- 'before two',
- 'test',
- 'after two'
+ expect(this.calls, "to equal", [
+ "before",
+ "before two",
+ "test",
+ "after two",
]);
});
});
-describe('Context Siblings', function () {
+describe("Context Siblings", function () {
beforeEach(function () {
- this.calls = ['before'];
+ this.calls = ["before"];
});
- describe('sequestered sibling', function () {
+ describe("sequestered sibling", function () {
beforeEach(function () {
- this.calls.push('before two');
- this.hiddenFromSibling = 'This should be hidden';
+ this.calls.push("before two");
+ this.hiddenFromSibling = "This should be hidden";
});
- it('should work', function () {
- expect(this.hiddenFromSibling, 'to equal', 'This should be hidden');
+ it("should work", function () {
+ expect(this.hiddenFromSibling, "to equal", "This should be hidden");
});
});
- describe('sibling verifiction', function () {
+ describe("sibling verifiction", function () {
beforeEach(function () {
- this.calls.push('before sibling');
+ this.calls.push("before sibling");
});
- it('should not have value set within a sibling describe', function () {
- expect('This should be hidden', 'not to equal', this.hiddenFromSibling);
- this.visibleFromTestSibling = 'Visible from test sibling';
+ it("should not have value set within a sibling describe", function () {
+ expect("This should be hidden", "not to equal", this.hiddenFromSibling);
+ this.visibleFromTestSibling = "Visible from test sibling";
});
- it('should allow test siblings to modify shared context', function () {
+ it("should allow test siblings to modify shared context", function () {
expect(
- 'Visible from test sibling',
- 'to equal',
- this.visibleFromTestSibling
+ "Visible from test sibling",
+ "to equal",
+ this.visibleFromTestSibling,
);
});
- it('should have reset this.calls before describe', function () {
- expect(this.calls, 'to equal', ['before', 'before sibling']);
+ it("should have reset this.calls before describe", function () {
+ expect(this.calls, "to equal", ["before", "before sibling"]);
});
});
after(function () {
- expect(this.calls, 'to equal', ['before', 'before sibling']);
+ expect(this.calls, "to equal", ["before", "before sibling"]);
});
});
-describe('methods', function () {
- describe('timeout()', function () {
- it('should return the timeout', function () {
+describe("methods", function () {
+ describe("timeout()", function () {
+ it("should return the timeout", function () {
// set this explicitly because browser and node use diff settings
this.timeout(1000);
- expect(this.timeout(), 'to be', 1000);
+ expect(this.timeout(), "to be", 1000);
});
});
- describe('slow()', function () {
- it('should return the slow', function () {
- expect(this.slow(), 'to be', 75);
+ describe("slow()", function () {
+ it("should return the slow", function () {
+ expect(this.slow(), "to be", 75);
});
});
- describe('retries', function () {
- it('should return the number of retries', function () {
- expect(this.retries(), 'to be', -1);
+ describe("retries", function () {
+ it("should return the number of retries", function () {
+ expect(this.retries(), "to be", -1);
});
});
});
diff --git a/test/unit/duration.spec.js b/test/unit/duration.spec.js
index 45d2681b..7f3d3560 100644
--- a/test/unit/duration.spec.js
+++ b/test/unit/duration.spec.js
@@ -1,24 +1,24 @@
-'use strict';
+"use strict";
-describe('durations', function () {
- describe('when slow', function () {
- it('should highlight in red', function (done) {
+describe("durations", function () {
+ describe("when slow", function () {
+ it("should highlight in red", function (done) {
setTimeout(function () {
done();
}, 100);
});
});
- describe('when reasonable', function () {
- it('should highlight in yellow', function (done) {
+ describe("when reasonable", function () {
+ it("should highlight in yellow", function (done) {
setTimeout(function () {
done();
}, 50);
});
});
- describe('when fast', function () {
- it('should not highlight', function (done) {
+ describe("when fast", function () {
+ it("should not highlight", function (done) {
setTimeout(function () {
done();
}, 10);
diff --git a/test/unit/errors.spec.js b/test/unit/errors.spec.js
index a36376fc..0847d713 100644
--- a/test/unit/errors.spec.js
+++ b/test/unit/errors.spec.js
@@ -1,95 +1,95 @@
-'use strict';
+"use strict";
-var errors = require('../../lib/errors');
-var constants = require('../../lib/error-constants');
-const sinon = require('sinon');
-const {createNoFilesMatchPatternError} = require('../../lib/errors');
+var errors = require("../../lib/errors");
+var constants = require("../../lib/error-constants");
+const sinon = require("sinon");
+const { createNoFilesMatchPatternError } = require("../../lib/errors");
-describe('Errors', function () {
+describe("Errors", function () {
afterEach(function () {
sinon.restore();
});
- var message = 'some message';
+ var message = "some message";
- describe('createInvalidReporterError()', function () {
- it('should include expected code in thrown reporter errors', function () {
+ describe("createInvalidReporterError()", function () {
+ it("should include expected code in thrown reporter errors", function () {
expect(
- errors.createInvalidReporterError(message, 'badReporter'),
- 'to satisfy',
+ errors.createInvalidReporterError(message, "badReporter"),
+ "to satisfy",
{
message,
- code: 'ERR_MOCHA_INVALID_REPORTER',
- reporter: 'badReporter'
- }
+ code: "ERR_MOCHA_INVALID_REPORTER",
+ reporter: "badReporter",
+ },
);
});
});
- describe('createInvalidInterfaceError()', function () {
- it('should include expected code in thrown interface errors', function () {
+ describe("createInvalidInterfaceError()", function () {
+ it("should include expected code in thrown interface errors", function () {
expect(
- errors.createInvalidInterfaceError(message, 'badUi'),
- 'to satisfy',
+ errors.createInvalidInterfaceError(message, "badUi"),
+ "to satisfy",
{
message,
- code: 'ERR_MOCHA_INVALID_INTERFACE',
- interface: 'badUi'
- }
+ code: "ERR_MOCHA_INVALID_INTERFACE",
+ interface: "badUi",
+ },
);
});
});
- describe('createForbiddenExclusivityError()', function () {
- describe('when Mocha instance is running in a worker process', function () {
- it('should output a message regarding incompatibility', function () {
- var mocha = {isWorker: true};
+ describe("createForbiddenExclusivityError()", function () {
+ describe("when Mocha instance is running in a worker process", function () {
+ it("should output a message regarding incompatibility", function () {
+ var mocha = { isWorker: true };
expect(
errors.createForbiddenExclusivityError(mocha, {}),
- 'to satisfy',
+ "to satisfy",
{
message: /parallel/,
- code: constants.FORBIDDEN_EXCLUSIVITY
- }
+ code: constants.FORBIDDEN_EXCLUSIVITY,
+ },
);
});
});
- describe('when Mocha instance is not running in a worker process', function () {
- it('should output a message regarding --forbid-only', function () {
+ describe("when Mocha instance is not running in a worker process", function () {
+ it("should output a message regarding --forbid-only", function () {
var mocha = {};
expect(
errors.createForbiddenExclusivityError(mocha, {}),
- 'to satisfy',
+ "to satisfy",
{
message: /--forbid-only/,
- code: constants.FORBIDDEN_EXCLUSIVITY
- }
+ code: constants.FORBIDDEN_EXCLUSIVITY,
+ },
);
});
});
});
- describe('createUnparsableFileError()', function () {
- it('should include expected code in thrown unparsable file errors', function () {
+ describe("createUnparsableFileError()", function () {
+ it("should include expected code in thrown unparsable file errors", function () {
expect(
- errors.createUnparsableFileError(message, 'badFilePath'),
- 'to satisfy',
+ errors.createUnparsableFileError(message, "badFilePath"),
+ "to satisfy",
{
message,
- code: 'ERR_MOCHA_UNPARSABLE_FILE'
- }
+ code: "ERR_MOCHA_UNPARSABLE_FILE",
+ },
);
});
});
- describe('deprecate()', function () {
+ describe("deprecate()", function () {
var emitWarning;
beforeEach(function () {
if (process.emitWarning) {
emitWarning = process.emitWarning;
- sinon.stub(process, 'emitWarning');
+ sinon.stub(process, "emitWarning");
} else {
process.emitWarning = sinon.spy();
}
@@ -103,33 +103,33 @@ describe('Errors', function () {
}
});
- it('should coerce its parameter to a string', function () {
+ it("should coerce its parameter to a string", function () {
errors.deprecate(1);
- expect(process.emitWarning, 'to have a call satisfying', [
- '1',
- 'DeprecationWarning'
+ expect(process.emitWarning, "to have a call satisfying", [
+ "1",
+ "DeprecationWarning",
]);
});
- it('should cache the message', function () {
- errors.deprecate('foo');
- errors.deprecate('foo');
- expect(process.emitWarning, 'was called times', 1);
+ it("should cache the message", function () {
+ errors.deprecate("foo");
+ errors.deprecate("foo");
+ expect(process.emitWarning, "was called times", 1);
});
- it('should ignore falsy messages', function () {
- errors.deprecate('');
- expect(process.emitWarning, 'was not called');
+ it("should ignore falsy messages", function () {
+ errors.deprecate("");
+ expect(process.emitWarning, "was not called");
});
});
- describe('warn()', function () {
+ describe("warn()", function () {
var emitWarning;
beforeEach(function () {
if (process.emitWarning) {
emitWarning = process.emitWarning;
- sinon.stub(process, 'emitWarning');
+ sinon.stub(process, "emitWarning");
} else {
process.emitWarning = sinon.spy();
}
@@ -142,44 +142,44 @@ describe('Errors', function () {
}
});
- it('should call process.emitWarning', function () {
- errors.warn('foo');
- expect(process.emitWarning, 'was called times', 1);
+ it("should call process.emitWarning", function () {
+ errors.warn("foo");
+ expect(process.emitWarning, "was called times", 1);
});
- it('should not cache messages', function () {
- errors.warn('foo');
- errors.warn('foo');
- expect(process.emitWarning, 'was called times', 2);
+ it("should not cache messages", function () {
+ errors.warn("foo");
+ errors.warn("foo");
+ expect(process.emitWarning, "was called times", 2);
});
- it('should ignore falsy messages', function () {
- errors.warn('');
- expect(process.emitWarning, 'was not called');
+ it("should ignore falsy messages", function () {
+ errors.warn("");
+ expect(process.emitWarning, "was not called");
});
});
- describe('isMochaError()', function () {
- describe('when provided an Error object having a known Mocha error code', function () {
- it('should return true', function () {
+ describe("isMochaError()", function () {
+ describe("when provided an Error object having a known Mocha error code", function () {
+ it("should return true", function () {
expect(
- errors.isMochaError(createNoFilesMatchPatternError('derp')),
- 'to be true'
+ errors.isMochaError(createNoFilesMatchPatternError("derp")),
+ "to be true",
);
});
});
- describe('when provided an Error object with a non-Mocha error code', function () {
- it('should return false', function () {
+ describe("when provided an Error object with a non-Mocha error code", function () {
+ it("should return false", function () {
const err = new Error();
- err.code = 'ENOTEA';
- expect(errors.isMochaError(err), 'to be false');
+ err.code = "ENOTEA";
+ expect(errors.isMochaError(err), "to be false");
});
});
- describe('when provided a non-error', function () {
- it('should return false', function () {
- expect(errors.isMochaError(), 'to be false');
+ describe("when provided a non-error", function () {
+ it("should return false", function () {
+ expect(errors.isMochaError(), "to be false");
});
});
});
diff --git a/test/unit/globals.spec.js b/test/unit/globals.spec.js
index 9ae8c591..c30489e1 100644
--- a/test/unit/globals.spec.js
+++ b/test/unit/globals.spec.js
@@ -1,6 +1,6 @@
-'use strict';
+"use strict";
-describe('global leaks', function () {
+describe("global leaks", function () {
before(function () {
// uncomment to test
// foo = 'hey';
@@ -12,28 +12,28 @@ describe('global leaks', function () {
// foo = 'bar'
});
- it('should cause tests to fail', function () {
+ it("should cause tests to fail", function () {
// uncomment to test
// foo = 'bar';
// bar = 'baz';
// baz = 'raz';
});
- it('should pass when accepted', function () {
+ it("should pass when accepted", function () {
global.okGlobalA = 1;
global.okGlobalB = 1;
global.okGlobalC = 1;
});
- it('should pass with wildcard', function () {
- global.callback123 = 'foo';
- global.callback345 = 'bar';
+ it("should pass with wildcard", function () {
+ global.callback123 = "foo";
+ global.callback345 = "bar";
});
it('should pass when prefixed "mocha-"', function () {
// Opera and IE do this for HTML element IDs anyway
// but to sure we can assert this in any browser, simulate it.
- global['mocha-example'] = {nodeType: 1};
+ global["mocha-example"] = { nodeType: 1 };
});
afterEach(function () {
diff --git a/test/unit/grep.spec.js b/test/unit/grep.spec.js
index 2f2fd874..c170b0a2 100644
--- a/test/unit/grep.spec.js
+++ b/test/unit/grep.spec.js
@@ -1,67 +1,67 @@
-'use strict';
+"use strict";
-var Mocha = require('../../lib/mocha');
+var Mocha = require("../../lib/mocha");
-describe('Mocha', function () {
+describe("Mocha", function () {
describe('"grep" option', function () {
- it('should add a RegExp to the mocha.options object', function () {
- var mocha = new Mocha({grep: /foo.*/});
- expect(mocha.options.grep, 'to equal', /foo.*/);
+ it("should add a RegExp to the mocha.options object", function () {
+ var mocha = new Mocha({ grep: /foo.*/ });
+ expect(mocha.options.grep, "to equal", /foo.*/);
});
- it('should convert string to a RegExp', function () {
- var mocha = new Mocha({grep: 'foo.*'});
- expect(mocha.options.grep, 'to equal', /foo.*/);
+ it("should convert string to a RegExp", function () {
+ var mocha = new Mocha({ grep: "foo.*" });
+ expect(mocha.options.grep, "to equal", /foo.*/);
});
});
describe('"fgrep" option', function () {
- it('should escape and convert string to a RegExp', function () {
- var mocha = new Mocha({fgrep: 'foo.*'});
- expect(mocha.options.grep, 'to equal', /foo\.\*/);
+ it("should escape and convert string to a RegExp", function () {
+ var mocha = new Mocha({ fgrep: "foo.*" });
+ expect(mocha.options.grep, "to equal", /foo\.\*/);
});
});
- describe('.grep()', function () {
+ describe(".grep()", function () {
// Test helper
function testGrep(mocha) {
return function testGrep(grep, expected) {
mocha.grep(grep);
- expect(String(mocha.options.grep), 'to be', expected);
+ expect(String(mocha.options.grep), "to be", expected);
};
}
- it('should add a RegExp to the mocha.options object', function () {
+ it("should add a RegExp to the mocha.options object", function () {
var test = testGrep(new Mocha());
- test(/foo/, '/foo/');
+ test(/foo/, "/foo/");
});
- it('should convert grep string to a RegExp', function () {
+ it("should convert grep string to a RegExp", function () {
var test = testGrep(new Mocha());
- test('foo', '/foo/');
- test('^foo.*bar$', '/^foo.*bar$/');
- test('^@.*(?=\\(\\)$)', '/^@.*(?=\\(\\)$)/');
+ test("foo", "/foo/");
+ test("^foo.*bar$", "/^foo.*bar$/");
+ test("^@.*(?=\\(\\)$)", "/^@.*(?=\\(\\)$)/");
});
- it('should covert grep regex-like string to a RegExp', function () {
+ it("should covert grep regex-like string to a RegExp", function () {
var test = testGrep(new Mocha());
- test('/foo/', '/foo/');
+ test("/foo/", "/foo/");
// Keep the flags
- test('/baz/i', '/baz/i');
- test('/bar/g', '/bar/g');
- test('/^foo(.*)bar/g', '/^foo(.*)bar/g');
+ test("/baz/i", "/baz/i");
+ test("/bar/g", "/bar/g");
+ test("/^foo(.*)bar/g", "/^foo(.*)bar/g");
});
- it('should return its parent Mocha object for chainability', function () {
+ it("should return its parent Mocha object for chainability", function () {
var mocha = new Mocha();
- expect(mocha.grep(), 'to be', mocha);
+ expect(mocha.grep(), "to be", mocha);
});
});
describe('"invert" option', function () {
- it('should add a Boolean to the mocha.options object', function () {
- var mocha = new Mocha({invert: true});
- expect(mocha.options.invert, 'to be', true);
+ it("should add a Boolean to the mocha.options object", function () {
+ var mocha = new Mocha({ invert: true });
+ expect(mocha.options.invert, "to be", true);
});
});
});
diff --git a/test/unit/hook-async.spec.js b/test/unit/hook-async.spec.js
index 6df31c52..f30269a8 100644
--- a/test/unit/hook-async.spec.js
+++ b/test/unit/hook-async.spec.js
@@ -1,133 +1,133 @@
-'use strict';
+"use strict";
-describe('async', function () {
+describe("async", function () {
var calls = [];
before(function () {
- calls.push('root before all');
+ calls.push("root before all");
});
after(function () {
- calls.push('root after all');
- expect(calls, 'to equal', [
- 'root before all',
- 'before all',
- 'parent before',
- 'before',
- 'before test one',
- 'one',
- 'after',
- 'after test one passed',
- 'parent after',
- 'parent before',
- 'before',
- 'before test two',
- 'two',
- 'after',
- 'after test two passed',
- 'parent after',
- 'parent before',
- 'before',
- 'before test three',
- 'three',
- 'after',
- 'after test three passed',
- 'parent after',
- 'after all',
- 'root after all'
+ calls.push("root after all");
+ expect(calls, "to equal", [
+ "root before all",
+ "before all",
+ "parent before",
+ "before",
+ "before test one",
+ "one",
+ "after",
+ "after test one passed",
+ "parent after",
+ "parent before",
+ "before",
+ "before test two",
+ "two",
+ "after",
+ "after test two passed",
+ "parent after",
+ "parent before",
+ "before",
+ "before test three",
+ "three",
+ "after",
+ "after test three passed",
+ "parent after",
+ "after all",
+ "root after all",
]);
});
beforeEach(function () {
- calls.push('parent before');
+ calls.push("parent before");
});
afterEach(function () {
- calls.push('parent after');
+ calls.push("parent after");
});
- describe('hooks', function () {
+ describe("hooks", function () {
before(function () {
- calls.push('before all');
+ calls.push("before all");
});
after(function () {
- calls.push('after all');
+ calls.push("after all");
});
beforeEach(function (done) {
var ctx = this;
process.nextTick(function () {
- calls.push('before');
+ calls.push("before");
if (ctx.currentTest) {
- calls.push('before test ' + ctx.currentTest.title);
+ calls.push("before test " + ctx.currentTest.title);
}
done();
});
});
- it('one', function (done) {
- expect(calls, 'to equal', [
- 'root before all',
- 'before all',
- 'parent before',
- 'before',
- 'before test one'
+ it("one", function (done) {
+ expect(calls, "to equal", [
+ "root before all",
+ "before all",
+ "parent before",
+ "before",
+ "before test one",
]);
- calls.push('one');
+ calls.push("one");
process.nextTick(done);
});
- it('two', function () {
- expect(calls, 'to equal', [
- 'root before all',
- 'before all',
- 'parent before',
- 'before',
- 'before test one',
- 'one',
- 'after',
- 'after test one passed',
- 'parent after',
- 'parent before',
- 'before',
- 'before test two'
+ it("two", function () {
+ expect(calls, "to equal", [
+ "root before all",
+ "before all",
+ "parent before",
+ "before",
+ "before test one",
+ "one",
+ "after",
+ "after test one passed",
+ "parent after",
+ "parent before",
+ "before",
+ "before test two",
]);
- calls.push('two');
+ calls.push("two");
});
- it('three', function () {
- expect(calls, 'to equal', [
- 'root before all',
- 'before all',
- 'parent before',
- 'before',
- 'before test one',
- 'one',
- 'after',
- 'after test one passed',
- 'parent after',
- 'parent before',
- 'before',
- 'before test two',
- 'two',
- 'after',
- 'after test two passed',
- 'parent after',
- 'parent before',
- 'before',
- 'before test three'
+ it("three", function () {
+ expect(calls, "to equal", [
+ "root before all",
+ "before all",
+ "parent before",
+ "before",
+ "before test one",
+ "one",
+ "after",
+ "after test one passed",
+ "parent after",
+ "parent before",
+ "before",
+ "before test two",
+ "two",
+ "after",
+ "after test two passed",
+ "parent after",
+ "parent before",
+ "before",
+ "before test three",
]);
- calls.push('three');
+ calls.push("three");
});
afterEach(function (done) {
var ctx = this;
process.nextTick(function () {
- calls.push('after');
+ calls.push("after");
if (ctx.currentTest) {
calls.push(
- 'after test ' + ctx.currentTest.title + ' ' + ctx.currentTest.state
+ "after test " + ctx.currentTest.title + " " + ctx.currentTest.state,
);
}
done();
diff --git a/test/unit/hook-sync-nested.spec.js b/test/unit/hook-sync-nested.spec.js
index c07ca20a..202b3754 100644
--- a/test/unit/hook-sync-nested.spec.js
+++ b/test/unit/hook-sync-nested.spec.js
@@ -1,108 +1,108 @@
-'use strict';
+"use strict";
-describe('serial', function () {
- describe('nested', function () {
+describe("serial", function () {
+ describe("nested", function () {
var calls = [];
beforeEach(function () {
- calls.push('parent before');
+ calls.push("parent before");
if (this.currentTest) {
- calls.push('parent before test ' + this.currentTest.title);
+ calls.push("parent before test " + this.currentTest.title);
}
});
afterEach(function () {
- calls.push('parent after');
+ calls.push("parent after");
if (this.currentTest) {
calls.push(
- 'parent after test ' +
+ "parent after test " +
this.currentTest.title +
- ' ' +
- this.currentTest.state
+ " " +
+ this.currentTest.state,
);
}
});
- it('foo', function () {
- expect(calls, 'to equal', ['parent before', 'parent before test foo']);
- calls.push('foo');
+ it("foo", function () {
+ expect(calls, "to equal", ["parent before", "parent before test foo"]);
+ calls.push("foo");
});
- it('bar', function () {
- expect(calls, 'to equal', [
- 'parent before',
- 'parent before test foo',
- 'foo',
- 'parent after',
- 'parent after test foo passed',
- 'parent before',
- 'parent before test bar'
+ it("bar", function () {
+ expect(calls, "to equal", [
+ "parent before",
+ "parent before test foo",
+ "foo",
+ "parent after",
+ "parent after test foo passed",
+ "parent before",
+ "parent before test bar",
]);
});
- describe('hooks', function () {
+ describe("hooks", function () {
beforeEach(function () {
- calls.push('before');
+ calls.push("before");
if (this.currentTest) {
- calls.push('before test ' + this.currentTest.title);
+ calls.push("before test " + this.currentTest.title);
}
});
- it('one', function () {
- expect(calls, 'to equal', [
- 'parent before',
- 'parent before test foo',
- 'foo',
- 'parent after',
- 'parent after test foo passed',
- 'parent before',
- 'parent before test bar',
- 'parent after',
- 'parent after test bar passed',
- 'parent before',
- 'parent before test one',
- 'before',
- 'before test one'
+ it("one", function () {
+ expect(calls, "to equal", [
+ "parent before",
+ "parent before test foo",
+ "foo",
+ "parent after",
+ "parent after test foo passed",
+ "parent before",
+ "parent before test bar",
+ "parent after",
+ "parent after test bar passed",
+ "parent before",
+ "parent before test one",
+ "before",
+ "before test one",
]);
- calls.push('one');
+ calls.push("one");
});
- it('two', function () {
- expect(calls, 'to equal', [
- 'parent before',
- 'parent before test foo',
- 'foo',
- 'parent after',
- 'parent after test foo passed',
- 'parent before',
- 'parent before test bar',
- 'parent after',
- 'parent after test bar passed',
- 'parent before',
- 'parent before test one',
- 'before',
- 'before test one',
- 'one',
- 'after',
- 'after test one passed',
- 'parent after',
- 'parent after test one passed',
- 'parent before',
- 'parent before test two',
- 'before',
- 'before test two'
+ it("two", function () {
+ expect(calls, "to equal", [
+ "parent before",
+ "parent before test foo",
+ "foo",
+ "parent after",
+ "parent after test foo passed",
+ "parent before",
+ "parent before test bar",
+ "parent after",
+ "parent after test bar passed",
+ "parent before",
+ "parent before test one",
+ "before",
+ "before test one",
+ "one",
+ "after",
+ "after test one passed",
+ "parent after",
+ "parent after test one passed",
+ "parent before",
+ "parent before test two",
+ "before",
+ "before test two",
]);
- calls.push('two');
+ calls.push("two");
});
afterEach(function () {
- calls.push('after');
+ calls.push("after");
if (this.currentTest) {
calls.push(
- 'after test ' +
+ "after test " +
this.currentTest.title +
- ' ' +
- this.currentTest.state
+ " " +
+ this.currentTest.state,
);
}
});
diff --git a/test/unit/hook-sync.spec.js b/test/unit/hook-sync.spec.js
index 73959036..d5aafeac 100644
--- a/test/unit/hook-sync.spec.js
+++ b/test/unit/hook-sync.spec.js
@@ -1,100 +1,100 @@
-'use strict';
+"use strict";
-describe('serial', function () {
+describe("serial", function () {
var calls = [];
beforeEach(function () {
- calls.push('parent before');
+ calls.push("parent before");
});
afterEach(function () {
- calls.push('parent after');
+ calls.push("parent after");
});
- describe('hooks', function () {
+ describe("hooks", function () {
beforeEach(function () {
- calls.push('before');
+ calls.push("before");
if (this.currentTest) {
- calls.push('before test ' + this.currentTest.title);
+ calls.push("before test " + this.currentTest.title);
}
});
- it('one', function () {
- expect(calls, 'to equal', ['parent before', 'before', 'before test one']);
- calls.push('one');
+ it("one", function () {
+ expect(calls, "to equal", ["parent before", "before", "before test one"]);
+ calls.push("one");
});
- it('two', function () {
- expect(calls, 'to equal', [
- 'parent before',
- 'before',
- 'before test one',
- 'one',
- 'after',
- 'after test one passed',
- 'parent after',
- 'parent before',
- 'before',
- 'before test two'
+ it("two", function () {
+ expect(calls, "to equal", [
+ "parent before",
+ "before",
+ "before test one",
+ "one",
+ "after",
+ "after test one passed",
+ "parent after",
+ "parent before",
+ "before",
+ "before test two",
]);
- calls.push('two');
+ calls.push("two");
});
- it('three', function () {
- expect(calls, 'to equal', [
- 'parent before',
- 'before',
- 'before test one',
- 'one',
- 'after',
- 'after test one passed',
- 'parent after',
- 'parent before',
- 'before',
- 'before test two',
- 'two',
- 'after',
- 'after test two passed',
- 'parent after',
- 'parent before',
- 'before',
- 'before test three'
+ it("three", function () {
+ expect(calls, "to equal", [
+ "parent before",
+ "before",
+ "before test one",
+ "one",
+ "after",
+ "after test one passed",
+ "parent after",
+ "parent before",
+ "before",
+ "before test two",
+ "two",
+ "after",
+ "after test two passed",
+ "parent after",
+ "parent before",
+ "before",
+ "before test three",
]);
- calls.push('three');
+ calls.push("three");
});
afterEach(function () {
- calls.push('after');
+ calls.push("after");
if (this.currentTest) {
calls.push(
- 'after test ' + this.currentTest.title + ' ' + this.currentTest.state
+ "after test " + this.currentTest.title + " " + this.currentTest.state,
);
}
});
after(function () {
- expect(calls, 'to equal', [
- 'parent before',
- 'before',
- 'before test one',
- 'one',
- 'after',
- 'after test one passed',
- 'parent after',
- 'parent before',
- 'before',
- 'before test two',
- 'two',
- 'after',
- 'after test two passed',
- 'parent after',
- 'parent before',
- 'before',
- 'before test three',
- 'three',
- 'after',
- 'after test three passed',
- 'parent after'
+ expect(calls, "to equal", [
+ "parent before",
+ "before",
+ "before test one",
+ "one",
+ "after",
+ "after test one passed",
+ "parent after",
+ "parent before",
+ "before",
+ "before test two",
+ "two",
+ "after",
+ "after test two passed",
+ "parent after",
+ "parent before",
+ "before",
+ "before test three",
+ "three",
+ "after",
+ "after test three passed",
+ "parent after",
]);
});
});
diff --git a/test/unit/hook-timeout.spec.js b/test/unit/hook-timeout.spec.js
index b8fe1089..f3a53534 100644
--- a/test/unit/hook-timeout.spec.js
+++ b/test/unit/hook-timeout.spec.js
@@ -1,11 +1,11 @@
-'use strict';
+"use strict";
-describe('hook timeout', function () {
+describe("hook timeout", function () {
before(function (done) {
setTimeout(done, 100);
});
- it('should work', function (done) {
+ it("should work", function (done) {
done();
});
});
diff --git a/test/unit/hook.spec.js b/test/unit/hook.spec.js
index 3ee6c89f..9326cbc7 100644
--- a/test/unit/hook.spec.js
+++ b/test/unit/hook.spec.js
@@ -1,44 +1,44 @@
-'use strict';
-var sinon = require('sinon');
-var Mocha = require('../../lib/mocha');
+"use strict";
+var sinon = require("sinon");
+var Mocha = require("../../lib/mocha");
var Hook = Mocha.Hook;
var Runnable = Mocha.Runnable;
-describe('Hook', function () {
+describe("Hook", function () {
var hook;
beforeEach(function () {
- hook = new Hook('Some hook', function () {});
+ hook = new Hook("Some hook", function () {});
});
afterEach(function () {
sinon.restore();
});
- describe('error', function () {
- it('should set the hook._error', function () {
- var expectedError = new Error('Expected error');
+ describe("error", function () {
+ it("should set the hook._error", function () {
+ var expectedError = new Error("Expected error");
hook.error(expectedError);
- expect(hook._error, 'to be', expectedError);
+ expect(hook._error, "to be", expectedError);
});
- it('should get the hook._error when called without arguments', function () {
- var expectedError = new Error('Expected error');
+ it("should get the hook._error when called without arguments", function () {
+ var expectedError = new Error("Expected error");
hook._error = expectedError;
- expect(hook.error(), 'to be', expectedError);
+ expect(hook.error(), "to be", expectedError);
});
});
- describe('reset', function () {
- it('should call Runnable.reset', function () {
- var runnableResetStub = sinon.stub(Runnable.prototype, 'reset');
+ describe("reset", function () {
+ it("should call Runnable.reset", function () {
+ var runnableResetStub = sinon.stub(Runnable.prototype, "reset");
hook.reset();
- expect(runnableResetStub, 'was called once');
+ expect(runnableResetStub, "was called once");
});
- it('should reset the error state', function () {
- hook.error(new Error('Expected error for test'));
+ it("should reset the error state", function () {
+ hook.error(new Error("Expected error for test"));
hook.reset();
- expect(hook.error(), 'to be undefined');
+ expect(hook.error(), "to be undefined");
});
});
});
diff --git a/test/unit/mocha.spec.js b/test/unit/mocha.spec.js
index 15abd66c..cd985a83 100644
--- a/test/unit/mocha.spec.js
+++ b/test/unit/mocha.spec.js
@@ -1,12 +1,12 @@
-'use strict';
+"use strict";
-var sinon = require('sinon');
-var EventEmitter = require('node:events').EventEmitter;
-var Mocha = require('../../lib/mocha');
-var utils = require('../../lib/utils');
-const errors = require('../../lib/errors');
+var sinon = require("sinon");
+var EventEmitter = require("node:events").EventEmitter;
+var Mocha = require("../../lib/mocha");
+var utils = require("../../lib/utils");
+const errors = require("../../lib/errors");
-describe('Mocha', function () {
+describe("Mocha", function () {
/**
* Options for `Mocha` constructor
*/
@@ -44,22 +44,22 @@ describe('Mocha', function () {
beforeEach(function () {
reporterInstance = {};
- opts = {reporter: sinon.stub().returns(reporterInstance)};
+ opts = { reporter: sinon.stub().returns(reporterInstance) };
// NOTE: calling `stub(someObject, someFunction)` where `someFunction` has
// its own static properties WILL NOT blast those static properties!
- Base = sinon.stub(Mocha.reporters, 'Base').returns({});
- sinon.stub(Mocha.reporters, 'base').returns({});
- sinon.stub(Mocha.reporters, 'spec').returns({});
+ Base = sinon.stub(Mocha.reporters, "Base").returns({});
+ sinon.stub(Mocha.reporters, "base").returns({});
+ sinon.stub(Mocha.reporters, "spec").returns({});
runner = {
...sinon.createStubInstance(EventEmitter),
runAsync: sinon.stub().resolves(0),
globals: sinon.stub(),
grep: sinon.stub(),
- dispose: sinon.stub()
+ dispose: sinon.stub(),
};
- Runner = sinon.stub(Mocha, 'Runner').returns(runner);
+ Runner = sinon.stub(Mocha, "Runner").returns(runner);
// the Runner constructor is the main export, and constants is a static prop.
// we don't need the constants themselves, but the object cannot be undefined
Runner.constants = {};
@@ -73,560 +73,561 @@ describe('Mocha', function () {
beforeAll: sinon.stub(),
beforeEach: sinon.stub(),
afterAll: sinon.stub(),
- afterEach: sinon.stub()
+ afterEach: sinon.stub(),
};
- Suite = sinon.stub(Mocha, 'Suite').returns(suite);
+ Suite = sinon.stub(Mocha, "Suite").returns(suite);
Suite.constants = {};
- sinon.stub(errors, 'warn');
- sinon.stub(utils, 'isString');
- sinon.stub(utils, 'noop');
+ sinon.stub(errors, "warn");
+ sinon.stub(utils, "isString");
+ sinon.stub(utils, "noop");
});
afterEach(function () {
sinon.restore();
});
- describe('constructor', function () {
+ describe("constructor", function () {
var mocha;
beforeEach(function () {
mocha = sinon.createStubInstance(Mocha);
mocha.timeout.returnsThis();
mocha.retries.returnsThis();
- sinon.stub(Mocha.prototype, 'timeout').returnsThis();
- sinon.stub(Mocha.prototype, 'global').returnsThis();
- sinon.stub(Mocha.prototype, 'retries').returnsThis();
- sinon.stub(Mocha.prototype, 'rootHooks').returnsThis();
- sinon.stub(Mocha.prototype, 'parallelMode').returnsThis();
- sinon.stub(Mocha.prototype, 'globalSetup').returnsThis();
- sinon.stub(Mocha.prototype, 'globalTeardown').returnsThis();
- sinon.stub(Mocha.prototype, 'enableGlobalSetup').returnsThis();
- sinon.stub(Mocha.prototype, 'enableGlobalTeardown').returnsThis();
+ sinon.stub(Mocha.prototype, "timeout").returnsThis();
+ sinon.stub(Mocha.prototype, "global").returnsThis();
+ sinon.stub(Mocha.prototype, "retries").returnsThis();
+ sinon.stub(Mocha.prototype, "rootHooks").returnsThis();
+ sinon.stub(Mocha.prototype, "parallelMode").returnsThis();
+ sinon.stub(Mocha.prototype, "globalSetup").returnsThis();
+ sinon.stub(Mocha.prototype, "globalTeardown").returnsThis();
+ sinon.stub(Mocha.prototype, "enableGlobalSetup").returnsThis();
+ sinon.stub(Mocha.prototype, "enableGlobalTeardown").returnsThis();
});
- it('should set _cleanReferencesAfterRun to true', function () {
- expect(new Mocha()._cleanReferencesAfterRun, 'to be', true);
+ it("should set _cleanReferencesAfterRun to true", function () {
+ expect(new Mocha()._cleanReferencesAfterRun, "to be", true);
});
- describe('when `timeout` option is `undefined`', function () {
- it('should not attempt to set timeout', function () {
+ describe("when `timeout` option is `undefined`", function () {
+ it("should not attempt to set timeout", function () {
// eslint-disable-next-line no-new
- new Mocha({timeout: undefined});
- expect(Mocha.prototype.timeout, 'was not called');
+ new Mocha({ timeout: undefined });
+ expect(Mocha.prototype.timeout, "was not called");
});
});
- describe('when `timeout` option is `false`', function () {
- it('should attempt to set timeout', function () {
+ describe("when `timeout` option is `false`", function () {
+ it("should attempt to set timeout", function () {
// eslint-disable-next-line no-new
- new Mocha({timeout: false});
- expect(Mocha.prototype.timeout, 'to have a call satisfying', [0]).and(
- 'was called once'
+ new Mocha({ timeout: false });
+ expect(Mocha.prototype.timeout, "to have a call satisfying", [0]).and(
+ "was called once",
);
});
});
- describe('when `global` option is an `Array`', function () {
- it('should attempt to set globals', function () {
+ describe("when `global` option is an `Array`", function () {
+ it("should attempt to set globals", function () {
// eslint-disable-next-line no-new
- new Mocha({global: ['singular']});
- expect(Mocha.prototype.global, 'to have a call satisfying', [
- ['singular']
- ]).and('was called once');
+ new Mocha({ global: ["singular"] });
+ expect(Mocha.prototype.global, "to have a call satisfying", [
+ ["singular"],
+ ]).and("was called once");
});
});
- describe('when `retries` option is present', function () {
- it('should attempt to set retries`', function () {
+ describe("when `retries` option is present", function () {
+ it("should attempt to set retries`", function () {
// eslint-disable-next-line no-new
- new Mocha({retries: 1});
- expect(Mocha.prototype.retries, 'to have a call satisfying', [1]).and(
- 'was called once'
+ new Mocha({ retries: 1 });
+ expect(Mocha.prototype.retries, "to have a call satisfying", [1]).and(
+ "was called once",
);
});
});
- describe('when `retries` option is not present', function () {
- it('should not attempt to set retries', function () {
+ describe("when `retries` option is not present", function () {
+ it("should not attempt to set retries", function () {
// eslint-disable-next-line no-new
new Mocha({});
- expect(Mocha.prototype.retries, 'was not called');
+ expect(Mocha.prototype.retries, "was not called");
});
});
- describe('when `rootHooks` option is truthy', function () {
- it('shouid attempt to set root hooks', function () {
+ describe("when `rootHooks` option is truthy", function () {
+ it("shouid attempt to set root hooks", function () {
// eslint-disable-next-line no-new
- new Mocha({rootHooks: ['a root hook']});
- expect(Mocha.prototype.rootHooks, 'to have a call satisfying', [
- ['a root hook']
- ]).and('was called once');
+ new Mocha({ rootHooks: ["a root hook"] });
+ expect(Mocha.prototype.rootHooks, "to have a call satisfying", [
+ ["a root hook"],
+ ]).and("was called once");
});
});
- describe('when `parallel` option is true', function () {
- describe('and `jobs` option > 1', function () {
- it('should enable parallel mode', function () {
+ describe("when `parallel` option is true", function () {
+ describe("and `jobs` option > 1", function () {
+ it("should enable parallel mode", function () {
// eslint-disable-next-line no-new
- new Mocha({parallel: true, jobs: 2});
- expect(Mocha.prototype.parallelMode, 'to have a call satisfying', [
- true
- ]).and('was called once');
+ new Mocha({ parallel: true, jobs: 2 });
+ expect(Mocha.prototype.parallelMode, "to have a call satisfying", [
+ true,
+ ]).and("was called once");
});
});
- describe('and `jobs` option <= 1', function () {
- it('should not enable parallel mode', function () {
+ describe("and `jobs` option <= 1", function () {
+ it("should not enable parallel mode", function () {
// eslint-disable-next-line no-new
- new Mocha({parallel: true, jobs: 1});
- expect(Mocha.prototype.parallelMode, 'was not called');
+ new Mocha({ parallel: true, jobs: 1 });
+ expect(Mocha.prototype.parallelMode, "was not called");
});
});
- describe('when `globalSetup` option is present', function () {
- it('should configure global setup fixtures', function () {
+ describe("when `globalSetup` option is present", function () {
+ it("should configure global setup fixtures", function () {
const globalSetup = [() => {}];
- const mocha = new Mocha({globalSetup});
- expect(mocha.globalSetup, 'to have a call satisfying', [
- globalSetup
- ]).and('was called once');
+ const mocha = new Mocha({ globalSetup });
+ expect(mocha.globalSetup, "to have a call satisfying", [
+ globalSetup,
+ ]).and("was called once");
});
});
- describe('when `globalTeardown` option is present', function () {
- it('should configure global teardown fixtures', function () {
+ describe("when `globalTeardown` option is present", function () {
+ it("should configure global teardown fixtures", function () {
const globalTeardown = [() => {}];
- const mocha = new Mocha({globalTeardown});
- expect(mocha.globalTeardown, 'to have a call satisfying', [
- globalTeardown
- ]).and('was called once');
+ const mocha = new Mocha({ globalTeardown });
+ expect(mocha.globalTeardown, "to have a call satisfying", [
+ globalTeardown,
+ ]).and("was called once");
});
});
- describe('when `enableGlobalSetup` option is present', function () {
- it('should toggle global setup fixtures', function () {
- const mocha = new Mocha({enableGlobalSetup: 1});
- expect(mocha.enableGlobalSetup, 'to have a call satisfying', [1]).and(
- 'was called once'
+ describe("when `enableGlobalSetup` option is present", function () {
+ it("should toggle global setup fixtures", function () {
+ const mocha = new Mocha({ enableGlobalSetup: 1 });
+ expect(mocha.enableGlobalSetup, "to have a call satisfying", [1]).and(
+ "was called once",
);
});
});
- describe('when `enableGlobalTeardown` option is present', function () {
- it('should configure global teardown fixtures', function () {
- const mocha = new Mocha({enableGlobalTeardown: 1});
- expect(mocha.enableGlobalTeardown, 'to have a call satisfying', [
- 1
- ]).and('was called once');
+ describe("when `enableGlobalTeardown` option is present", function () {
+ it("should configure global teardown fixtures", function () {
+ const mocha = new Mocha({ enableGlobalTeardown: 1 });
+ expect(mocha.enableGlobalTeardown, "to have a call satisfying", [
+ 1,
+ ]).and("was called once");
});
});
});
});
- describe('instance method', function () {
+ describe("instance method", function () {
var mocha;
beforeEach(function () {
mocha = new Mocha(opts);
});
- describe('allowUncaught()', function () {
- it('should set the allowUncaught option to true', function () {
+ describe("allowUncaught()", function () {
+ it("should set the allowUncaught option to true", function () {
mocha.allowUncaught();
- expect(mocha.options, 'to have property', 'allowUncaught', true);
+ expect(mocha.options, "to have property", "allowUncaught", true);
});
- it('should set the allowUncaught option to false', function () {
+ it("should set the allowUncaught option to false", function () {
mocha.allowUncaught(false);
- expect(mocha.options, 'to have property', 'allowUncaught', false);
+ expect(mocha.options, "to have property", "allowUncaught", false);
});
- it('should be chainable', function () {
- expect(mocha.allowUncaught(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.allowUncaught(), "to be", mocha);
});
});
- describe('asyncOnly()', function () {
- it('should set the asyncOnly option to true', function () {
+ describe("asyncOnly()", function () {
+ it("should set the asyncOnly option to true", function () {
mocha.asyncOnly();
- expect(mocha.options, 'to have property', 'asyncOnly', true);
+ expect(mocha.options, "to have property", "asyncOnly", true);
});
- it('should set the asyncOnly option to false', function () {
+ it("should set the asyncOnly option to false", function () {
mocha.asyncOnly(false);
- expect(mocha.options, 'to have property', 'asyncOnly', false);
+ expect(mocha.options, "to have property", "asyncOnly", false);
});
- it('should be chainable', function () {
- expect(mocha.asyncOnly(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.asyncOnly(), "to be", mocha);
});
});
- describe('bail()', function () {
+ describe("bail()", function () {
it('should set the "bail" flag on the root suite', function () {
mocha.bail();
- expect(suite.bail, 'to have a call satisfying', [true]).and(
- 'was called once'
+ expect(suite.bail, "to have a call satisfying", [true]).and(
+ "was called once",
);
});
it('should unset the "bail" flag on the root suite', function () {
mocha.bail(false);
- expect(suite.bail, 'to have a call satisfying', [false]).and(
- 'was called once'
+ expect(suite.bail, "to have a call satisfying", [false]).and(
+ "was called once",
);
});
- it('should be chainable', function () {
- expect(mocha.bail(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.bail(), "to be", mocha);
});
});
- describe('checkLeaks()', function () {
- it('should set the checkLeaks option to true', function () {
+ describe("checkLeaks()", function () {
+ it("should set the checkLeaks option to true", function () {
mocha.checkLeaks();
- expect(mocha.options, 'to have property', 'checkLeaks', true);
+ expect(mocha.options, "to have property", "checkLeaks", true);
});
});
- describe('cleanReferencesAfterRun()', function () {
- it('should set the _cleanReferencesAfterRun attribute', function () {
+ describe("cleanReferencesAfterRun()", function () {
+ it("should set the _cleanReferencesAfterRun attribute", function () {
mocha.cleanReferencesAfterRun();
- expect(mocha._cleanReferencesAfterRun, 'to be', true);
+ expect(mocha._cleanReferencesAfterRun, "to be", true);
});
- it('should set the _cleanReferencesAfterRun attribute to false', function () {
+ it("should set the _cleanReferencesAfterRun attribute to false", function () {
mocha.cleanReferencesAfterRun(false);
- expect(mocha._cleanReferencesAfterRun, 'to be', false);
+ expect(mocha._cleanReferencesAfterRun, "to be", false);
});
- it('should be chainable', function () {
- expect(mocha.cleanReferencesAfterRun(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.cleanReferencesAfterRun(), "to be", mocha);
});
});
- describe('color()', function () {
- it('should set the color option to true', function () {
+ describe("color()", function () {
+ it("should set the color option to true", function () {
mocha.color();
- expect(mocha.options, 'to have property', 'color', true);
+ expect(mocha.options, "to have property", "color", true);
});
- it('should set the color option to false', function () {
+ it("should set the color option to false", function () {
mocha.color(false);
- expect(mocha.options, 'to have property', 'color', false);
+ expect(mocha.options, "to have property", "color", false);
});
- it('should be chainable', function () {
- expect(mocha.color(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.color(), "to be", mocha);
});
});
- describe('delay()', function () {
- it('should set the delay option to true', function () {
+ describe("delay()", function () {
+ it("should set the delay option to true", function () {
mocha.delay();
- expect(mocha.options, 'to have property', 'delay', true);
+ expect(mocha.options, "to have property", "delay", true);
});
- it('should be chainable', function () {
- expect(mocha.delay(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.delay(), "to be", mocha);
});
});
- describe('diff()', function () {
- it('should set the diff option to true', function () {
+ describe("diff()", function () {
+ it("should set the diff option to true", function () {
mocha.diff();
- expect(mocha.options, 'to have property', 'diff', true);
+ expect(mocha.options, "to have property", "diff", true);
});
- it('should set the diff option to false', function () {
+ it("should set the diff option to false", function () {
mocha.diff(false);
- expect(mocha.options, 'to have property', 'diff', false);
+ expect(mocha.options, "to have property", "diff", false);
});
});
- describe('dispose()', function () {
- it('should dispose the root suite', function () {
+ describe("dispose()", function () {
+ it("should dispose the root suite", function () {
mocha.dispose();
- expect(suite.dispose, 'was called once');
+ expect(suite.dispose, "was called once");
});
- it('should dispose previous test runner', function () {
+ it("should dispose previous test runner", function () {
mocha._previousRunner = runner;
mocha.dispose();
- expect(runner.dispose, 'was called once');
+ expect(runner.dispose, "was called once");
});
- it('should unload the files', function () {
- var unloadFilesStub = sinon.stub(mocha, 'unloadFiles');
+ it("should unload the files", function () {
+ var unloadFilesStub = sinon.stub(mocha, "unloadFiles");
mocha.dispose();
- expect(unloadFilesStub, 'was called once');
+ expect(unloadFilesStub, "was called once");
});
});
- describe('dryRun()', function () {
- it('should set the dryRun option to true', function () {
+ describe("dryRun()", function () {
+ it("should set the dryRun option to true", function () {
mocha.dryRun();
- expect(mocha.options, 'to have property', 'dryRun', true);
+ expect(mocha.options, "to have property", "dryRun", true);
});
- it('should set the dryRun option to false', function () {
+ it("should set the dryRun option to false", function () {
mocha.dryRun(false);
- expect(mocha.options, 'to have property', 'dryRun', false);
+ expect(mocha.options, "to have property", "dryRun", false);
});
});
- describe('passOnFailingTestSuite()', function() {
- it('should set the passOnFailingTestSuite option to false', function() {
+ describe("passOnFailingTestSuite()", function () {
+ it("should set the passOnFailingTestSuite option to false", function () {
mocha.passOnFailingTestSuite();
expect(
mocha.options,
- 'to have property',
- 'passOnFailingTestSuite',
- false
+ "to have property",
+ "passOnFailingTestSuite",
+ false,
);
});
- it('should set the passOnFailingTestSuite option to true', function() {
+ it("should set the passOnFailingTestSuite option to true", function () {
mocha.passOnFailingTestSuite(true);
expect(
mocha.options,
- 'to have property',
- 'passOnFailingTestSuite',
- true
+ "to have property",
+ "passOnFailingTestSuite",
+ true,
);
});
});
- describe('failZero()', function () {
- it('should set the failZero option to true', function () {
+ describe("failZero()", function () {
+ it("should set the failZero option to true", function () {
mocha.failZero();
- expect(mocha.options, 'to have property', 'failZero', true);
+ expect(mocha.options, "to have property", "failZero", true);
});
- it('should set the failZero option to false', function () {
+ it("should set the failZero option to false", function () {
mocha.failZero(false);
- expect(mocha.options, 'to have property', 'failZero', false);
+ expect(mocha.options, "to have property", "failZero", false);
});
});
- describe('forbidOnly()', function () {
- it('should set the forbidOnly option to true', function () {
+ describe("forbidOnly()", function () {
+ it("should set the forbidOnly option to true", function () {
mocha.forbidOnly();
- expect(mocha.options, 'to have property', 'forbidOnly', true);
+ expect(mocha.options, "to have property", "forbidOnly", true);
});
- it('should set the forbidOnly option to false', function () {
+ it("should set the forbidOnly option to false", function () {
mocha.forbidOnly(false);
- expect(mocha.options, 'to have property', 'forbidOnly', false);
+ expect(mocha.options, "to have property", "forbidOnly", false);
});
- it('should be chainable', function () {
- expect(mocha.forbidOnly(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.forbidOnly(), "to be", mocha);
});
});
- describe('forbidPending()', function () {
- it('should set the forbidPending option to true', function () {
+ describe("forbidPending()", function () {
+ it("should set the forbidPending option to true", function () {
mocha.forbidPending();
- expect(mocha.options, 'to have property', 'forbidPending', true);
+ expect(mocha.options, "to have property", "forbidPending", true);
});
- it('should set the forbidPending option to false', function () {
+ it("should set the forbidPending option to false", function () {
mocha.forbidPending(false);
- expect(mocha.options, 'to have property', 'forbidPending', false);
+ expect(mocha.options, "to have property", "forbidPending", false);
});
- it('should be chainable', function () {
- expect(mocha.forbidPending(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.forbidPending(), "to be", mocha);
});
});
- describe('fullTrace()', function () {
- it('should set the fullTrace option to true', function () {
+ describe("fullTrace()", function () {
+ it("should set the fullTrace option to true", function () {
mocha.fullTrace();
- expect(mocha.options, 'to have property', 'fullTrace', true);
+ expect(mocha.options, "to have property", "fullTrace", true);
});
- it('should set the fullTrace option to false', function () {
+ it("should set the fullTrace option to false", function () {
mocha.fullTrace(false);
- expect(mocha.options, 'to have property', 'fullTrace', false);
+ expect(mocha.options, "to have property", "fullTrace", false);
});
- it('should be chainable', function () {
- expect(mocha.fullTrace(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.fullTrace(), "to be", mocha);
});
});
- describe('global()', function () {
- it('should be an empty array initially', function () {
- expect(mocha.options.global, 'to be empty');
+ describe("global()", function () {
+ it("should be an empty array initially", function () {
+ expect(mocha.options.global, "to be empty");
});
- it('should be chainable', function () {
- expect(mocha.global(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.global(), "to be", mocha);
});
- describe('when argument is invalid', function () {
- it('should not modify the whitelist when given empty string', function () {
- mocha.global('');
- expect(mocha.options.global, 'to be empty');
+ describe("when argument is invalid", function () {
+ it("should not modify the whitelist when given empty string", function () {
+ mocha.global("");
+ expect(mocha.options.global, "to be empty");
});
- it('should not modify the whitelist when given empty array', function () {
+ it("should not modify the whitelist when given empty array", function () {
mocha.global([]);
- expect(mocha.options.global, 'to be empty');
+ expect(mocha.options.global, "to be empty");
});
});
- describe('when argument is valid', function () {
- var elem = 'foo';
- var elem2 = 'bar';
- var elem3 = 'baz';
+ describe("when argument is valid", function () {
+ var elem = "foo";
+ var elem2 = "bar";
+ var elem3 = "baz";
- it('should add string to the whitelist', function () {
+ it("should add string to the whitelist", function () {
mocha.global(elem);
- expect(mocha.options.global, 'to contain', elem);
- expect(mocha.options.global, 'to have length', 1);
+ expect(mocha.options.global, "to contain", elem);
+ expect(mocha.options.global, "to have length", 1);
});
- it('should add contents of string array to the whitelist', function () {
+ it("should add contents of string array to the whitelist", function () {
var elems = [elem, elem2];
mocha.global(elems);
- expect(mocha.options.global, 'to contain', elem, elem2);
- expect(mocha.options.global, 'to have length', elems.length);
+ expect(mocha.options.global, "to contain", elem, elem2);
+ expect(mocha.options.global, "to have length", elems.length);
});
- it('should not have duplicates', function () {
- var mocha = new Mocha({global: [elem, elem2]});
+ it("should not have duplicates", function () {
+ var mocha = new Mocha({ global: [elem, elem2] });
var elems = [elem, elem2, elem3];
mocha.global(elems);
- expect(mocha.options.global, 'to contain', elem, elem2, elem3);
- expect(mocha.options.global, 'to have length', elems.length);
+ expect(mocha.options.global, "to contain", elem, elem2, elem3);
+ expect(mocha.options.global, "to have length", elems.length);
});
});
});
- describe('inlineDiffs()', function () {
- it('should set the inlineDiffs option to true', function () {
+ describe("inlineDiffs()", function () {
+ it("should set the inlineDiffs option to true", function () {
mocha.inlineDiffs();
- expect(mocha.options, 'to have property', 'inlineDiffs', true);
+ expect(mocha.options, "to have property", "inlineDiffs", true);
});
- it('should set the inlineDiffs option to false', function () {
+ it("should set the inlineDiffs option to false", function () {
mocha.inlineDiffs(false);
- expect(mocha.options, 'to have property', 'inlineDiffs', false);
+ expect(mocha.options, "to have property", "inlineDiffs", false);
});
- it('should be chainable', function () {
- expect(mocha.inlineDiffs(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.inlineDiffs(), "to be", mocha);
});
});
- describe('invert()', function () {
- it('should set the invert option to true', function () {
+ describe("invert()", function () {
+ it("should set the invert option to true", function () {
mocha.invert();
- expect(mocha.options, 'to have property', 'invert', true);
+ expect(mocha.options, "to have property", "invert", true);
});
- it('should be chainable', function () {
- expect(mocha.invert(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.invert(), "to be", mocha);
});
});
- describe('noHighlighting()', function () {
+ describe("noHighlighting()", function () {
// :NOTE: Browser-only option...
- it('should set the noHighlighting option to true', function () {
+ it("should set the noHighlighting option to true", function () {
mocha.noHighlighting();
- expect(mocha.options, 'to have property', 'noHighlighting', true);
+ expect(mocha.options, "to have property", "noHighlighting", true);
});
- it('should be chainable', function () {
- expect(mocha.noHighlighting(), 'to be', mocha);
+ it("should be chainable", function () {
+ expect(mocha.noHighlighting(), "to be", mocha);
});
});
- describe('reporter()', function () {
- it('should be chainable', function () {
- expect(mocha.reporter(), 'to be', mocha);
+ describe("reporter()", function () {
+ it("should be chainable", function () {
+ expect(mocha.reporter(), "to be", mocha);
});
- it('should keep reporterOption on options', function () {
+ it("should keep reporterOption on options", function () {
var mocha = new Mocha({
- reporter: 'spec',
+ reporter: "spec",
reporterOption: {
- foo: 'bar'
- }
+ foo: "bar",
+ },
});
- expect(mocha.options.reporterOption, 'to have property', 'foo', 'bar');
+ expect(mocha.options.reporterOption, "to have property", "foo", "bar");
// To support the legacy property name that can be used by reporters
- expect(mocha.options.reporterOptions, 'to have property', 'foo', 'bar');
+ expect(mocha.options.reporterOptions, "to have property", "foo", "bar");
});
- it('should support legacy reporterOptions', function () {
+ it("should support legacy reporterOptions", function () {
var mocha = new Mocha({
- reporter: 'spec',
+ reporter: "spec",
reporterOptions: {
- foo: 'bar'
- }
+ foo: "bar",
+ },
});
- expect(mocha.options.reporterOption, 'to have property', 'foo', 'bar');
+ expect(mocha.options.reporterOption, "to have property", "foo", "bar");
// To support the legacy property name that can be used by reporters
- expect(mocha.options.reporterOptions, 'to have property', 'foo', 'bar');
+ expect(mocha.options.reporterOptions, "to have property", "foo", "bar");
});
});
- describe('run()', function () {
+ describe("run()", function () {
let globalFixtureContext;
beforeEach(function () {
globalFixtureContext = {};
- sinon.stub(mocha, 'runGlobalSetup').returns(globalFixtureContext);
- sinon.stub(mocha, 'runGlobalTeardown').returns(globalFixtureContext);
+ sinon.stub(mocha, "runGlobalSetup").returns(globalFixtureContext);
+ sinon.stub(mocha, "runGlobalTeardown").returns(globalFixtureContext);
});
- describe('when files have been added to the Mocha instance', function () {
+ describe("when files have been added to the Mocha instance", function () {
beforeEach(function () {
- sinon.stub(mocha, 'loadFiles');
- mocha.addFile('some-file.js');
+ sinon.stub(mocha, "loadFiles");
+ mocha.addFile("some-file.js");
});
- describe('when Mocha is set to eagerly load files', function () {
- it('should eagerly load files', function (done) {
+ describe("when Mocha is set to eagerly load files", function () {
+ it("should eagerly load files", function (done) {
mocha.run(function () {
- expect(mocha.loadFiles, 'was called once');
+ expect(mocha.loadFiles, "was called once");
done();
});
});
});
- describe('when Mocha is set to lazily load files', function () {
+ describe("when Mocha is set to lazily load files", function () {
beforeEach(function () {
mocha.lazyLoadFiles(true);
});
- it('should not eagerly load files', function (done) {
+ it("should not eagerly load files", function (done) {
mocha.run(function () {
- expect(mocha.loadFiles, 'was not called');
+ expect(mocha.loadFiles, "was not called");
done();
});
});
});
});
- describe('Runner initialization', function () {
- it('should instantiate a Runner', function (done) {
+ describe("Runner initialization", function () {
+ it("should instantiate a Runner", function (done) {
mocha.run(function () {
- expect(Runner, 'to have a call satisfying', {
+ expect(Runner, "to have a call satisfying", {
calledWithNew: true,
args: [
mocha.suite,
{
delay: mocha.options.delay,
- cleanReferencesAfterRun: mocha.options.cleanReferencesAfterRun
- }
- ]
- }).and('was called once');
+ cleanReferencesAfterRun:
+ mocha.options.cleanReferencesAfterRun,
+ },
+ ],
+ }).and("was called once");
done();
});
});
@@ -639,10 +640,10 @@ describe('Mocha', function () {
it('should configure "grep"', function (done) {
mocha.run(function () {
- expect(runner.grep, 'to have a call satisfying', [
+ expect(runner.grep, "to have a call satisfying", [
mocha.options.grep,
- mocha.options.invert
- ]).and('was called once');
+ mocha.options.invert,
+ ]).and("was called once");
done();
});
});
@@ -650,66 +651,66 @@ describe('Mocha', function () {
describe('when "global" option is present', function () {
beforeEach(function () {
- mocha.options.global = ['foo', 'bar'];
+ mocha.options.global = ["foo", "bar"];
});
- it('should configure global vars', function (done) {
+ it("should configure global vars", function (done) {
mocha.run(function () {
- expect(runner.globals, 'to have a call satisfying', [
- mocha.options.global
- ]).and('was called once');
+ expect(runner.globals, "to have a call satisfying", [
+ mocha.options.global,
+ ]).and("was called once");
done();
});
});
});
});
- describe('Base reporter initialization', function () {
+ describe("Base reporter initialization", function () {
beforeEach(function () {
- mocha.options.inlineDiffs = 'some value';
+ mocha.options.inlineDiffs = "some value";
mocha.options.diff = false;
});
describe('when "color" options is set', function () {
beforeEach(function () {
- mocha.options.color = 'truthy';
+ mocha.options.color = "truthy";
});
- it('should configure the Base reporter', function (done) {
+ it("should configure the Base reporter", function (done) {
mocha.run(function () {
- expect(Base, 'to satisfy', {
- inlineDiffs: 'some value',
+ expect(Base, "to satisfy", {
+ inlineDiffs: "some value",
hideDiff: true,
- useColors: 'truthy'
+ useColors: "truthy",
});
done();
});
});
});
- it('should configure the Base reporter', function (done) {
+ it("should configure the Base reporter", function (done) {
mocha.run(function () {
- expect(Base, 'to satisfy', {
- inlineDiffs: 'some value',
- hideDiff: true
+ expect(Base, "to satisfy", {
+ inlineDiffs: "some value",
+ hideDiff: true,
});
done();
});
});
});
- it('should instantiate a reporter', function (done) {
+ it("should instantiate a reporter", function (done) {
mocha.run(function () {
- expect(opts.reporter, 'to have a call satisfying', {
+ expect(opts.reporter, "to have a call satisfying", {
calledWithNew: true,
- args: [runner, mocha.options]
- }).and('was called once');
+ args: [runner, mocha.options],
+ }).and("was called once");
done();
});
});
// TODO: figure out how to stub the stats collector
- it('should initialize the stats collector');
+ it("should initialize the stats collector");
describe('when a reporter instance has a "done" method', function () {
beforeEach(function () {
@@ -718,73 +719,73 @@ describe('Mocha', function () {
it('should call the reporter "done" method', function (done) {
mocha.run(function () {
- expect(reporterInstance.done, 'was called once');
+ expect(reporterInstance.done, "was called once");
done();
});
});
});
- it('should execute the callback when complete', function (done) {
+ it("should execute the callback when complete", function (done) {
mocha.run(done);
});
- describe('when a run is in progress', function () {
- it('should throw', function (done) {
+ describe("when a run is in progress", function () {
+ it("should throw", function (done) {
mocha.run(done); // this is async!
expect(
function () {
mocha.run();
},
- 'to throw',
+ "to throw",
{
- code: 'ERR_MOCHA_INSTANCE_ALREADY_RUNNING',
- instance: mocha
- }
+ code: "ERR_MOCHA_INSTANCE_ALREADY_RUNNING",
+ instance: mocha,
+ },
);
});
- it('should not call `Runner#runAsync`', function (done) {
+ it("should not call `Runner#runAsync`", function (done) {
mocha.run(done); // this is async!
try {
mocha.run();
} catch (ignored) {
} finally {
// it'll be 0 or 1, depending on timing.
- expect(runner.runAsync.callCount, 'to be less than', 2);
+ expect(runner.runAsync.callCount, "to be less than", 2);
}
});
});
- describe('when the `Mocha` instance is already disposed', function () {
+ describe("when the `Mocha` instance is already disposed", function () {
beforeEach(function () {
mocha.dispose();
});
- it('should throw', function () {
+ it("should throw", function () {
expect(
function () {
mocha.run();
},
- 'to throw',
+ "to throw",
{
- code: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED',
+ code: "ERR_MOCHA_INSTANCE_ALREADY_DISPOSED",
cleanReferencesAfterRun: true,
- instance: mocha
- }
+ instance: mocha,
+ },
);
});
- it('should not call `Runner#runAsync`', function () {
+ it("should not call `Runner#runAsync`", function () {
try {
mocha.run();
} catch (ignored) {
} finally {
- expect(runner.runAsync, 'was not called');
+ expect(runner.runAsync, "was not called");
}
});
});
- describe('when a run has finished and is called again', function () {
+ describe("when a run has finished and is called again", function () {
beforeEach(function (done) {
mocha.run(function () {
runner.runAsync.reset();
@@ -792,177 +793,177 @@ describe('Mocha', function () {
});
});
- it('should throw', function () {
+ it("should throw", function () {
expect(
function () {
mocha.run();
},
- 'to throw',
+ "to throw",
{
- code: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED',
- instance: mocha
- }
+ code: "ERR_MOCHA_INSTANCE_ALREADY_DISPOSED",
+ instance: mocha,
+ },
);
});
- it('should not call `Runner#runAsync()`', function () {
+ it("should not call `Runner#runAsync()`", function () {
try {
mocha.run();
} catch (ignored) {
} finally {
- expect(runner.runAsync, 'was not called');
+ expect(runner.runAsync, "was not called");
}
});
});
- describe('when Mocha configured for multiple runs and multiple runs are attempted', function () {
+ describe("when Mocha configured for multiple runs and multiple runs are attempted", function () {
beforeEach(function () {
mocha.cleanReferencesAfterRun(false);
});
- it('should not throw', function (done) {
+ it("should not throw", function (done) {
mocha.run(function () {
mocha.run(done);
});
});
- it('should call `Runner#runAsync` for each call', function (done) {
+ it("should call `Runner#runAsync` for each call", function (done) {
mocha.run(function () {
mocha.run(function () {
- expect(runner.runAsync, 'was called twice');
+ expect(runner.runAsync, "was called twice");
done();
});
});
});
- it('should reset the root Suite between runs', function (done) {
+ it("should reset the root Suite between runs", function (done) {
mocha.run(function () {
mocha.run(function () {
- expect(suite.reset, 'was called once');
+ expect(suite.reset, "was called once");
done();
});
});
});
- it('should dispose the previous runner', function (done) {
+ it("should dispose the previous runner", function (done) {
mocha.run(function () {
mocha.run(function () {
- expect(runner.dispose, 'was called once');
+ expect(runner.dispose, "was called once");
done();
});
});
});
});
- describe('when global setup fixtures enabled', function () {
+ describe("when global setup fixtures enabled", function () {
beforeEach(function () {
mocha.options.enableGlobalSetup = true;
});
- describe('when global setup fixtures not present', function () {
+ describe("when global setup fixtures not present", function () {
beforeEach(function () {
- sinon.stub(mocha, 'hasGlobalSetupFixtures').returns(false);
+ sinon.stub(mocha, "hasGlobalSetupFixtures").returns(false);
});
- it('should not run global setup fixtures', function (done) {
+ it("should not run global setup fixtures", function (done) {
mocha.run(() => {
- expect(mocha.runGlobalSetup, 'was not called');
+ expect(mocha.runGlobalSetup, "was not called");
done();
});
});
});
- describe('when global setup fixtures are present', function () {
+ describe("when global setup fixtures are present", function () {
beforeEach(function () {
- sinon.stub(mocha, 'hasGlobalSetupFixtures').returns(true);
+ sinon.stub(mocha, "hasGlobalSetupFixtures").returns(true);
});
- it('should run global setup fixtures', function (done) {
+ it("should run global setup fixtures", function (done) {
mocha.run(() => {
- expect(mocha.runGlobalSetup, 'to have a call satisfying', {
- args: [expect.it('to be', runner)]
- }).and('was called once');
+ expect(mocha.runGlobalSetup, "to have a call satisfying", {
+ args: [expect.it("to be", runner)],
+ }).and("was called once");
done();
});
});
});
});
- describe('when global setup fixtures disabled', function () {
+ describe("when global setup fixtures disabled", function () {
beforeEach(function () {
mocha.options.enableGlobalSetup = false;
});
- describe('when global setup fixtures not present', function () {
+ describe("when global setup fixtures not present", function () {
beforeEach(function () {
- sinon.stub(mocha, 'hasGlobalSetupFixtures').returns(false);
+ sinon.stub(mocha, "hasGlobalSetupFixtures").returns(false);
});
- it('should not run global setup fixtures', function (done) {
+ it("should not run global setup fixtures", function (done) {
mocha.run(() => {
- expect(mocha.runGlobalSetup, 'was not called');
+ expect(mocha.runGlobalSetup, "was not called");
done();
});
});
});
- describe('when global setup fixtures are present', function () {
+ describe("when global setup fixtures are present", function () {
beforeEach(function () {
- sinon.stub(mocha, 'hasGlobalSetupFixtures').returns(true);
+ sinon.stub(mocha, "hasGlobalSetupFixtures").returns(true);
});
- it('should not run global setup fixtures', function (done) {
+ it("should not run global setup fixtures", function (done) {
mocha.run(() => {
- expect(mocha.runGlobalSetup, 'was not called');
+ expect(mocha.runGlobalSetup, "was not called");
done();
});
});
});
});
- describe('when global teardown fixtures enabled', function () {
+ describe("when global teardown fixtures enabled", function () {
beforeEach(function () {
mocha.options.enableGlobalTeardown = true;
});
- describe('when global teardown fixtures not present', function () {
+ describe("when global teardown fixtures not present", function () {
beforeEach(function () {
- sinon.stub(mocha, 'hasGlobalTeardownFixtures').returns(false);
+ sinon.stub(mocha, "hasGlobalTeardownFixtures").returns(false);
});
- it('should not run global teardown fixtures', function (done) {
+ it("should not run global teardown fixtures", function (done) {
mocha.run(() => {
- expect(mocha.runGlobalTeardown, 'was not called');
+ expect(mocha.runGlobalTeardown, "was not called");
done();
});
});
});
- describe('when global teardown fixtures are present', function () {
+ describe("when global teardown fixtures are present", function () {
beforeEach(function () {
- sinon.stub(mocha, 'hasGlobalTeardownFixtures').returns(true);
+ sinon.stub(mocha, "hasGlobalTeardownFixtures").returns(true);
});
- it('should run global teardown fixtures', function (done) {
+ it("should run global teardown fixtures", function (done) {
mocha.run(() => {
- expect(mocha.runGlobalTeardown, 'to have a call satisfying', {
- args: [expect.it('to be', runner), {context: {}}]
- }).and('was called once');
+ expect(mocha.runGlobalTeardown, "to have a call satisfying", {
+ args: [expect.it("to be", runner), { context: {} }],
+ }).and("was called once");
done();
});
});
- describe('when global setup fixtures are present and enabled', function () {
+ describe("when global setup fixtures are present and enabled", function () {
beforeEach(function () {
- sinon.stub(mocha, 'hasGlobalSetupFixtures').returns(true);
+ sinon.stub(mocha, "hasGlobalSetupFixtures").returns(true);
mocha.options.enableGlobalSetup = true;
});
- it('should use the same context as returned by `runGlobalSetup`', function (done) {
+ it("should use the same context as returned by `runGlobalSetup`", function (done) {
mocha.run(() => {
- expect(mocha.runGlobalTeardown, 'to have a call satisfying', {
+ expect(mocha.runGlobalTeardown, "to have a call satisfying", {
args: [
- expect.it('to be', runner),
- {context: globalFixtureContext}
- ]
- }).and('was called once');
+ expect.it("to be", runner),
+ { context: globalFixtureContext },
+ ],
+ }).and("was called once");
done();
});
});
@@ -970,31 +971,31 @@ describe('Mocha', function () {
});
});
- describe('when global teardown fixtures disabled', function () {
+ describe("when global teardown fixtures disabled", function () {
beforeEach(function () {
mocha.options.enableGlobalTeardown = false;
});
- describe('when global teardown fixtures not present', function () {
+ describe("when global teardown fixtures not present", function () {
beforeEach(function () {
- sinon.stub(mocha, 'hasGlobalTeardownFixtures').returns(false);
+ sinon.stub(mocha, "hasGlobalTeardownFixtures").returns(false);
});
- it('should not run global teardown fixtures', function (done) {
+ it("should not run global teardown fixtures", function (done) {
mocha.run(() => {
- expect(mocha.runGlobalTeardown, 'was not called');
+ expect(mocha.runGlobalTeardown, "was not called");
done();
});
});
});
- describe('when global teardown fixtures are present', function () {
+ describe("when global teardown fixtures are present", function () {
beforeEach(function () {
- sinon.stub(mocha, 'hasGlobalTeardownFixtures').returns(true);
+ sinon.stub(mocha, "hasGlobalTeardownFixtures").returns(true);
});
- it('should not run global teardown fixtures', function (done) {
+ it("should not run global teardown fixtures", function (done) {
mocha.run(() => {
- expect(mocha.runGlobalTeardown, 'was not called');
+ expect(mocha.runGlobalTeardown, "was not called");
done();
});
});
@@ -1002,237 +1003,237 @@ describe('Mocha', function () {
});
});
- describe('parallelMode()', function () {
- describe('when `Mocha` is running in a browser', function () {
+ describe("parallelMode()", function () {
+ describe("when `Mocha` is running in a browser", function () {
beforeEach(function () {
- sinon.stub(utils, 'isBrowser').returns(true);
+ sinon.stub(utils, "isBrowser").returns(true);
});
- it('should throw', function () {
+ it("should throw", function () {
expect(
function () {
mocha.parallelMode();
},
- 'to throw',
- {code: 'ERR_MOCHA_UNSUPPORTED'}
+ "to throw",
+ { code: "ERR_MOCHA_UNSUPPORTED" },
);
});
});
});
- describe('unloadFile()', function () {
- describe('when run in a browser', function () {
+ describe("unloadFile()", function () {
+ describe("when run in a browser", function () {
beforeEach(function () {
- sinon.stub(utils, 'isBrowser').returns(true);
+ sinon.stub(utils, "isBrowser").returns(true);
});
- it('should throw', function () {
- expect(() => Mocha.unloadFile('guy-fieri.js'), 'to throw', {
- code: 'ERR_MOCHA_UNSUPPORTED'
+ it("should throw", function () {
+ expect(() => Mocha.unloadFile("guy-fieri.js"), "to throw", {
+ code: "ERR_MOCHA_UNSUPPORTED",
});
});
});
});
- describe('_runGlobalFixtures()', function () {
- it('should execute multiple fixtures in order', async function () {
+ describe("_runGlobalFixtures()", function () {
+ it("should execute multiple fixtures in order", async function () {
const fixtures = [
- sinon.stub().resolves('foo'),
- sinon.stub().returns('bar')
+ sinon.stub().resolves("foo"),
+ sinon.stub().returns("bar"),
];
const context = await mocha._runGlobalFixtures(fixtures);
- return expect(fixtures, 'to satisfy', [
- expect.it('to have a call satisfying', {
+ return expect(fixtures, "to satisfy", [
+ expect.it("to have a call satisfying", {
thisValue: context,
- returnValue: expect.it('to be fulfilled with', 'foo')
+ returnValue: expect.it("to be fulfilled with", "foo"),
}),
- expect.it('to have a call satisfying', {
+ expect.it("to have a call satisfying", {
thisValue: context,
- returnValue: 'bar'
- })
+ returnValue: "bar",
+ }),
]);
});
});
- describe('runGlobalSetup()', function () {
+ describe("runGlobalSetup()", function () {
let context;
beforeEach(function () {
- sinon.stub(mocha, '_runGlobalFixtures').resolvesArg(1);
+ sinon.stub(mocha, "_runGlobalFixtures").resolvesArg(1);
context = {};
});
- describe('when fixture(s) are present', function () {
+ describe("when fixture(s) are present", function () {
beforeEach(function () {
mocha.options.globalSetup = [sinon.spy()];
});
- it('should attempt run the fixtures', async function () {
+ it("should attempt run the fixtures", async function () {
await mocha.runGlobalSetup(context);
- expect(mocha._runGlobalFixtures, 'to have a call satisfying', [
+ expect(mocha._runGlobalFixtures, "to have a call satisfying", [
mocha.options.globalSetup,
- context
+ context,
]);
});
});
- describe('when a fixture is not present', function () {
- it('should not attempt to run fixtures', async function () {
+ describe("when a fixture is not present", function () {
+ it("should not attempt to run fixtures", async function () {
await mocha.runGlobalSetup();
- expect(mocha._runGlobalFixtures, 'was not called');
+ expect(mocha._runGlobalFixtures, "was not called");
});
});
});
- describe('runGlobalTeardown()', function () {
+ describe("runGlobalTeardown()", function () {
let context;
beforeEach(function () {
- sinon.stub(mocha, '_runGlobalFixtures').resolvesArg(1);
+ sinon.stub(mocha, "_runGlobalFixtures").resolvesArg(1);
context = {};
});
- describe('when fixture(s) are present', function () {
+ describe("when fixture(s) are present", function () {
beforeEach(function () {
mocha.options.globalTeardown = [sinon.spy()];
});
- it('should attempt to run the fixtures', async function () {
+ it("should attempt to run the fixtures", async function () {
await mocha.runGlobalTeardown();
- expect(mocha._runGlobalFixtures, 'to have a call satisfying', [
+ expect(mocha._runGlobalFixtures, "to have a call satisfying", [
mocha.options.globalTeardown,
- context
+ context,
]);
});
});
- describe('when a fixture is not present', function () {
- it('not attempt to run the fixtures', async function () {
+ describe("when a fixture is not present", function () {
+ it("not attempt to run the fixtures", async function () {
await mocha.runGlobalTeardown();
- expect(mocha._runGlobalFixtures, 'was not called');
+ expect(mocha._runGlobalFixtures, "was not called");
});
});
});
- describe('hasGlobalSetupFixtures()', function () {
- describe('when one or more global setup fixtures are present', function () {
- it('should return `true`', function () {
+ describe("hasGlobalSetupFixtures()", function () {
+ describe("when one or more global setup fixtures are present", function () {
+ it("should return `true`", function () {
mocha.options.globalSetup = [() => {}];
- expect(mocha.hasGlobalSetupFixtures(), 'to be true');
+ expect(mocha.hasGlobalSetupFixtures(), "to be true");
});
});
- describe('when no global setup fixtures are present', function () {
- it('should return `false`', function () {
+ describe("when no global setup fixtures are present", function () {
+ it("should return `false`", function () {
mocha.options.globalSetup = [];
- expect(mocha.hasGlobalSetupFixtures(), 'to be false');
+ expect(mocha.hasGlobalSetupFixtures(), "to be false");
});
});
});
- describe('hasGlobalTeardownFixtures()', function () {
- describe('when one or more global teardown fixtures are present', function () {
- it('should return `true`', function () {
+ describe("hasGlobalTeardownFixtures()", function () {
+ describe("when one or more global teardown fixtures are present", function () {
+ it("should return `true`", function () {
mocha.options.globalTeardown = [() => {}];
- expect(mocha.hasGlobalTeardownFixtures(), 'to be true');
+ expect(mocha.hasGlobalTeardownFixtures(), "to be true");
});
});
- describe('when no global teardown fixtures are present', function () {
- it('should return `false`', function () {
+ describe("when no global teardown fixtures are present", function () {
+ it("should return `false`", function () {
mocha.options.globalTeardown = [];
- expect(mocha.hasGlobalTeardownFixtures(), 'to be false');
+ expect(mocha.hasGlobalTeardownFixtures(), "to be false");
});
});
});
- describe('rootHooks()', function () {
- it('should be chainable', function () {
- expect(mocha.rootHooks(), 'to be', mocha);
+ describe("rootHooks()", function () {
+ it("should be chainable", function () {
+ expect(mocha.rootHooks(), "to be", mocha);
});
describe('when provided a single "before all" hook', function () {
- it('should attach it to the root suite', function () {
+ it("should attach it to the root suite", function () {
const beforeAll = () => {};
- mocha.rootHooks({beforeAll});
- expect(mocha.suite.beforeAll, 'to have a call satisfying', [
- beforeAll
- ]).and('was called once');
+ mocha.rootHooks({ beforeAll });
+ expect(mocha.suite.beforeAll, "to have a call satisfying", [
+ beforeAll,
+ ]).and("was called once");
});
});
describe('when provided a single "before each" hook', function () {
- it('should attach it to the root suite', function () {
+ it("should attach it to the root suite", function () {
const beforeEach = () => {};
- mocha.rootHooks({beforeEach});
- expect(mocha.suite.beforeEach, 'to have a call satisfying', [
- beforeEach
- ]).and('was called once');
+ mocha.rootHooks({ beforeEach });
+ expect(mocha.suite.beforeEach, "to have a call satisfying", [
+ beforeEach,
+ ]).and("was called once");
});
});
describe('when provided a single "after all" hook', function () {
- it('should attach it to the root suite', function () {
+ it("should attach it to the root suite", function () {
const afterAll = () => {};
- mocha.rootHooks({afterAll});
- expect(mocha.suite.afterAll, 'to have a call satisfying', [
- afterAll
- ]).and('was called once');
+ mocha.rootHooks({ afterAll });
+ expect(mocha.suite.afterAll, "to have a call satisfying", [
+ afterAll,
+ ]).and("was called once");
});
});
describe('when provided a single "after each" hook', function () {
- it('should attach it to the root suite', function () {
+ it("should attach it to the root suite", function () {
const afterEach = () => {};
- mocha.rootHooks({afterEach});
- expect(mocha.suite.afterEach, 'to have a call satisfying', [
- afterEach
- ]).and('was called once');
+ mocha.rootHooks({ afterEach });
+ expect(mocha.suite.afterEach, "to have a call satisfying", [
+ afterEach,
+ ]).and("was called once");
});
});
describe('when provided multiple "before all" hooks', function () {
- it('should attach each to the root suite', function () {
+ it("should attach each to the root suite", function () {
const beforeAll = [() => {}, () => {}];
- mocha.rootHooks({beforeAll});
- expect(mocha.suite.beforeAll, 'to have calls satisfying', [
+ mocha.rootHooks({ beforeAll });
+ expect(mocha.suite.beforeAll, "to have calls satisfying", [
[beforeAll[0]],
- [beforeAll[1]]
- ]).and('was called twice');
+ [beforeAll[1]],
+ ]).and("was called twice");
});
});
describe('when provided multiple "before each" hooks', function () {
- it('should attach each to the root suite', function () {
+ it("should attach each to the root suite", function () {
const beforeEach = [() => {}, () => {}];
- mocha.rootHooks({beforeEach});
- expect(mocha.suite.beforeEach, 'to have calls satisfying', [
+ mocha.rootHooks({ beforeEach });
+ expect(mocha.suite.beforeEach, "to have calls satisfying", [
[beforeEach[0]],
- [beforeEach[1]]
- ]).and('was called twice');
+ [beforeEach[1]],
+ ]).and("was called twice");
});
});
describe('when provided multiple "after all" hooks', function () {
- it('should attach each to the root suite', function () {
+ it("should attach each to the root suite", function () {
const afterAll = [() => {}, () => {}];
- mocha.rootHooks({afterAll});
- expect(mocha.suite.afterAll, 'to have calls satisfying', [
+ mocha.rootHooks({ afterAll });
+ expect(mocha.suite.afterAll, "to have calls satisfying", [
[afterAll[0]],
- [afterAll[1]]
- ]).and('was called twice');
+ [afterAll[1]],
+ ]).and("was called twice");
});
});
describe('when provided multiple "after each" hooks', function () {
- it('should attach each to the root suite', function () {
+ it("should attach each to the root suite", function () {
const afterEach = [() => {}, () => {}];
- mocha.rootHooks({afterEach});
- expect(mocha.suite.afterEach, 'to have calls satisfying', [
+ mocha.rootHooks({ afterEach });
+ expect(mocha.suite.afterEach, "to have calls satisfying", [
[afterEach[0]],
- [afterEach[1]]
- ]).and('was called twice');
+ [afterEach[1]],
+ ]).and("was called twice");
});
});
});
diff --git a/test/unit/overspecified-async.spec.js b/test/unit/overspecified-async.spec.js
index 0f9b6c9f..b2eddcbe 100644
--- a/test/unit/overspecified-async.spec.js
+++ b/test/unit/overspecified-async.spec.js
@@ -1,7 +1,7 @@
-'use strict';
+"use strict";
-describe('overspecified asynchronous resolution method', function () {
- it('should fail when multiple methods are used', function (done) {
+describe("overspecified asynchronous resolution method", function () {
+ it("should fail when multiple methods are used", function (done) {
setTimeout(done, 0);
// uncomment
diff --git a/test/unit/parse-query.spec.js b/test/unit/parse-query.spec.js
index d3be471b..dd399e94 100644
--- a/test/unit/parse-query.spec.js
+++ b/test/unit/parse-query.spec.js
@@ -1,23 +1,23 @@
-'use strict';
+"use strict";
-var parseQuery = require('../../lib/browser/parse-query');
+var parseQuery = require("../../lib/browser/parse-query");
-describe('parseQuery()', function () {
- it('should get queryString and return key-value object', function () {
- expect(parseQuery('?foo=1&bar=2&baz=3'), 'to equal', {
- foo: '1',
- bar: '2',
- baz: '3'
+describe("parseQuery()", function () {
+ it("should get queryString and return key-value object", function () {
+ expect(parseQuery("?foo=1&bar=2&baz=3"), "to equal", {
+ foo: "1",
+ bar: "2",
+ baz: "3",
});
- expect(parseQuery('?r1=^@(?!.*\\)$)&r2=m{2}&r3=^co.*'), 'to equal', {
- r1: '^@(?!.*\\)$)',
- r2: 'm{2}',
- r3: '^co.*'
+ expect(parseQuery("?r1=^@(?!.*\\)$)&r2=m{2}&r3=^co.*"), "to equal", {
+ r1: "^@(?!.*\\)$)",
+ r2: "m{2}",
+ r3: "^co.*",
});
});
it('should parse "+" as a space', function () {
- expect(parseQuery('?grep=foo+bar'), 'to equal', {grep: 'foo bar'});
+ expect(parseQuery("?grep=foo+bar"), "to equal", { grep: "foo bar" });
});
});
diff --git a/test/unit/plugin-loader.spec.js b/test/unit/plugin-loader.spec.js
index 257d6d05..d56bf14c 100644
--- a/test/unit/plugin-loader.spec.js
+++ b/test/unit/plugin-loader.spec.js
@@ -1,234 +1,234 @@
-'use strict';
+"use strict";
-const PluginLoader = require('../../lib/plugin-loader');
-const sinon = require('sinon');
-const {INVALID_PLUGIN_DEFINITION, INVALID_PLUGIN_IMPLEMENTATION} =
- require('../../lib/error-constants').constants;
+const PluginLoader = require("../../lib/plugin-loader");
+const sinon = require("sinon");
+const { INVALID_PLUGIN_DEFINITION, INVALID_PLUGIN_IMPLEMENTATION } =
+ require("../../lib/error-constants").constants;
-describe('plugin module', function () {
- describe('class PluginLoader', function () {
- describe('constructor', function () {
- describe('when passed no options', function () {
- it('should populate a registry of built-in plugins', function () {
- expect(new PluginLoader().registered.has('mochaHooks'), 'to be true');
+describe("plugin module", function () {
+ describe("class PluginLoader", function () {
+ describe("constructor", function () {
+ describe("when passed no options", function () {
+ it("should populate a registry of built-in plugins", function () {
+ expect(new PluginLoader().registered.has("mochaHooks"), "to be true");
});
});
- describe('when passed custom plugins', function () {
- it('should register the custom plugins', function () {
- const plugin = {exportName: 'mochaBananaPhone'};
+ describe("when passed custom plugins", function () {
+ it("should register the custom plugins", function () {
+ const plugin = { exportName: "mochaBananaPhone" };
expect(
- new PluginLoader({pluginDefs: [plugin]}).registered,
- 'to satisfy',
- new Map([['mochaBananaPhone', plugin]])
+ new PluginLoader({ pluginDefs: [plugin] }).registered,
+ "to satisfy",
+ new Map([["mochaBananaPhone", plugin]]),
);
});
});
- describe('when passed ignored plugins', function () {
- it('should retain a list of ignored plugins', function () {
+ describe("when passed ignored plugins", function () {
+ it("should retain a list of ignored plugins", function () {
expect(
new PluginLoader({
- ignore: ['elephantInRoom']
+ ignore: ["elephantInRoom"],
}).ignoredExportNames,
- 'to contain',
- 'elephantInRoom'
+ "to contain",
+ "elephantInRoom",
);
});
});
});
- describe('static method', function () {
- describe('create()', function () {
- it('should return a PluginLoader instance', function () {
- expect(PluginLoader.create(), 'to be a', PluginLoader);
+ describe("static method", function () {
+ describe("create()", function () {
+ it("should return a PluginLoader instance", function () {
+ expect(PluginLoader.create(), "to be a", PluginLoader);
});
});
});
- describe('instance method', function () {
+ describe("instance method", function () {
let pluginLoader;
beforeEach(function () {
pluginLoader = PluginLoader.create({
- ignore: ['elephantInRoom']
+ ignore: ["elephantInRoom"],
});
});
- describe('register()', function () {
- describe('when the plugin export name is not in use', function () {
- it('should not throw', function () {
+ describe("register()", function () {
+ describe("when the plugin export name is not in use", function () {
+ it("should not throw", function () {
expect(
- () => pluginLoader.register({exportName: 'butts'}),
- 'not to throw'
+ () => pluginLoader.register({ exportName: "butts" }),
+ "not to throw",
);
});
});
- describe('when the plugin export name is already in use', function () {
- it('should throw', function () {
- const pluginDef = {exportName: 'butts'};
+ describe("when the plugin export name is already in use", function () {
+ it("should throw", function () {
+ const pluginDef = { exportName: "butts" };
pluginLoader.register(pluginDef);
- expect(() => pluginLoader.register(pluginDef), 'to throw', {
+ expect(() => pluginLoader.register(pluginDef), "to throw", {
code: INVALID_PLUGIN_DEFINITION,
- pluginDef
+ pluginDef,
});
});
});
- describe('when the plugin export name is ignored', function () {
+ describe("when the plugin export name is ignored", function () {
let pluginDef;
beforeEach(function () {
- pluginDef = {exportName: 'elephantInRoom'};
+ pluginDef = { exportName: "elephantInRoom" };
});
- it('should not throw', function () {
- expect(() => pluginLoader.register(pluginDef), 'not to throw');
+ it("should not throw", function () {
+ expect(() => pluginLoader.register(pluginDef), "not to throw");
});
- it('should not register the plugin', function () {
+ it("should not register the plugin", function () {
pluginLoader.register(pluginDef);
expect(
pluginLoader.registered,
- 'not to have key',
- 'elephantInRoom'
+ "not to have key",
+ "elephantInRoom",
);
});
});
- describe('when passed a falsy parameter', function () {
- it('should throw', function () {
- expect(() => pluginLoader.register(), 'to throw', {
- code: INVALID_PLUGIN_DEFINITION
+ describe("when passed a falsy parameter", function () {
+ it("should throw", function () {
+ expect(() => pluginLoader.register(), "to throw", {
+ code: INVALID_PLUGIN_DEFINITION,
});
});
});
- describe('when passed a non-object parameter', function () {
- it('should throw', function () {
- expect(() => pluginLoader.register(1), 'to throw', {
+ describe("when passed a non-object parameter", function () {
+ it("should throw", function () {
+ expect(() => pluginLoader.register(1), "to throw", {
code: INVALID_PLUGIN_DEFINITION,
- pluginDef: 1
+ pluginDef: 1,
});
});
});
- describe('when passed a definition w/o an exportName', function () {
- it('should throw', function () {
- const pluginDef = {foo: 'bar'};
- expect(() => pluginLoader.register(pluginDef), 'to throw', {
+ describe("when passed a definition w/o an exportName", function () {
+ it("should throw", function () {
+ const pluginDef = { foo: "bar" };
+ expect(() => pluginLoader.register(pluginDef), "to throw", {
code: INVALID_PLUGIN_DEFINITION,
- pluginDef
+ pluginDef,
});
});
});
});
- describe('load()', function () {
+ describe("load()", function () {
let pluginLoader;
beforeEach(function () {
pluginLoader = PluginLoader.create();
});
- describe('when called with a falsy value', function () {
- it('should return false', function () {
- expect(pluginLoader.load(), 'to be false');
+ describe("when called with a falsy value", function () {
+ it("should return false", function () {
+ expect(pluginLoader.load(), "to be false");
});
});
- describe('when called with an object containing no recognized plugin', function () {
- it('should return false', function () {
+ describe("when called with an object containing no recognized plugin", function () {
+ it("should return false", function () {
// also it should not throw
expect(
- pluginLoader.load({mochaBananaPhone: () => {}}),
- 'to be false'
+ pluginLoader.load({ mochaBananaPhone: () => {} }),
+ "to be false",
);
});
});
- describe('when called with an object containing a recognized plugin', function () {
+ describe("when called with an object containing a recognized plugin", function () {
let plugin;
let pluginLoader;
beforeEach(function () {
plugin = {
- exportName: 'mochaBananaPhone',
- validate: sinon.spy()
+ exportName: "mochaBananaPhone",
+ validate: sinon.spy(),
};
- pluginLoader = PluginLoader.create({pluginDefs: [plugin]});
+ pluginLoader = PluginLoader.create({ pluginDefs: [plugin] });
});
- it('should return true', function () {
+ it("should return true", function () {
const func = () => {};
- expect(pluginLoader.load({mochaBananaPhone: func}), 'to be true');
+ expect(pluginLoader.load({ mochaBananaPhone: func }), "to be true");
});
- it('should retain the value of any matching property in its mapping', function () {
+ it("should retain the value of any matching property in its mapping", function () {
const func = () => {};
- pluginLoader.load({mochaBananaPhone: func});
+ pluginLoader.load({ mochaBananaPhone: func });
expect(
pluginLoader.loaded,
- 'to satisfy',
- new Map([['mochaBananaPhone', [func]]])
+ "to satisfy",
+ new Map([["mochaBananaPhone", [func]]]),
);
});
- it('should call the associated validator, if present', function () {
+ it("should call the associated validator, if present", function () {
const func = () => {};
- pluginLoader.load({mochaBananaPhone: func});
- expect(plugin.validate, 'was called once');
+ pluginLoader.load({ mochaBananaPhone: func });
+ expect(plugin.validate, "was called once");
});
});
});
- describe('load()', function () {
+ describe("load()", function () {
let pluginLoader;
let fooPlugin;
let barPlugin;
beforeEach(function () {
fooPlugin = {
- exportName: 'foo',
- validate: sinon.stub()
+ exportName: "foo",
+ validate: sinon.stub(),
};
- fooPlugin.validate.withArgs('ERROR').throws();
+ fooPlugin.validate.withArgs("ERROR").throws();
barPlugin = {
- exportName: 'bar',
- validate: sinon.stub()
+ exportName: "bar",
+ validate: sinon.stub(),
};
pluginLoader = PluginLoader.create({
- pluginDefs: [fooPlugin, barPlugin]
+ pluginDefs: [fooPlugin, barPlugin],
});
});
- describe('when passed a falsy or non-object value', function () {
- it('should return false', function () {
- expect(pluginLoader.load(), 'to be false');
+ describe("when passed a falsy or non-object value", function () {
+ it("should return false", function () {
+ expect(pluginLoader.load(), "to be false");
});
- it('should not call a validator', function () {
- expect([fooPlugin, barPlugin], 'to have items satisfying', {
- validate: expect.it('was not called')
+ it("should not call a validator", function () {
+ expect([fooPlugin, barPlugin], "to have items satisfying", {
+ validate: expect.it("was not called"),
});
});
});
- describe('when passed an object value', function () {
- describe('when no keys match any known named exports', function () {
+ describe("when passed an object value", function () {
+ describe("when no keys match any known named exports", function () {
let retval;
beforeEach(function () {
- retval = pluginLoader.load({butts: () => {}});
+ retval = pluginLoader.load({ butts: () => {} });
});
- it('should return false', function () {
- expect(retval, 'to be false');
+ it("should return false", function () {
+ expect(retval, "to be false");
});
});
- describe('when a key matches a known named export', function () {
+ describe("when a key matches a known named export", function () {
let retval;
let impl;
@@ -236,55 +236,55 @@ describe('plugin module', function () {
impl = sinon.stub();
});
- it('should call the associated validator', function () {
- retval = pluginLoader.load({foo: impl});
+ it("should call the associated validator", function () {
+ retval = pluginLoader.load({ foo: impl });
- expect(fooPlugin.validate, 'to have a call satisfying', [
- impl
- ]).and('was called once');
+ expect(fooPlugin.validate, "to have a call satisfying", [
+ impl,
+ ]).and("was called once");
});
- it('should not call validators whose keys were not found', function () {
- retval = pluginLoader.load({foo: impl});
- expect(barPlugin.validate, 'was not called');
+ it("should not call validators whose keys were not found", function () {
+ retval = pluginLoader.load({ foo: impl });
+ expect(barPlugin.validate, "was not called");
});
- describe('when the value passes the associated validator', function () {
+ describe("when the value passes the associated validator", function () {
beforeEach(function () {
- retval = pluginLoader.load({foo: impl});
+ retval = pluginLoader.load({ foo: impl });
});
- it('should return true', function () {
- expect(retval, 'to be true');
+ it("should return true", function () {
+ expect(retval, "to be true");
});
- it('should add the implementation to the internal mapping', function () {
+ it("should add the implementation to the internal mapping", function () {
expect(
pluginLoader.loaded,
- 'to satisfy',
- new Map([['foo', expect.it('to have length', 1)]])
+ "to satisfy",
+ new Map([["foo", expect.it("to have length", 1)]]),
);
});
- it('should not add an implementation of plugins not present', function () {
+ it("should not add an implementation of plugins not present", function () {
expect(
pluginLoader.loaded,
- 'to satisfy',
- new Map([['bar', expect.it('to be empty')]])
+ "to satisfy",
+ new Map([["bar", expect.it("to be empty")]]),
);
});
});
- describe('when the value does not pass the associated validator', function () {
- it('should throw', function () {
- expect(() => pluginLoader.load({foo: 'ERROR'}), 'to throw');
+ describe("when the value does not pass the associated validator", function () {
+ it("should throw", function () {
+ expect(() => pluginLoader.load({ foo: "ERROR" }), "to throw");
});
});
});
});
});
- describe('finalize()', function () {
+ describe("finalize()", function () {
let pluginLoader;
let fooPlugin;
let barPlugin;
@@ -292,57 +292,57 @@ describe('plugin module', function () {
beforeEach(function () {
fooPlugin = {
- exportName: 'foo',
- optionName: 'fooOption',
+ exportName: "foo",
+ optionName: "fooOption",
validate: sinon.stub(),
- finalize: impls => impls.map(() => 'FOO')
+ finalize: (impls) => impls.map(() => "FOO"),
};
- fooPlugin.validate.withArgs('ERROR').throws();
+ fooPlugin.validate.withArgs("ERROR").throws();
barPlugin = {
- exportName: 'bar',
+ exportName: "bar",
validate: sinon.stub(),
- finalize: impls => impls.map(() => 'BAR')
+ finalize: (impls) => impls.map(() => "BAR"),
};
bazPlugin = {
- exportName: 'baz'
+ exportName: "baz",
};
pluginLoader = PluginLoader.create({
- pluginDefs: [fooPlugin, barPlugin, bazPlugin]
+ pluginDefs: [fooPlugin, barPlugin, bazPlugin],
});
});
- describe('when no plugins have been loaded', function () {
- it('should return an empty map', async function () {
- return expect(pluginLoader.finalize(), 'to be fulfilled with', {});
+ describe("when no plugins have been loaded", function () {
+ it("should return an empty map", async function () {
+ return expect(pluginLoader.finalize(), "to be fulfilled with", {});
});
});
- describe('when a plugin has one or more implementations', function () {
+ describe("when a plugin has one or more implementations", function () {
beforeEach(function () {
- pluginLoader.load({foo: sinon.stub()});
- pluginLoader.load({foo: sinon.stub()});
+ pluginLoader.load({ foo: sinon.stub() });
+ pluginLoader.load({ foo: sinon.stub() });
});
- it('should return an object map using `optionName` key for each registered plugin', async function () {
- return expect(pluginLoader.finalize(), 'to be fulfilled with', {
- fooOption: ['FOO', 'FOO']
+ it("should return an object map using `optionName` key for each registered plugin", async function () {
+ return expect(pluginLoader.finalize(), "to be fulfilled with", {
+ fooOption: ["FOO", "FOO"],
});
});
- it('should omit unused plugins', async function () {
- pluginLoader.load({bar: sinon.stub()});
- return expect(pluginLoader.finalize(), 'to be fulfilled with', {
- fooOption: ['FOO', 'FOO'],
- bar: ['BAR']
+ it("should omit unused plugins", async function () {
+ pluginLoader.load({ bar: sinon.stub() });
+ return expect(pluginLoader.finalize(), "to be fulfilled with", {
+ fooOption: ["FOO", "FOO"],
+ bar: ["BAR"],
});
});
});
describe('when a plugin has no "finalize" function', function () {
- it('should return an array of raw implementations', function () {
- pluginLoader.load({baz: 'polar bears'});
- return expect(pluginLoader.finalize(), 'to be fulfilled with', {
- baz: ['polar bears']
+ it("should return an array of raw implementations", function () {
+ pluginLoader.load({ baz: "polar bears" });
+ return expect(pluginLoader.finalize(), "to be fulfilled with", {
+ baz: ["polar bears"],
});
});
});
@@ -350,42 +350,42 @@ describe('plugin module', function () {
});
});
- describe('root hooks plugin 🎣', function () {
+ describe("root hooks plugin 🎣", function () {
let pluginLoader;
beforeEach(function () {
pluginLoader = PluginLoader.create();
});
- describe('when impl is an array', function () {
- it('should fail validation', function () {
- expect(() => pluginLoader.load({mochaHooks: []}), 'to throw', {
- code: INVALID_PLUGIN_IMPLEMENTATION
+ describe("when impl is an array", function () {
+ it("should fail validation", function () {
+ expect(() => pluginLoader.load({ mochaHooks: [] }), "to throw", {
+ code: INVALID_PLUGIN_IMPLEMENTATION,
});
});
});
- describe('when impl is a primitive', function () {
- it('should fail validation', function () {
- expect(() => pluginLoader.load({mochaHooks: 'nuts'}), 'to throw', {
- code: INVALID_PLUGIN_IMPLEMENTATION
+ describe("when impl is a primitive", function () {
+ it("should fail validation", function () {
+ expect(() => pluginLoader.load({ mochaHooks: "nuts" }), "to throw", {
+ code: INVALID_PLUGIN_IMPLEMENTATION,
});
});
});
- describe('when impl is a function', function () {
- it('should pass validation', function () {
- expect(pluginLoader.load({mochaHooks: sinon.stub()}), 'to be true');
+ describe("when impl is a function", function () {
+ it("should pass validation", function () {
+ expect(pluginLoader.load({ mochaHooks: sinon.stub() }), "to be true");
});
});
- describe('when impl is an object of functions', function () {
+ describe("when impl is an object of functions", function () {
// todo: hook name validation?
- it('should pass validation');
+ it("should pass validation");
});
- describe('when a loaded impl is finalized', function () {
- it('should flatten the implementations', async function () {
+ describe("when a loaded impl is finalized", function () {
+ it("should flatten the implementations", async function () {
function a() {}
function b() {}
function d() {}
@@ -394,116 +394,116 @@ describe('plugin module', function () {
function c() {
return {
beforeAll: d,
- beforeEach: g
+ beforeEach: g,
};
}
async function e() {
return {
- afterEach: f
+ afterEach: f,
};
}
[
{
- beforeEach: a
+ beforeEach: a,
},
{
- afterAll: b
+ afterAll: b,
},
c,
- e
- ].forEach(impl => {
- pluginLoader.load({mochaHooks: impl});
+ e,
+ ].forEach((impl) => {
+ pluginLoader.load({ mochaHooks: impl });
});
- return expect(pluginLoader.finalize(), 'to be fulfilled with', {
+ return expect(pluginLoader.finalize(), "to be fulfilled with", {
rootHooks: {
beforeAll: [d],
beforeEach: [a, g],
afterAll: [b],
- afterEach: [f]
- }
+ afterEach: [f],
+ },
});
});
});
});
- describe('global fixtures plugin', function () {
+ describe("global fixtures plugin", function () {
let pluginLoader;
beforeEach(function () {
pluginLoader = PluginLoader.create();
});
- describe('global setup', function () {
- describe('when an implementation is a primitive', function () {
- it('should fail validation', function () {
+ describe("global setup", function () {
+ describe("when an implementation is a primitive", function () {
+ it("should fail validation", function () {
expect(
- () => pluginLoader.load({mochaGlobalSetup: 'nuts'}),
- 'to throw'
+ () => pluginLoader.load({ mochaGlobalSetup: "nuts" }),
+ "to throw",
);
});
});
- describe('when an implementation is an array of primitives', function () {
- it('should fail validation', function () {
+ describe("when an implementation is an array of primitives", function () {
+ it("should fail validation", function () {
expect(
- () => pluginLoader.load({mochaGlobalSetup: ['nuts']}),
- 'to throw'
+ () => pluginLoader.load({ mochaGlobalSetup: ["nuts"] }),
+ "to throw",
);
});
});
- describe('when an implementation is a function', function () {
- it('should pass validation', function () {
+ describe("when an implementation is a function", function () {
+ it("should pass validation", function () {
expect(
- pluginLoader.load({mochaGlobalSetup: sinon.stub()}),
- 'to be true'
+ pluginLoader.load({ mochaGlobalSetup: sinon.stub() }),
+ "to be true",
);
});
});
- describe('when an implementation is an array of functions', function () {
- it('should pass validation', function () {
+ describe("when an implementation is an array of functions", function () {
+ it("should pass validation", function () {
expect(
- pluginLoader.load({mochaGlobalSetup: [sinon.stub()]}),
- 'to be true'
+ pluginLoader.load({ mochaGlobalSetup: [sinon.stub()] }),
+ "to be true",
);
});
});
});
- describe('global teardown', function () {
- describe('when an implementation is a primitive', function () {
- it('should fail validation', function () {
+ describe("global teardown", function () {
+ describe("when an implementation is a primitive", function () {
+ it("should fail validation", function () {
expect(
- () => pluginLoader.load({mochaGlobalTeardown: 'nuts'}),
- 'to throw'
+ () => pluginLoader.load({ mochaGlobalTeardown: "nuts" }),
+ "to throw",
);
});
});
- describe('when an implementation is an array of primitives', function () {
- it('should fail validation', function () {
+ describe("when an implementation is an array of primitives", function () {
+ it("should fail validation", function () {
expect(
- () => pluginLoader.load({mochaGlobalTeardown: ['nuts']}),
- 'to throw'
+ () => pluginLoader.load({ mochaGlobalTeardown: ["nuts"] }),
+ "to throw",
);
});
});
- describe('when an implementation is a function', function () {
- it('should pass validation', function () {
+ describe("when an implementation is a function", function () {
+ it("should pass validation", function () {
expect(
- pluginLoader.load({mochaGlobalTeardown: sinon.stub()}),
- 'to be true'
+ pluginLoader.load({ mochaGlobalTeardown: sinon.stub() }),
+ "to be true",
);
});
});
- describe('when an implementation is an array of functions', function () {
- it('should pass validation', function () {
+ describe("when an implementation is an array of functions", function () {
+ it("should pass validation", function () {
expect(
- pluginLoader.load({mochaGlobalTeardown: [sinon.stub()]}),
- 'to be true'
+ pluginLoader.load({ mochaGlobalTeardown: [sinon.stub()] }),
+ "to be true",
);
});
});
diff --git a/test/unit/required-tokens.spec.js b/test/unit/required-tokens.spec.js
index ba2ee95d..8fa0bc2b 100644
--- a/test/unit/required-tokens.spec.js
+++ b/test/unit/required-tokens.spec.js
@@ -1,7 +1,7 @@
-'use strict';
+"use strict";
-const assert = require('node:assert');
-const {describe, it} = require('../..');
+const assert = require("node:assert");
+const { describe, it } = require("../..");
describe('using imported "describe"', function () {
it('using imported "it"', function (done) {
diff --git a/test/unit/root.spec.js b/test/unit/root.spec.js
index 9adbaf9c..c32effec 100644
--- a/test/unit/root.spec.js
+++ b/test/unit/root.spec.js
@@ -1,13 +1,13 @@
-'use strict';
+"use strict";
var calls = [];
before(function () {
- calls.push('before');
+ calls.push("before");
});
-describe('root', function () {
- it('should be a valid suite', function () {
- expect(calls, 'to equal', ['before']);
+describe("root", function () {
+ it("should be a valid suite", function () {
+ expect(calls, "to equal", ["before"]);
});
});
diff --git a/test/unit/runnable.spec.js b/test/unit/runnable.spec.js
index 7739ba2a..44b800ab 100644
--- a/test/unit/runnable.spec.js
+++ b/test/unit/runnable.spec.js
@@ -1,51 +1,51 @@
-'use strict';
+"use strict";
-var Mocha = require('../../lib/mocha');
+var Mocha = require("../../lib/mocha");
var Runnable = Mocha.Runnable;
var Suite = Mocha.Suite;
-var sinon = require('sinon');
-const {TIMEOUT} = require('../../lib/error-constants').constants;
+var sinon = require("sinon");
+const { TIMEOUT } = require("../../lib/error-constants").constants;
var STATE_FAILED = Runnable.constants.STATE_FAILED;
-describe('Runnable(title, fn)', function () {
- describe('#timeout(ms)', function () {
+describe("Runnable(title, fn)", function () {
+ describe("#timeout(ms)", function () {
var DISABLED_TIMEOUTS = 0;
var MAX_TIMEOUT = 2147483647; // INT_MAX (32-bit signed integer)
- describe('when value is less than lower bound', function () {
- it('should clamp to lower bound given numeric', function () {
+ describe("when value is less than lower bound", function () {
+ it("should clamp to lower bound given numeric", function () {
var run = new Runnable();
run.timeout(-1);
- expect(run.timeout(), 'to be', DISABLED_TIMEOUTS);
+ expect(run.timeout(), "to be", DISABLED_TIMEOUTS);
});
- it('should clamp to lower bound given timestamp', function () {
+ it("should clamp to lower bound given timestamp", function () {
var run = new Runnable();
- run.timeout('-1 ms');
- expect(run.timeout(), 'to be', DISABLED_TIMEOUTS);
+ run.timeout("-1 ms");
+ expect(run.timeout(), "to be", DISABLED_TIMEOUTS);
});
});
- describe('when value is equal to lower bound', function () {
+ describe("when value is equal to lower bound", function () {
var run;
beforeEach(function () {
run = new Runnable();
run.timeout(DISABLED_TIMEOUTS);
});
- describe('given numeric value', function () {
- it('should set the timeout value to disabled', function () {
- expect(run.timeout(), 'to be', DISABLED_TIMEOUTS);
+ describe("given numeric value", function () {
+ it("should set the timeout value to disabled", function () {
+ expect(run.timeout(), "to be", DISABLED_TIMEOUTS);
});
});
- describe('given string timestamp', function () {
- it('should set the timeout value to disabled', function () {
- expect(run.timeout(), 'to be', DISABLED_TIMEOUTS);
+ describe("given string timestamp", function () {
+ it("should set the timeout value to disabled", function () {
+ expect(run.timeout(), "to be", DISABLED_TIMEOUTS);
});
});
});
- describe('when value is within `setTimeout` bounds', function () {
+ describe("when value is within `setTimeout` bounds", function () {
var run;
var timeout = 1000;
@@ -54,34 +54,34 @@ describe('Runnable(title, fn)', function () {
run.timeout(timeout);
});
- describe('given numeric value', function () {
- it('should set the timeout value', function () {
- expect(run.timeout(), 'to be', timeout);
+ describe("given numeric value", function () {
+ it("should set the timeout value", function () {
+ expect(run.timeout(), "to be", timeout);
});
});
- describe('given string timestamp', function () {
- it('should set the timeout value', function () {
- expect(run.timeout(), 'to be', timeout);
+ describe("given string timestamp", function () {
+ it("should set the timeout value", function () {
+ expect(run.timeout(), "to be", timeout);
});
});
});
- describe('when value is equal to upper bound', function () {
+ describe("when value is equal to upper bound", function () {
var run;
beforeEach(function () {
run = new Runnable();
run.timeout(MAX_TIMEOUT);
});
- describe('given numeric value', function () {
- it('should set the disabled timeout value', function () {
- expect(run.timeout(), 'to be', 0);
+ describe("given numeric value", function () {
+ it("should set the disabled timeout value", function () {
+ expect(run.timeout(), "to be", 0);
});
});
});
- describe('when value is out-of-bounds', function () {
+ describe("when value is out-of-bounds", function () {
var run;
var timeout = MAX_TIMEOUT + 1;
@@ -90,199 +90,199 @@ describe('Runnable(title, fn)', function () {
run.timeout(timeout);
});
- describe('given numeric value', function () {
- it('should set the disabled timeout value', function () {
- expect(run.timeout(), 'to be', 0);
+ describe("given numeric value", function () {
+ it("should set the disabled timeout value", function () {
+ expect(run.timeout(), "to be", 0);
});
});
});
});
- describe('#slow(ms)', function () {
+ describe("#slow(ms)", function () {
var run;
beforeEach(function () {
run = new Runnable();
});
- it('should set the slow threshold', function () {
+ it("should set the slow threshold", function () {
run.slow(100);
- expect(run.slow(), 'to be', 100);
+ expect(run.slow(), "to be", 100);
});
- it('should not set the slow threshold if the parameter is not passed', function () {
+ it("should not set the slow threshold if the parameter is not passed", function () {
run.slow();
- expect(run.slow(), 'to be', 75);
+ expect(run.slow(), "to be", 75);
});
- it('should not set the slow threshold if the parameter is undefined', function () {
+ it("should not set the slow threshold if the parameter is undefined", function () {
run.slow(undefined);
- expect(run.slow(), 'to be', 75);
+ expect(run.slow(), "to be", 75);
});
- describe('when passed a time-formatted string', function () {
- it('should convert to ms', function () {
- run.slow('1s');
- expect(run.slow(), 'to be', 1000);
+ describe("when passed a time-formatted string", function () {
+ it("should convert to ms", function () {
+ run.slow("1s");
+ expect(run.slow(), "to be", 1000);
});
});
});
- describe('#reset', function () {
+ describe("#reset", function () {
var run;
beforeEach(function () {
run = new Runnable();
});
- it('should reset current run state', function () {
+ it("should reset current run state", function () {
run.timedOut = true;
run._currentRetry = 5;
run.pending = true;
run.err = new Error();
- run.state = 'error';
+ run.state = "error";
run.reset();
- expect(run.timedOut, 'to be false');
- expect(run._currentRetry, 'to be', 0);
- expect(run.pending, 'to be false');
- expect(run.err, 'to be undefined');
- expect(run.state, 'to be undefined');
+ expect(run.timedOut, "to be false");
+ expect(run._currentRetry, "to be", 0);
+ expect(run.pending, "to be false");
+ expect(run.err, "to be undefined");
+ expect(run.state, "to be undefined");
});
});
- describe('.title', function () {
- it('should be present', function () {
- expect(new Runnable('foo').title, 'to be', 'foo');
+ describe(".title", function () {
+ it("should be present", function () {
+ expect(new Runnable("foo").title, "to be", "foo");
});
});
- describe('.titlePath()', function () {
+ describe(".titlePath()", function () {
it("returns the concatenation of the parent's title path and runnable's title", function () {
- var runnable = new Runnable('bar');
- runnable.parent = new Suite('foo');
+ var runnable = new Runnable("bar");
+ runnable.parent = new Suite("foo");
expect(
JSON.stringify(runnable.titlePath()),
- 'to be',
- JSON.stringify(['foo', 'bar'])
+ "to be",
+ JSON.stringify(["foo", "bar"]),
);
});
});
- describe('when arity >= 1', function () {
+ describe("when arity >= 1", function () {
var run;
beforeEach(function () {
// Runnable knows whether it's provided a 'done' parameter
// eslint-disable-next-line no-unused-vars
- run = new Runnable('foo', function (done) {});
+ run = new Runnable("foo", function (done) {});
});
- it('should be .async', function () {
- expect(run.async, 'to be', 1);
+ it("should be .async", function () {
+ expect(run.async, "to be", 1);
});
- it('should not be .sync', function () {
- expect(run.sync, 'to be false');
+ it("should not be .sync", function () {
+ expect(run.sync, "to be false");
});
});
- describe('when arity == 0', function () {
+ describe("when arity == 0", function () {
var run;
beforeEach(function () {
- run = new Runnable('foo', function () {});
+ run = new Runnable("foo", function () {});
});
- it('should not be .async', function () {
- expect(run.async, 'to be', 0);
+ it("should not be .async", function () {
+ expect(run.async, "to be", 0);
});
- it('should be .sync', function () {
- expect(run.sync, 'to be true');
+ it("should be .sync", function () {
+ expect(run.sync, "to be true");
});
});
- describe('#globals', function () {
- it('should allow for whitelisting globals', function () {
- var runnable = new Runnable('foo', function () {});
- runnable.globals(['foobar']);
- expect(runnable._allowedGlobals, 'to equal', ['foobar']);
+ describe("#globals", function () {
+ it("should allow for whitelisting globals", function () {
+ var runnable = new Runnable("foo", function () {});
+ runnable.globals(["foobar"]);
+ expect(runnable._allowedGlobals, "to equal", ["foobar"]);
});
});
- describe('#retries(n)', function () {
- it('should set the number of retries', function () {
+ describe("#retries(n)", function () {
+ it("should set the number of retries", function () {
var run = new Runnable();
run.retries(1);
- expect(run.retries(), 'to be', 1);
+ expect(run.retries(), "to be", 1);
});
});
- describe('.run(fn)', function () {
- describe('when .pending', function () {
- it('should not invoke the callback', function (done) {
+ describe(".run(fn)", function () {
+ describe("when .pending", function () {
+ it("should not invoke the callback", function (done) {
var spy = sinon.spy();
- var runnable = new Runnable('foo', spy);
+ var runnable = new Runnable("foo", spy);
runnable.pending = true;
runnable.run(function (err) {
if (err) {
return done(err);
}
- expect(spy, 'was not called');
+ expect(spy, "was not called");
done();
});
});
});
- describe('when sync', function () {
- describe('without error', function () {
- it('should invoke the callback', function (done) {
+ describe("when sync", function () {
+ describe("without error", function () {
+ it("should invoke the callback", function (done) {
var spy = sinon.spy();
- var runnable = new Runnable('foo', spy);
+ var runnable = new Runnable("foo", spy);
runnable.run(function (err) {
if (err) {
return done(err);
}
- expect(spy, 'was called times', 1);
+ expect(spy, "was called times", 1);
done();
});
});
});
- describe('when an exception is thrown', function () {
- it('should invoke the callback with error', function (done) {
- var stub = sinon.stub().throws('Error', 'fail');
- var runnable = new Runnable('foo', stub);
+ describe("when an exception is thrown", function () {
+ it("should invoke the callback with error", function (done) {
+ var stub = sinon.stub().throws("Error", "fail");
+ var runnable = new Runnable("foo", stub);
runnable.run(function (err) {
- expect(err.message, 'to be', 'fail');
- expect(stub, 'was called');
+ expect(err.message, "to be", "fail");
+ expect(stub, "was called");
done();
});
});
});
- describe('when an exception is thrown and is allowed to remain uncaught', function () {
- it('throws an error when it is allowed', function () {
- var stub = sinon.stub().throws('Error', 'fail');
- var runnable = new Runnable('foo', stub);
+ describe("when an exception is thrown and is allowed to remain uncaught", function () {
+ it("throws an error when it is allowed", function () {
+ var stub = sinon.stub().throws("Error", "fail");
+ var runnable = new Runnable("foo", stub);
runnable.allowUncaught = true;
function fail() {
runnable.run(function () {});
}
- expect(fail, 'to throw', 'fail');
+ expect(fail, "to throw", "fail");
});
});
});
- describe('when timeouts are disabled', function () {
- it('should not error with timeout', function (done) {
- var runnable = new Runnable('foo', function (done) {
+ describe("when timeouts are disabled", function () {
+ it("should not error with timeout", function (done) {
+ var runnable = new Runnable("foo", function (done) {
setTimeout(function () {
setTimeout(done);
}, 2);
@@ -290,33 +290,33 @@ describe('Runnable(title, fn)', function () {
runnable.timeout(1);
runnable.timeout(0);
runnable.run(function (err) {
- expect(err, 'to be falsy');
+ expect(err, "to be falsy");
done();
});
});
});
- describe('when async', function () {
- describe('without error', function () {
- it('should invoke the callback', function (done) {
- var runnable = new Runnable('foo', function (done) {
+ describe("when async", function () {
+ describe("without error", function () {
+ it("should invoke the callback", function (done) {
+ var runnable = new Runnable("foo", function (done) {
setTimeout(done);
});
runnable.run(function (err) {
- expect(err, 'to be falsy');
+ expect(err, "to be falsy");
done();
});
});
});
- describe('when the callback is invoked several times', function () {
- describe('without an error', function () {
+ describe("when the callback is invoked several times", function () {
+ describe("without an error", function () {
it('should emit a single "error" event', function (done) {
var callbackSpy = sinon.spy();
var errorSpy = sinon.spy();
- var runnable = new Runnable('foo', function (done) {
+ var runnable = new Runnable("foo", function (done) {
process.nextTick(done);
setTimeout(done);
setTimeout(done);
@@ -325,15 +325,15 @@ describe('Runnable(title, fn)', function () {
// XXX too many diff assertions and very flimsy assertion that this
// event was only emitted once. think of a better way.
- runnable.on('error', errorSpy).on('error', function (err) {
+ runnable.on("error", errorSpy).on("error", function (err) {
process.nextTick(function () {
- expect(errorSpy, 'was called times', 1);
+ expect(errorSpy, "was called times", 1);
expect(
err.message,
- 'to match',
- /done\(\) called multiple times/
+ "to match",
+ /done\(\) called multiple times/,
);
- expect(callbackSpy, 'was called times', 1);
+ expect(callbackSpy, "was called times", 1);
done();
});
});
@@ -342,30 +342,30 @@ describe('Runnable(title, fn)', function () {
});
});
- describe('with an error', function () {
+ describe("with an error", function () {
it('should emit a single "error" event', function (done) {
var callbackSpy = sinon.spy();
var errorSpy = sinon.spy();
- var runnable = new Runnable('foo', function (done) {
- done(new Error('fail'));
+ var runnable = new Runnable("foo", function (done) {
+ done(new Error("fail"));
setTimeout(done);
- done(new Error('fail'));
+ done(new Error("fail"));
setTimeout(done);
setTimeout(done);
});
// XXX too many diff assertions and very flimsy assertion that this
// event was only emitted once. think of a better way.
- runnable.on('error', errorSpy).on('error', function (err) {
+ runnable.on("error", errorSpy).on("error", function (err) {
process.nextTick(function () {
- expect(errorSpy, 'was called times', 1);
+ expect(errorSpy, "was called times", 1);
expect(
err.message,
- 'to match',
- /done\(\) called multiple times.+received error: Error: fail/
+ "to match",
+ /done\(\) called multiple times.+received error: Error: fail/,
);
- expect(callbackSpy, 'was called times', 1);
+ expect(callbackSpy, "was called times", 1);
done();
});
});
@@ -375,232 +375,232 @@ describe('Runnable(title, fn)', function () {
});
});
- describe('when an exception is thrown', function () {
- it('should invoke the callback', function (done) {
+ describe("when an exception is thrown", function () {
+ it("should invoke the callback", function (done) {
var runnable = new Runnable(
- 'foo',
- sinon.stub().throws('Error', 'fail')
+ "foo",
+ sinon.stub().throws("Error", "fail"),
);
runnable.run(function (err) {
- expect(err.message, 'to be', 'fail');
+ expect(err.message, "to be", "fail");
done();
});
});
- it('should not throw its own exception if passed a non-object', function (done) {
- var runnable = new Runnable('foo', function () {
+ it("should not throw its own exception if passed a non-object", function (done) {
+ var runnable = new Runnable("foo", function () {
/* eslint no-throw-literal: off */
throw null;
});
runnable.run(function (err) {
- expect(err.message, 'to be', Runnable.toValueOrError().message);
+ expect(err.message, "to be", Runnable.toValueOrError().message);
done();
});
});
});
- describe('when an exception is thrown and is allowed to remain uncaught', function () {
- it('throws an error when it is allowed', function (done) {
- var runnable = new Runnable('foo', function () {
- throw new Error('fail');
+ describe("when an exception is thrown and is allowed to remain uncaught", function () {
+ it("throws an error when it is allowed", function (done) {
+ var runnable = new Runnable("foo", function () {
+ throw new Error("fail");
});
runnable.allowUncaught = true;
function fail() {
runnable.run(function () {});
}
- expect(fail, 'to throw', 'fail');
+ expect(fail, "to throw", "fail");
done();
});
});
- describe('when an error is passed', function () {
- it('should invoke the callback', function (done) {
- var runnable = new Runnable('foo', function (done) {
- done(new Error('fail'));
+ describe("when an error is passed", function () {
+ it("should invoke the callback", function (done) {
+ var runnable = new Runnable("foo", function (done) {
+ done(new Error("fail"));
});
runnable.run(function (err) {
- expect(err.message, 'to be', 'fail');
+ expect(err.message, "to be", "fail");
done();
});
});
});
- describe('when done() is invoked with a non-Error object', function () {
- it('should invoke the callback', function (done) {
- var runnable = new Runnable('foo', function (done) {
+ describe("when done() is invoked with a non-Error object", function () {
+ it("should invoke the callback", function (done) {
+ var runnable = new Runnable("foo", function (done) {
done({
- error: 'Test error'
+ error: "Test error",
});
});
runnable.run(function (err) {
expect(
err.message,
- 'to be',
- 'done() invoked with non-Error: {"error":"Test error"}'
+ "to be",
+ 'done() invoked with non-Error: {"error":"Test error"}',
);
done();
});
});
});
- describe('when done() is invoked with a string', function () {
- it('should invoke the callback', function (done) {
- var runnable = new Runnable('foo', function (done) {
- done('Test error');
+ describe("when done() is invoked with a string", function () {
+ it("should invoke the callback", function (done) {
+ var runnable = new Runnable("foo", function (done) {
+ done("Test error");
});
runnable.run(function (err) {
expect(
err.message,
- 'to be',
- 'done() invoked with non-Error: Test error'
+ "to be",
+ "done() invoked with non-Error: Test error",
);
done();
});
});
});
- it('should allow updating the timeout', function (done) {
+ it("should allow updating the timeout", function (done) {
var spy = sinon.spy();
// Runnable knows whether it's provided a 'done' parameter
// eslint-disable-next-line no-unused-vars
- var runnable = new Runnable('foo', function (done) {
+ var runnable = new Runnable("foo", function (done) {
setTimeout(spy, 1);
setTimeout(spy, 100);
});
runnable.timeout(50);
runnable.run(function (err) {
- expect(err, 'to be truthy');
- expect(spy, 'was called times', 1);
+ expect(err, "to be truthy");
+ expect(spy, "was called times", 1);
done();
});
});
- it('should allow a timeout of 0', function (done) {
- const runnable = new Runnable('foo', () => {});
+ it("should allow a timeout of 0", function (done) {
+ const runnable = new Runnable("foo", () => {});
runnable.timeout(0);
- runnable.run(err => {
- expect(err, 'to be falsy');
+ runnable.run((err) => {
+ expect(err, "to be falsy");
done();
});
});
});
- describe('when fn returns a promise', function () {
- describe('when the promise is fulfilled with no value', function () {
+ describe("when fn returns a promise", function () {
+ describe("when the promise is fulfilled with no value", function () {
var fulfilledPromise = {
then: function (fulfilled) {
setTimeout(fulfilled);
- }
+ },
};
- it('should invoke the callback', function (done) {
- var runnable = new Runnable('foo', function () {
+ it("should invoke the callback", function (done) {
+ var runnable = new Runnable("foo", function () {
return fulfilledPromise;
});
runnable.run(function (err) {
- expect(err, 'to be falsy');
+ expect(err, "to be falsy");
done();
});
});
});
- describe('when the promise is fulfilled with a value', function () {
+ describe("when the promise is fulfilled with a value", function () {
var fulfilledPromise = {
then: function (fulfilled) {
setTimeout(function () {
fulfilled({});
});
- }
+ },
};
- it('should invoke the callback', function (done) {
- var runnable = new Runnable('foo', function () {
+ it("should invoke the callback", function (done) {
+ var runnable = new Runnable("foo", function () {
return fulfilledPromise;
});
runnable.run(function (err) {
- expect(err, 'to be falsy');
+ expect(err, "to be falsy");
done();
});
});
});
- describe('when the promise is rejected', function () {
- var expectedErr = new Error('fail');
+ describe("when the promise is rejected", function () {
+ var expectedErr = new Error("fail");
var rejectedPromise = {
then: function (fulfilled, rejected) {
setTimeout(function () {
rejected(expectedErr);
});
- }
+ },
};
- it('should invoke the callback', function (done) {
- var runnable = new Runnable('foo', function () {
+ it("should invoke the callback", function (done) {
+ var runnable = new Runnable("foo", function () {
return rejectedPromise;
});
runnable.run(function (err) {
- expect(err, 'to be', expectedErr);
+ expect(err, "to be", expectedErr);
done();
});
});
});
- describe('when the promise is rejected without a reason', function () {
- var expectedErr = new Error('Promise rejected with no or falsy reason');
+ describe("when the promise is rejected without a reason", function () {
+ var expectedErr = new Error("Promise rejected with no or falsy reason");
var rejectedPromise = {
then: function (fulfilled, rejected) {
setTimeout(function () {
rejected();
});
- }
+ },
};
- it('should invoke the callback', function (done) {
- var runnable = new Runnable('foo', function () {
+ it("should invoke the callback", function (done) {
+ var runnable = new Runnable("foo", function () {
return rejectedPromise;
});
runnable.run(function (err) {
- expect(err.message, 'to be', expectedErr.message);
+ expect(err.message, "to be", expectedErr.message);
done();
});
});
});
- describe('when the promise takes too long to settle', function () {
+ describe("when the promise takes too long to settle", function () {
var foreverPendingPromise = {
- then: function () {}
+ then: function () {},
};
- it('should throw the timeout error', function (done) {
- var runnable = new Runnable('foo', function () {
+ it("should throw the timeout error", function (done) {
+ var runnable = new Runnable("foo", function () {
return foreverPendingPromise;
});
- runnable.file = '/some/path';
+ runnable.file = "/some/path";
runnable.timeout(10);
runnable.run(function (err) {
- expect(err, 'to satisfy', {code: TIMEOUT, timeout: 10});
+ expect(err, "to satisfy", { code: TIMEOUT, timeout: 10 });
done();
});
});
});
});
- describe('when fn returns a non-promise', function () {
- it('should invoke the callback', function (done) {
- var runnable = new Runnable('foo', function () {
+ describe("when fn returns a non-promise", function () {
+ it("should invoke the callback", function (done) {
+ var runnable = new Runnable("foo", function () {
return {
- then: 'i ran my tests'
+ then: "i ran my tests",
};
});
@@ -608,39 +608,39 @@ describe('Runnable(title, fn)', function () {
});
});
- describe('if timed-out', function () {
- it('should ignore call to `done` and not execute callback again', function (done) {
- var runnable = new Runnable('foo', function (done) {
+ describe("if timed-out", function () {
+ it("should ignore call to `done` and not execute callback again", function (done) {
+ var runnable = new Runnable("foo", function (done) {
setTimeout(done, 20);
});
runnable.timeout(10);
runnable.run(function (err) {
- expect(err, 'to satisfy', {code: TIMEOUT, timeout: 10});
+ expect(err, "to satisfy", { code: TIMEOUT, timeout: 10 });
// timedOut is set *after* this callback is executed
process.nextTick(function () {
- expect(runnable.timedOut, 'to be truthy');
+ expect(runnable.timedOut, "to be truthy");
done();
});
});
});
});
- describe('if async', function () {
- it('this.skip() should set runnable to pending', function (done) {
- var runnable = new Runnable('foo', function () {
+ describe("if async", function () {
+ it("this.skip() should set runnable to pending", function (done) {
+ var runnable = new Runnable("foo", function () {
// normally "this" but it gets around having to muck with a context
runnable.skip();
});
runnable.run(function (err) {
- expect(err, 'to be undefined');
- expect(runnable.pending, 'to be true');
+ expect(err, "to be undefined");
+ expect(runnable.pending, "to be true");
done();
});
});
- it('this.skip() should halt synchronous execution', function (done) {
+ it("this.skip() should halt synchronous execution", function (done) {
var aborted = true;
- var runnable = new Runnable('foo', function () {
+ var runnable = new Runnable("foo", function () {
// normally "this" but it gets around having to muck with a context
runnable.skip();
/* istanbul ignore next */
@@ -648,93 +648,93 @@ describe('Runnable(title, fn)', function () {
});
runnable.run(function () {
process.nextTick(function () {
- expect(aborted, 'to be true');
+ expect(aborted, "to be true");
done();
});
});
});
});
- describe('when fn is not a function', function () {
- it('should throw an error', function () {
- var runnable = new Runnable('foo', 4);
+ describe("when fn is not a function", function () {
+ it("should throw an error", function () {
+ var runnable = new Runnable("foo", 4);
runnable.run(function (err) {
expect(
err.message,
- 'to be',
- 'A runnable must be passed a function as its second argument.'
+ "to be",
+ "A runnable must be passed a function as its second argument.",
);
});
});
});
});
- describe('#isFailed()', function () {
- it('should return `true` if test has not failed', function () {
- var runnable = new Runnable('foo', function () {});
+ describe("#isFailed()", function () {
+ it("should return `true` if test has not failed", function () {
+ var runnable = new Runnable("foo", function () {});
// runner sets the state
runnable.run(function () {
- expect(runnable.isFailed(), 'to be false');
+ expect(runnable.isFailed(), "to be false");
});
});
- it('should return `true` if test has failed', function () {
- var runnable = new Runnable('foo', function () {});
+ it("should return `true` if test has failed", function () {
+ var runnable = new Runnable("foo", function () {});
// runner sets the state
runnable.state = STATE_FAILED;
runnable.run(function () {
- expect(runnable.isFailed(), 'to be false');
+ expect(runnable.isFailed(), "to be false");
});
});
- it('should return `false` if test is pending', function () {
- var runnable = new Runnable('foo', function () {});
+ it("should return `false` if test is pending", function () {
+ var runnable = new Runnable("foo", function () {});
// runner sets the state
runnable.isPending = function () {
return true;
};
runnable.run(function () {
- expect(runnable.isFailed(), 'to be false');
+ expect(runnable.isFailed(), "to be false");
});
});
});
- describe('#resetTimeout()', function () {
- it('should not time out if timeouts disabled after reset', function (done) {
- var runnable = new Runnable('foo', function () {});
+ describe("#resetTimeout()", function () {
+ it("should not time out if timeouts disabled after reset", function (done) {
+ var runnable = new Runnable("foo", function () {});
runnable.timeout(10);
runnable.resetTimeout();
runnable.timeout(0);
runnable.run();
setTimeout(function () {
- expect(runnable.timedOut, 'to be', false);
+ expect(runnable.timedOut, "to be", false);
done();
}, 20);
});
});
- describe('static method', function () {
- describe('toValueOrError', function () {
- it('should return identity if parameter is truthy', function () {
- expect(Runnable.toValueOrError('foo'), 'to be', 'foo');
+ describe("static method", function () {
+ describe("toValueOrError", function () {
+ it("should return identity if parameter is truthy", function () {
+ expect(Runnable.toValueOrError("foo"), "to be", "foo");
});
- it('should return an Error if parameter is falsy', function () {
- expect(Runnable.toValueOrError(null), 'to be an', Error);
+ it("should return an Error if parameter is falsy", function () {
+ expect(Runnable.toValueOrError(null), "to be an", Error);
});
});
});
- describe('interesting property', function () {
- describe('id', function () {
- it('should have a unique identifier', function () {
- expect(new Runnable('foo', () => {}), 'to have property', 'id');
+ describe("interesting property", function () {
+ describe("id", function () {
+ it("should have a unique identifier", function () {
+ expect(new Runnable("foo", () => {}), "to have property", "id");
});
- it('should have a permanent identifier', function () {
- const runnable = new Runnable('foo', () => {});
- expect(runnable.id, 'to be', runnable.id);
+ it("should have a permanent identifier", function () {
+ const runnable = new Runnable("foo", () => {});
+ expect(runnable.id, "to be", runnable.id);
});
});
});
diff --git a/test/unit/runner.spec.js b/test/unit/runner.spec.js
index 7487ddfb..c9cb4a4a 100644
--- a/test/unit/runner.spec.js
+++ b/test/unit/runner.spec.js
@@ -1,13 +1,13 @@
-'use strict';
+"use strict";
-const path = require('node:path');
-const sinon = require('sinon');
-const Mocha = require('../../lib/mocha');
-const Pending = require('../../lib/pending');
-const {Suite, Runner, Test, Hook, Runnable} = Mocha;
-const {noop} = Mocha.utils;
-const {FATAL, MULTIPLE_DONE, UNSUPPORTED} =
- require('../../lib/error-constants').constants;
+const path = require("node:path");
+const sinon = require("sinon");
+const Mocha = require("../../lib/mocha");
+const Pending = require("../../lib/pending");
+const { Suite, Runner, Test, Hook, Runnable } = Mocha;
+const { noop } = Mocha.utils;
+const { FATAL, MULTIPLE_DONE, UNSUPPORTED } =
+ require("../../lib/error-constants").constants;
const {
EVENT_HOOK_BEGIN,
@@ -20,99 +20,99 @@ const {
EVENT_SUITE_END,
STATE_IDLE,
STATE_RUNNING,
- STATE_STOPPED
+ STATE_STOPPED,
} = Runner.constants;
-const {STATE_FAILED} = Mocha.Runnable.constants;
+const { STATE_FAILED } = Mocha.Runnable.constants;
-describe('Runner', function () {
+describe("Runner", function () {
afterEach(function () {
sinon.restore();
});
- describe('instance method', function () {
+ describe("instance method", function () {
let suite;
let runner;
beforeEach(function () {
- suite = new Suite('Suite', 'root');
- runner = new Runner(suite, {cleanReferencesAfterRun: true});
+ suite = new Suite("Suite", "root");
+ runner = new Runner(suite, { cleanReferencesAfterRun: true });
runner.checkLeaks = true;
});
- describe('grep()', function () {
- it('should update the runner.total with number of matched tests', function () {
- suite.addTest(new Test('im a test about lions', noop));
- suite.addTest(new Test('im another test about lions', noop));
- suite.addTest(new Test('im a test about bears', noop));
+ describe("grep()", function () {
+ it("should update the runner.total with number of matched tests", function () {
+ suite.addTest(new Test("im a test about lions", noop));
+ suite.addTest(new Test("im another test about lions", noop));
+ suite.addTest(new Test("im a test about bears", noop));
var newRunner = new Runner(suite);
newRunner.grep(/lions/);
- expect(newRunner.total, 'to be', 2);
+ expect(newRunner.total, "to be", 2);
});
- it('should update the runner.total with number of matched tests when inverted', function () {
- suite.addTest(new Test('im a test about lions', noop));
- suite.addTest(new Test('im another test about lions', noop));
- suite.addTest(new Test('im a test about bears', noop));
+ it("should update the runner.total with number of matched tests when inverted", function () {
+ suite.addTest(new Test("im a test about lions", noop));
+ suite.addTest(new Test("im another test about lions", noop));
+ suite.addTest(new Test("im a test about bears", noop));
var newRunner = new Runner(suite);
newRunner.grep(/lions/, true);
- expect(newRunner.total, 'to be', 1);
+ expect(newRunner.total, "to be", 1);
});
});
- describe('grepTotal()', function () {
- it('should return the total number of matched tests', function () {
- suite.addTest(new Test('im a test about lions', noop));
- suite.addTest(new Test('im another test about lions', noop));
- suite.addTest(new Test('im a test about bears', noop));
+ describe("grepTotal()", function () {
+ it("should return the total number of matched tests", function () {
+ suite.addTest(new Test("im a test about lions", noop));
+ suite.addTest(new Test("im another test about lions", noop));
+ suite.addTest(new Test("im a test about bears", noop));
runner.grep(/lions/);
- expect(runner.grepTotal(suite), 'to be', 2);
+ expect(runner.grepTotal(suite), "to be", 2);
});
- it('should return the total number of matched tests when inverted', function () {
- suite.addTest(new Test('im a test about lions', noop));
- suite.addTest(new Test('im another test about lions', noop));
- suite.addTest(new Test('im a test about bears', noop));
+ it("should return the total number of matched tests when inverted", function () {
+ suite.addTest(new Test("im a test about lions", noop));
+ suite.addTest(new Test("im another test about lions", noop));
+ suite.addTest(new Test("im a test about bears", noop));
runner.grep(/lions/, true);
- expect(runner.grepTotal(suite), 'to be', 1);
+ expect(runner.grepTotal(suite), "to be", 1);
});
});
- describe('globalProps()', function () {
- it('should include common non enumerable globals', function () {
+ describe("globalProps()", function () {
+ it("should include common non enumerable globals", function () {
var props = runner.globalProps();
expect(
props,
- 'to contain',
- 'setTimeout',
- 'clearTimeout',
- 'setInterval',
- 'clearInterval',
- 'Date',
- 'XMLHttpRequest'
+ "to contain",
+ "setTimeout",
+ "clearTimeout",
+ "setInterval",
+ "clearInterval",
+ "Date",
+ "XMLHttpRequest",
);
});
});
- describe('globals()', function () {
- it('should default to the known globals', function () {
- expect(runner.globals().length, 'to be greater than', 16);
+ describe("globals()", function () {
+ it("should default to the known globals", function () {
+ expect(runner.globals().length, "to be greater than", 16);
});
- it('should white-list globals', function () {
- runner.globals(['foo', 'bar']);
- expect(runner.globals(), 'to contain', 'foo', 'bar');
+ it("should white-list globals", function () {
+ runner.globals(["foo", "bar"]);
+ expect(runner.globals(), "to contain", "foo", "bar");
});
});
- describe('checkGlobals(test)', function () {
+ describe("checkGlobals(test)", function () {
before(function () {
if (!Object.create) {
this.skip();
}
});
- it('should allow variables that match a wildcard', function (done) {
- runner.globals(['foo*', 'giz*']);
- global.foo = 'baz';
- global.gizmo = 'quux';
+ it("should allow variables that match a wildcard", function (done) {
+ runner.globals(["foo*", "giz*"]);
+ global.foo = "baz";
+ global.gizmo = "quux";
runner.checkGlobals();
delete global.foo;
delete global.gizmo;
@@ -120,12 +120,12 @@ describe('Runner', function () {
});
it('should emit "fail" when a new global is introduced', function (done) {
- var test = new Test('im a test', noop);
+ var test = new Test("im a test", noop);
runner.checkGlobals();
- global.foo = 'bar';
+ global.foo = "bar";
runner.on(EVENT_TEST_FAIL, function (_test, _err) {
- expect(_test, 'to be', test);
- expect(_err, 'to have message', "global leak(s) detected: 'foo'");
+ expect(_test, "to be", test);
+ expect(_err, "to have message", "global leak(s) detected: 'foo'");
delete global.foo;
done();
});
@@ -134,63 +134,63 @@ describe('Runner', function () {
it('should emit "fail" when a single new disallowed global is introduced after a single extra global is allowed', function (done) {
var doneCalled = false;
- runner.globals('good');
+ runner.globals("good");
global.bad = 1;
runner.on(EVENT_TEST_FAIL, function () {
delete global.bad;
done();
doneCalled = true;
});
- runner.checkGlobals(new Test('yet another test', noop));
+ runner.checkGlobals(new Test("yet another test", noop));
if (!doneCalled) {
- done(Error('Expected test failure did not occur.'));
+ done(Error("Expected test failure did not occur."));
}
});
- it('should not fail when a new common global is introduced', function () {
+ it("should not fail when a new common global is introduced", function () {
if (process.browser) {
this.skip();
return;
}
// verify that the prop isn't enumerable
expect(
- Object.prototype.propertyIsEnumerable.call(global, 'XMLHttpRequest'),
- 'to be',
- false
+ Object.prototype.propertyIsEnumerable.call(global, "XMLHttpRequest"),
+ "to be",
+ false,
);
// create a new runner and keep a reference to the test.
- var test = new Test('im a test about bears', noop);
+ var test = new Test("im a test about bears", noop);
suite.addTest(test);
var newRunner = new Runner(suite);
// make the prop enumerable again.
global.XMLHttpRequest = noop;
expect(
- Object.prototype.propertyIsEnumerable.call(global, 'XMLHttpRequest'),
- 'to be',
- true
+ Object.prototype.propertyIsEnumerable.call(global, "XMLHttpRequest"),
+ "to be",
+ true,
);
// verify the test hasn't failed.
newRunner.checkGlobals(test);
- expect(test, 'not to have key', 'state');
+ expect(test, "not to have key", "state");
// clean up our global space.
delete global.XMLHttpRequest;
});
- it('should pluralize the error message when several are introduced', function (done) {
- var test = new Test('im a test', noop);
+ it("should pluralize the error message when several are introduced", function (done) {
+ var test = new Test("im a test", noop);
runner.checkGlobals();
- global.foo = 'bar';
- global.bar = 'baz';
+ global.foo = "bar";
+ global.bar = "baz";
runner.on(EVENT_TEST_FAIL, function (_test, _err) {
- expect(_test, 'to be', test);
+ expect(_test, "to be", test);
expect(
_err.message,
- 'to be',
- "global leak(s) detected: 'foo', 'bar'"
+ "to be",
+ "global leak(s) detected: 'foo', 'bar'",
);
delete global.foo;
delete global.bar;
@@ -199,33 +199,33 @@ describe('Runner', function () {
runner.checkGlobals(test);
});
- it('should respect per test whitelisted globals', function () {
- var test = new Test('im a test about lions', noop);
- test.globals(['foo']);
+ it("should respect per test whitelisted globals", function () {
+ var test = new Test("im a test about lions", noop);
+ test.globals(["foo"]);
suite.addTest(test);
var runner = new Runner(suite);
- global.foo = 'bar';
+ global.foo = "bar";
// verify the test hasn't failed.
runner.checkGlobals(test);
- expect(test, 'not to have key', 'state');
+ expect(test, "not to have key", "state");
delete global.foo;
});
- it('should respect per test whitelisted globals but still detect other leaks', function (done) {
- var test = new Test('im a test about lions', noop);
- test.globals(['foo']);
+ it("should respect per test whitelisted globals but still detect other leaks", function (done) {
+ var test = new Test("im a test about lions", noop);
+ test.globals(["foo"]);
suite.addTest(test);
- global.foo = 'whitelisted';
- global.bar = 'detect-me';
+ global.foo = "whitelisted";
+ global.bar = "detect-me";
runner.on(EVENT_TEST_FAIL, function (_test, _err) {
- expect(_test.title, 'to be', 'im a test about lions');
- expect(_err, 'to have message', "global leak(s) detected: 'bar'");
+ expect(_test.title, "to be", "im a test about lions");
+ expect(_err, "to have message", "global leak(s) detected: 'bar'");
delete global.foo;
delete global.bar;
done();
@@ -234,36 +234,36 @@ describe('Runner', function () {
});
it('should emit "fail" when a global beginning with "d" is introduced', function (done) {
- global.derp = 'bar';
+ global.derp = "bar";
runner.on(EVENT_TEST_FAIL, function (_test, _err) {
- expect(_test.title, 'to be', 'herp');
- expect(_err, 'to have message', "global leak(s) detected: 'derp'");
+ expect(_test.title, "to be", "herp");
+ expect(_err, "to have message", "global leak(s) detected: 'derp'");
delete global.derp;
done();
});
- runner.checkGlobals(new Test('herp', noop));
+ runner.checkGlobals(new Test("herp", noop));
});
});
- describe('hook()', function () {
- it('should execute hooks after failed test if suite bail is true', function (done) {
- runner.fail(new Test('failed test', noop), new Error());
+ describe("hook()", function () {
+ it("should execute hooks after failed test if suite bail is true", function (done) {
+ runner.fail(new Test("failed test", noop), new Error());
suite.bail(true);
suite.afterEach(function () {
suite.afterAll(function () {
done();
});
});
- runner.hook('afterEach', noop);
- runner.hook('afterAll', noop);
+ runner.hook("afterEach", noop);
+ runner.hook("afterAll", noop);
});
- it('should augment hook title with current test title', function (done) {
+ it("should augment hook title with current test title", function (done) {
var expectedHookTitle;
function assertHookTitle() {
- expect(hook.title, 'to be', expectedHookTitle);
+ expect(hook.title, "to be", expectedHookTitle);
}
var failHook = false;
- var hookError = new Error('failed hook');
+ var hookError = new Error("failed hook");
suite.beforeEach(function () {
assertHookTitle();
if (failHook) {
@@ -276,19 +276,19 @@ describe('Runner', function () {
runner.on(EVENT_TEST_PASS, assertHookTitle);
var hook = suite._beforeEach[0];
- suite.addTest(new Test('should behave', noop));
- suite.addTest(new Test('should obey', noop));
+ suite.addTest(new Test("should behave", noop));
+ suite.addTest(new Test("should obey", noop));
runner.suite = suite;
runner.test = suite.tests[0];
expectedHookTitle = '"before each" hook for "should behave"';
- runner.hook('beforeEach', function (err) {
+ runner.hook("beforeEach", function (err) {
if (err && err !== hookError) return done(err);
runner.test = suite.tests[1];
failHook = true;
expectedHookTitle = '"before each" hook for "should obey"';
- runner.hook('beforeEach', function (err) {
+ runner.hook("beforeEach", function (err) {
if (err && err !== hookError) return done(err);
return done();
});
@@ -296,137 +296,137 @@ describe('Runner', function () {
});
});
- describe('fail()', function () {
- it('should increment `Runner#failures`', function () {
- expect(runner.failures, 'to be', 0);
- runner.fail(new Test('one', noop), {});
- expect(runner.failures, 'to be', 1);
- runner.fail(new Test('two', noop), new Error());
- expect(runner.failures, 'to be', 2);
+ describe("fail()", function () {
+ it("should increment `Runner#failures`", function () {
+ expect(runner.failures, "to be", 0);
+ runner.fail(new Test("one", noop), {});
+ expect(runner.failures, "to be", 1);
+ runner.fail(new Test("two", noop), new Error());
+ expect(runner.failures, "to be", 2);
});
it('should set `Test#state` to "failed"', function () {
- var test = new Test('some test', noop);
- runner.fail(test, 'some error');
- expect(test.state, 'to be', STATE_FAILED);
+ var test = new Test("some test", noop);
+ runner.fail(test, "some error");
+ expect(test.state, "to be", STATE_FAILED);
});
it('should emit "fail"', function (done) {
- var test = new Test('some other test', noop);
+ var test = new Test("some other test", noop);
var err = {};
runner.on(EVENT_TEST_FAIL, function (_test, _err) {
- expect(_test, 'to be', test);
- expect(_err, 'to be an', Error);
- expect(_err, 'not to be', {});
+ expect(_test, "to be", test);
+ expect(_err, "to be an", Error);
+ expect(_err, "not to be", {});
done();
});
runner.fail(test, err);
});
- it('should emit a helpful message when failed with a string', function (done) {
- var test = new Test('helpful test', noop);
- var err = 'string';
+ it("should emit a helpful message when failed with a string", function (done) {
+ var test = new Test("helpful test", noop);
+ var err = "string";
runner.on(EVENT_TEST_FAIL, function (_test, _err) {
- expect(_err, 'to be an', Error);
+ expect(_err, "to be an", Error);
expect(
_err,
- 'to have message',
- 'the string "string" was thrown, throw an Error :)'
+ "to have message",
+ 'the string "string" was thrown, throw an Error :)',
);
done();
});
runner.fail(test, err);
});
- it('should emit a the error when failed with an Error instance', function (done) {
- var test = new Test('a test', noop);
- var err = new Error('an error message');
+ it("should emit a the error when failed with an Error instance", function (done) {
+ var test = new Test("a test", noop);
+ var err = new Error("an error message");
runner.on(EVENT_TEST_FAIL, function (_test, _err) {
- expect(_err, 'to be an', Error);
- expect(_err, 'to have message', 'an error message');
+ expect(_err, "to be an", Error);
+ expect(_err, "to have message", "an error message");
done();
});
runner.fail(test, err);
});
- it('should emit the error when failed with an Error-like object', function (done) {
- var test = new Test('a test', noop);
- var err = {message: 'an error message'};
+ it("should emit the error when failed with an Error-like object", function (done) {
+ var test = new Test("a test", noop);
+ var err = { message: "an error message" };
runner.on(EVENT_TEST_FAIL, function (_test, _err) {
- expect(_err, 'not to be an', Error);
- expect(_err.message, 'to be', 'an error message');
+ expect(_err, "not to be an", Error);
+ expect(_err.message, "to be", "an error message");
done();
});
runner.fail(test, err);
});
- it('should emit a helpful message when failed with an Object', function (done) {
- var test = new Test('a test', noop);
- var err = {x: 1};
+ it("should emit a helpful message when failed with an Object", function (done) {
+ var test = new Test("a test", noop);
+ var err = { x: 1 };
runner.on(EVENT_TEST_FAIL, function (_test, _err) {
- expect(_err, 'to be an', Error);
+ expect(_err, "to be an", Error);
expect(
_err,
- 'to have message',
- 'the object {\n "x": 1\n} was thrown, throw an Error :)'
+ "to have message",
+ 'the object {\n "x": 1\n} was thrown, throw an Error :)',
);
done();
});
runner.fail(test, err);
});
- it('should emit a helpful message when failed with an Array', function (done) {
- var test = new Test('a test', noop);
+ it("should emit a helpful message when failed with an Array", function (done) {
+ var test = new Test("a test", noop);
var err = [1, 2];
runner.on(EVENT_TEST_FAIL, function (_test, _err) {
- expect(_err, 'to be an', Error);
+ expect(_err, "to be an", Error);
expect(
_err,
- 'to have message',
- 'the array [\n 1\n 2\n] was thrown, throw an Error :)'
+ "to have message",
+ "the array [\n 1\n 2\n] was thrown, throw an Error :)",
);
done();
});
runner.fail(test, err);
});
- it('should recover if the error stack is not writable', function (done) {
+ it("should recover if the error stack is not writable", function (done) {
if (!Object.create) {
this.skip();
return;
}
- var err = new Error('not evil');
- Object.defineProperty(err, 'stack', {
- value: err.stack
+ var err = new Error("not evil");
+ Object.defineProperty(err, "stack", {
+ value: err.stack,
});
- var test = new Test('a test', noop);
+ var test = new Test("a test", noop);
runner.on(EVENT_TEST_FAIL, function (_test, _err) {
- expect(_err, 'to have message', 'not evil');
+ expect(_err, "to have message", "not evil");
done();
});
runner.fail(test, err);
});
- it('should return and not increment failures when test is pending', function () {
- var test = new Test('a test');
+ it("should return and not increment failures when test is pending", function () {
+ var test = new Test("a test");
suite.addTest(test);
test.pending = true;
runner.fail(test, new Error());
- expect(runner.failures, 'to be', 0);
+ expect(runner.failures, "to be", 0);
});
- describe('when Runner has stopped', function () {
+ describe("when Runner has stopped", function () {
beforeEach(function () {
runner.state = STATE_STOPPED;
});
- describe('when test is not pending', function () {
+ describe("when test is not pending", function () {
describe('when error is the "multiple done" variety', function () {
it('should throw the "multiple done" error', function () {
- var test = new Test('test', function () {});
+ var test = new Test("test", function () {});
suite.addTest(test);
var err = new Error();
err.code = MULTIPLE_DONE;
@@ -434,49 +434,49 @@ describe('Runner', function () {
function () {
runner.fail(test, err);
},
- 'to throw',
- err
+ "to throw",
+ err,
);
});
});
describe('when error is not of the "multiple done" variety', function () {
it('should throw a "fatal" error', function () {
- var test = new Test('test', function () {});
+ var test = new Test("test", function () {});
suite.addTest(test);
var err = new Error();
expect(
function () {
runner.fail(test, err);
},
- 'to throw',
+ "to throw",
{
- code: FATAL
- }
+ code: FATAL,
+ },
);
});
});
});
});
- it('should increment .failures', function () {
- expect(runner.failures, 'to be', 0);
- var test1 = new Test('fail hook 1', noop);
- var test2 = new Test('fail hook 2', noop);
+ it("should increment .failures", function () {
+ expect(runner.failures, "to be", 0);
+ var test1 = new Test("fail hook 1", noop);
+ var test2 = new Test("fail hook 2", noop);
suite.addTest(test1);
suite.addTest(test2);
- runner.fail(test1, new Error('error1'));
- expect(runner.failures, 'to be', 1);
- runner.fail(test2, new Error('error2'));
- expect(runner.failures, 'to be', 2);
+ runner.fail(test1, new Error("error1"));
+ expect(runner.failures, "to be", 1);
+ runner.fail(test2, new Error("error2"));
+ expect(runner.failures, "to be", 2);
});
it('should emit "fail"', function (done) {
var hook = new Hook();
hook.parent = suite;
- var err = new Error('error');
+ var err = new Error("error");
runner.on(EVENT_TEST_FAIL, function (_hook, _err) {
- expect(_hook, 'to be', hook);
- expect(_err, 'to be', err);
+ expect(_hook, "to be", hook);
+ expect(_err, "to be", err);
done();
});
runner.fail(hook, err);
@@ -485,27 +485,27 @@ describe('Runner', function () {
it('should not emit "end" if suite bail is not true', function (done) {
var hook = new Hook();
hook.parent = suite;
- var err = new Error('error');
+ var err = new Error("error");
suite.bail(false);
expect(
function () {
runner.fail(hook, err);
},
- 'not to emit from',
+ "not to emit from",
hook,
- EVENT_RUN_END
+ EVENT_RUN_END,
);
done();
});
});
- describe('run()', function () {
+ describe("run()", function () {
it('should emit "retry" when a retryable test fails', function (done) {
var retries = 2;
var retryableFails = 0;
- var err = new Error('bear error');
+ var err = new Error("bear error");
- var test = new Test('im a test about bears', function () {
+ var test = new Test("im a test about bears", function () {
if (retryableFails < retries) {
throw err;
}
@@ -516,82 +516,82 @@ describe('Runner', function () {
runner.on(EVENT_TEST_RETRY, function (testClone, testErr) {
retryableFails += 1;
- expect(testClone.title, 'to be', test.title);
- expect(testErr, 'to be', err);
+ expect(testClone.title, "to be", test.title);
+ expect(testErr, "to be", err);
});
runner.run(function (failures) {
- expect(failures, 'to be', 0);
- expect(retryableFails, 'to be', retries);
+ expect(failures, "to be", 0);
+ expect(retryableFails, "to be", retries);
done();
});
});
// karma-mocha is inexplicably doing this with a Hook
- it('should not throw an exception if something emits EVENT_TEST_END with a non-Test object', function () {
+ it("should not throw an exception if something emits EVENT_TEST_END with a non-Test object", function () {
expect(function () {
runner.emit(EVENT_TEST_END, {});
- }, 'not to throw');
+ }, "not to throw");
});
- it('should clean references after a run', function () {
+ it("should clean references after a run", function () {
runner = new Runner(suite, {
delay: false,
- cleanReferencesAfterRun: true
+ cleanReferencesAfterRun: true,
});
- var cleanReferencesStub = sinon.stub(suite, 'cleanReferences');
+ var cleanReferencesStub = sinon.stub(suite, "cleanReferences");
runner.run();
runner.emit(EVENT_SUITE_END, suite);
- expect(cleanReferencesStub, 'was called once');
+ expect(cleanReferencesStub, "was called once");
});
- it('should not clean references after a run when `cleanReferencesAfterRun` is `false`', function () {
+ it("should not clean references after a run when `cleanReferencesAfterRun` is `false`", function () {
runner = new Runner(suite, {
delay: false,
- cleanReferencesAfterRun: false
+ cleanReferencesAfterRun: false,
});
- var cleanReferencesStub = sinon.stub(suite, 'cleanReferences');
+ var cleanReferencesStub = sinon.stub(suite, "cleanReferences");
runner.run();
runner.emit(EVENT_SUITE_END, suite);
- expect(cleanReferencesStub, 'was not called');
+ expect(cleanReferencesStub, "was not called");
});
- it('should not leak `Process.uncaughtException` listeners', function (done) {
+ it("should not leak `Process.uncaughtException` listeners", function (done) {
var normalUncaughtExceptionListenerCount =
- process.listenerCount('uncaughtException');
+ process.listenerCount("uncaughtException");
runner.run();
runner.run();
runner.run();
expect(
- process.listenerCount('uncaughtException'),
- 'to be',
- normalUncaughtExceptionListenerCount + 1
+ process.listenerCount("uncaughtException"),
+ "to be",
+ normalUncaughtExceptionListenerCount + 1,
);
done();
});
- describe('stack traces', function () {
+ describe("stack traces", function () {
var stack = [
- 'AssertionError: foo bar',
- 'at EventEmitter.<anonymous> (/usr/local/dev/test.js:16:12)',
- 'at Context.<anonymous> (/usr/local/dev/test.js:19:5)',
- 'Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:244:7)',
- 'Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:374:10)',
- '/usr/local/lib/node_modules/mocha/lib/runner.js:452:12',
- 'next (/usr/local/lib/node_modules/mocha/lib/runner.js:299:14)',
- '/usr/local/lib/node_modules/mocha/lib/runner.js:309:7',
- 'next (/usr/local/lib/node_modules/mocha/lib/runner.js:248:23)',
- 'Immediate._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:276:5)',
- 'at processImmediate [as _immediateCallback] (timers.js:321:17)'
+ "AssertionError: foo bar",
+ "at EventEmitter.<anonymous> (/usr/local/dev/test.js:16:12)",
+ "at Context.<anonymous> (/usr/local/dev/test.js:19:5)",
+ "Test.Runnable.run (/usr/local/lib/node_modules/mocha/lib/runnable.js:244:7)",
+ "Runner.runTest (/usr/local/lib/node_modules/mocha/lib/runner.js:374:10)",
+ "/usr/local/lib/node_modules/mocha/lib/runner.js:452:12",
+ "next (/usr/local/lib/node_modules/mocha/lib/runner.js:299:14)",
+ "/usr/local/lib/node_modules/mocha/lib/runner.js:309:7",
+ "next (/usr/local/lib/node_modules/mocha/lib/runner.js:248:23)",
+ "Immediate._onImmediate (/usr/local/lib/node_modules/mocha/lib/runner.js:276:5)",
+ "at processImmediate [as _immediateCallback] (timers.js:321:17)",
];
before(function () {
// Only for Node running on Windows
- if (process.platform === 'win32') {
+ if (process.platform === "win32") {
var addDrive = function (str) {
- var drive = 'C:';
+ var drive = "C:";
var pos = str.indexOf(path.posix.sep);
return pos !== -1
? str.slice(0, pos) + drive + str.slice(pos)
@@ -609,81 +609,81 @@ describe('Runner', function () {
}
});
- describe('short', function () {
+ describe("short", function () {
before(function () {
if (process.browser) {
this.skip();
}
});
- it('should prettify the stack-trace', function (done) {
+ it("should prettify the stack-trace", function (done) {
var hook = new Hook();
hook.parent = suite;
var err = new Error();
// Fake stack-trace
- err.stack = stack.join('\n');
+ err.stack = stack.join("\n");
runner.on(EVENT_TEST_FAIL, function (_hook, _err) {
- expect(_err.stack, 'to be', stack.slice(0, 3).join('\n'));
+ expect(_err.stack, "to be", stack.slice(0, 3).join("\n"));
done();
});
runner.fail(hook, err);
});
- it('should prettify stack-traces in error cause trail', function (done) {
+ it("should prettify stack-traces in error cause trail", function (done) {
var hook = new Hook();
hook.parent = suite;
var causeErr = new Error();
// Fake stack-trace
- causeErr.stack = stack.join('\n');
+ causeErr.stack = stack.join("\n");
var err = new Error();
err.cause = causeErr;
runner.on(EVENT_TEST_FAIL, function (_hook, _err) {
- expect(_err.cause.stack, 'to be', stack.slice(0, 3).join('\n'));
+ expect(_err.cause.stack, "to be", stack.slice(0, 3).join("\n"));
done();
});
runner.fail(hook, err);
});
});
- describe('long', function () {
- it('should display the full stack-trace', function (done) {
+ describe("long", function () {
+ it("should display the full stack-trace", function (done) {
var hook = new Hook();
hook.parent = suite;
var err = new Error();
// Fake stack-trace
- err.stack = stack.join('\n');
+ err.stack = stack.join("\n");
// Add --stack-trace option
runner.fullStackTrace = true;
runner.on(EVENT_TEST_FAIL, function (_hook, _err) {
- expect(_err.stack, 'to be', stack.join('\n'));
+ expect(_err.stack, "to be", stack.join("\n"));
done();
});
runner.fail(hook, err);
});
- it('should display full stack-traces in error cause trail', function (done) {
+ it("should display full stack-traces in error cause trail", function (done) {
var hook = new Hook();
hook.parent = suite;
var causeErr = new Error();
// Fake stack-trace
- causeErr.stack = stack.join('\n');
+ causeErr.stack = stack.join("\n");
var err = new Error();
err.cause = causeErr;
// Add --stack-trace option
runner.fullStackTrace = true;
runner.on(EVENT_TEST_FAIL, function (_hook, _err) {
- expect(_err.cause.stack, 'to be', stack.join('\n'));
+ expect(_err.cause.stack, "to be", stack.join("\n"));
done();
});
runner.fail(hook, err);
});
});
- describe('ginormous', function () {
+ describe("ginormous", function () {
before(function () {
if (process.browser) {
this.skip();
@@ -696,7 +696,7 @@ describe('Runner', function () {
var data = [];
data.length = n;
for (var i = 0; i < n; i++) {
- data[i] = {a: 1};
+ data[i] = { a: 1 };
}
return JSON.stringify(data);
}
@@ -707,47 +707,47 @@ describe('Runner', function () {
var data = [];
data.length = n;
var str =
- 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.';
+ "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
for (var i = 0; i < n; i++) {
data[i] = str;
}
- return data.join('\n');
+ return data.join("\n");
}
- it('should not hang if overlong error message is single line', function (done) {
+ it("should not hang if overlong error message is single line", function (done) {
var hook = new Hook();
hook.parent = suite;
var message = genOverlongSingleLineMessage();
var err = new Error();
// Fake stack-trace
- err.stack = [message].concat(stack).join('\n');
+ err.stack = [message].concat(stack).join("\n");
runner.on(EVENT_TEST_FAIL, function (_hook, _err) {
- var filteredErrStack = _err.stack.split('\n').slice(1);
+ var filteredErrStack = _err.stack.split("\n").slice(1);
expect(
- filteredErrStack.join('\n'),
- 'to be',
- stack.slice(0, 3).join('\n')
+ filteredErrStack.join("\n"),
+ "to be",
+ stack.slice(0, 3).join("\n"),
);
done();
});
runner.fail(hook, err);
});
- it('should not hang if overlong error message is multiple lines', function (done) {
+ it("should not hang if overlong error message is multiple lines", function (done) {
var hook = new Hook();
hook.parent = suite;
var message = genOverlongMultiLineMessage();
var err = new Error();
// Fake stack-trace
- err.stack = [message].concat(stack).join('\n');
+ err.stack = [message].concat(stack).join("\n");
runner.on(EVENT_TEST_FAIL, function (_hook, _err) {
- var filteredErrStack = _err.stack.split('\n').slice(-3);
+ var filteredErrStack = _err.stack.split("\n").slice(-3);
expect(
- filteredErrStack.join('\n'),
- 'to be',
- stack.slice(0, 3).join('\n')
+ filteredErrStack.join("\n"),
+ "to be",
+ stack.slice(0, 3).join("\n"),
);
done();
});
@@ -757,81 +757,81 @@ describe('Runner', function () {
});
});
- describe('runAsync()', function () {
+ describe("runAsync()", function () {
beforeEach(function () {
- sinon.stub(runner, 'run').callsArgWithAsync(0, 42).returnsThis();
+ sinon.stub(runner, "run").callsArgWithAsync(0, 42).returnsThis();
});
- it('should return a Promise with a failure count', async function () {
- return expect(runner.runAsync(), 'to be fulfilled with', 42);
+ it("should return a Promise with a failure count", async function () {
+ return expect(runner.runAsync(), "to be fulfilled with", 42);
});
- it('should pass through options to Runner#run', async function () {
- await runner.runAsync({foo: 'bar'});
- expect(runner.run, 'to have a call satisfying', [
- expect.it('to be a function'),
- {foo: 'bar'}
- ]).and('was called once');
+ it("should pass through options to Runner#run", async function () {
+ await runner.runAsync({ foo: "bar" });
+ expect(runner.run, "to have a call satisfying", [
+ expect.it("to be a function"),
+ { foo: "bar" },
+ ]).and("was called once");
});
});
- describe('dispose()', function () {
- it('should remove all listeners from itself', function () {
- runner.on('disposeShouldRemoveThis', noop);
+ describe("dispose()", function () {
+ it("should remove all listeners from itself", function () {
+ runner.on("disposeShouldRemoveThis", noop);
runner.dispose();
- expect(runner.listenerCount('disposeShouldRemoveThis'), 'to be', 0);
+ expect(runner.listenerCount("disposeShouldRemoveThis"), "to be", 0);
});
it('should remove "error" listeners from a test', function () {
var fn = sinon.stub();
- runner.test = new Test('test for dispose', fn);
+ runner.test = new Test("test for dispose", fn);
runner.runTest(noop);
// sanity check
- expect(runner.test.listenerCount('error'), 'to be', 1);
+ expect(runner.test.listenerCount("error"), "to be", 1);
runner.dispose();
- expect(runner.test.listenerCount('error'), 'to be', 0);
+ expect(runner.test.listenerCount("error"), "to be", 0);
});
it('should remove "uncaughtException" listeners from the process', function () {
var normalUncaughtExceptionListenerCount =
- process.listenerCount('uncaughtException');
+ process.listenerCount("uncaughtException");
runner.run(noop);
// sanity check
expect(
- process.listenerCount('uncaughtException'),
- 'to be',
- normalUncaughtExceptionListenerCount + 1
+ process.listenerCount("uncaughtException"),
+ "to be",
+ normalUncaughtExceptionListenerCount + 1,
);
runner.dispose();
expect(
- process.listenerCount('uncaughtException'),
- 'to be',
- normalUncaughtExceptionListenerCount
+ process.listenerCount("uncaughtException"),
+ "to be",
+ normalUncaughtExceptionListenerCount,
);
});
});
- describe('runTest()', function () {
- it('should return when no tests to run', function () {
+ describe("runTest()", function () {
+ it("should return when no tests to run", function () {
runner.test = undefined;
- expect(runner.runTest(noop), 'to be undefined');
+ expect(runner.runTest(noop), "to be undefined");
});
});
- describe('allowUncaught()', function () {
- it('should allow unhandled errors to propagate through', function () {
+ describe("allowUncaught()", function () {
+ it("should allow unhandled errors to propagate through", function () {
var newRunner = new Runner(suite);
newRunner.allowUncaught = true;
- newRunner.test = new Test('failing test', function () {
- throw new Error('allow unhandled errors');
+ newRunner.test = new Test("failing test", function () {
+ throw new Error("allow unhandled errors");
});
function fail() {
newRunner.runTest();
}
- expect(fail, 'to throw', 'allow unhandled errors');
+ expect(fail, "to throw", "allow unhandled errors");
});
- it('should not allow unhandled errors in sync hooks to propagate through', function (done) {
+ it("should not allow unhandled errors in sync hooks to propagate through", function (done) {
suite.beforeEach(function () {
throw new Error();
});
@@ -846,17 +846,17 @@ describe('Runner', function () {
function throwError() {
_run.call(hook, fn);
}
- expect(throwError, 'not to throw');
+ expect(throwError, "not to throw");
done();
};
});
- runner.hook('beforeEach', noop);
+ runner.hook("beforeEach", noop);
});
- it('should allow unhandled errors in sync hooks to propagate through', function (done) {
+ it("should allow unhandled errors in sync hooks to propagate through", function (done) {
suite.beforeEach(function () {
- throw new Error('allow unhandled errors in sync hooks');
+ throw new Error("allow unhandled errors in sync hooks");
});
var runner = new Runner(suite);
runner.allowUncaught = true;
@@ -867,20 +867,20 @@ describe('Runner', function () {
function throwError() {
_run.call(hook, fn);
}
- var expected = 'allow unhandled errors in sync hooks';
- expect(throwError, 'to throw', expected);
+ var expected = "allow unhandled errors in sync hooks";
+ expect(throwError, "to throw", expected);
done();
};
});
- runner.hook('beforeEach', noop);
+ runner.hook("beforeEach", noop);
});
- it('async - should allow unhandled errors in hooks to propagate through', function (done) {
+ it("async - should allow unhandled errors in hooks to propagate through", function (done) {
// the `done` argument, although unused, it triggers the async path
// see this.async in the Runnable constructor
suite.beforeEach(function () {
- throw new Error('allow unhandled errors in async hooks');
+ throw new Error("allow unhandled errors in async hooks");
});
var runner = new Runner(suite);
runner.allowUncaught = true;
@@ -891,282 +891,282 @@ describe('Runner', function () {
function throwError() {
_run.call(hook, fn);
}
- var expected = 'allow unhandled errors in async hooks';
- expect(throwError, 'to throw', expected);
+ var expected = "allow unhandled errors in async hooks";
+ expect(throwError, "to throw", expected);
done();
};
});
- runner.hook('beforeEach', noop);
+ runner.hook("beforeEach", noop);
});
});
- describe('abort()', function () {
- it('should set _abort property to true', function () {
+ describe("abort()", function () {
+ it("should set _abort property to true", function () {
runner.abort();
- expect(runner._abort, 'to be true');
+ expect(runner._abort, "to be true");
});
- it('should return the Runner', function () {
- expect(runner.abort(), 'to be', runner);
+ it("should return the Runner", function () {
+ expect(runner.abort(), "to be", runner);
});
});
- describe('_uncaught()', function () {
- describe('when called with a non-Runner context', function () {
- it('should throw', function () {
- expect(runner._uncaught.bind({}), 'to throw', {
- code: FATAL
+ describe("_uncaught()", function () {
+ describe("when called with a non-Runner context", function () {
+ it("should throw", function () {
+ expect(runner._uncaught.bind({}), "to throw", {
+ code: FATAL,
});
});
});
});
- describe('uncaught()', function () {
+ describe("uncaught()", function () {
beforeEach(function () {
- sinon.stub(runner, 'fail');
+ sinon.stub(runner, "fail");
});
- describe('when allow-uncaught is set to true', function () {
- it('should propagate error and throw', function () {
+ describe("when allow-uncaught is set to true", function () {
+ it("should propagate error and throw", function () {
if (process.browser) this.skip();
- var err = new Error('should rethrow err');
+ var err = new Error("should rethrow err");
runner.allowUncaught = true;
expect(
function () {
runner.uncaught(err);
},
- 'to throw',
- 'should rethrow err'
+ "to throw",
+ "should rethrow err",
);
});
});
- describe('when provided an object argument', function () {
- describe('when argument is not an Error', function () {
+ describe("when provided an object argument", function () {
+ describe("when argument is not an Error", function () {
var err;
beforeEach(function () {
- err = {whatever: 'yolo'};
+ err = { whatever: "yolo" };
});
- it('should fail with a transient Runnable and a new Error coerced from the object', function () {
+ it("should fail with a transient Runnable and a new Error coerced from the object", function () {
runner.uncaught(err);
- expect(runner.fail, 'to have all calls satisfying', [
- expect.it('to be a', Runnable).and('to satisfy', {
+ expect(runner.fail, "to have all calls satisfying", [
+ expect.it("to be a", Runnable).and("to satisfy", {
parent: runner.suite,
- title: /uncaught error outside test suite/i
+ title: /uncaught error outside test suite/i,
}),
- expect.it('to be an', Error).and('to satisfy', {
+ expect.it("to be an", Error).and("to satisfy", {
message: /throw an error/i,
- uncaught: true
- })
- ]).and('was called once');
+ uncaught: true,
+ }),
+ ]).and("was called once");
});
});
- describe('when argument is a Pending', function () {
- it('should ignore argument and return', function () {
+ describe("when argument is a Pending", function () {
+ it("should ignore argument and return", function () {
var err = new Pending();
- expect(runner.uncaught(err), 'to be undefined');
+ expect(runner.uncaught(err), "to be undefined");
});
});
- describe('when argument is an Error', function () {
+ describe("when argument is an Error", function () {
var err;
beforeEach(function () {
- err = new Error('sorry dave');
+ err = new Error("sorry dave");
});
it('should add the "uncaught" property to the Error', function () {
runner.uncaught(err);
- expect(err, 'to have property', 'uncaught', true);
+ expect(err, "to have property", "uncaught", true);
});
- describe('when no Runnables are running', function () {
+ describe("when no Runnables are running", function () {
beforeEach(function () {
delete runner.currentRunnable;
});
- it('should fail with a transient Runnable and the error', function () {
+ it("should fail with a transient Runnable and the error", function () {
runner.uncaught(err);
- expect(runner.fail, 'to have all calls satisfying', [
- expect.it('to be a', Runnable).and('to satisfy', {
+ expect(runner.fail, "to have all calls satisfying", [
+ expect.it("to be a", Runnable).and("to satisfy", {
parent: runner.suite,
- title: /uncaught error outside test suite/i
+ title: /uncaught error outside test suite/i,
}),
- err
- ]).and('was called once');
+ err,
+ ]).and("was called once");
});
- describe('when Runner is RUNNING', function () {
+ describe("when Runner is RUNNING", function () {
beforeEach(function () {
runner.state = STATE_RUNNING;
});
- it('should not emit start/end events', function () {
+ it("should not emit start/end events", function () {
expect(
function () {
runner.uncaught(err);
},
- 'not to emit from',
+ "not to emit from",
runner,
- 'start'
- ).and('not to emit from', runner, 'end');
+ "start",
+ ).and("not to emit from", runner, "end");
});
});
- describe('when Runner is IDLE', function () {
+ describe("when Runner is IDLE", function () {
beforeEach(function () {
runner.state = STATE_IDLE;
});
- it('should emit start/end events for the benefit of reporters', function () {
+ it("should emit start/end events for the benefit of reporters", function () {
expect(
function () {
runner.uncaught(err);
},
- 'to emit from',
+ "to emit from",
runner,
- 'start'
- ).and('to emit from', runner, 'end');
+ "start",
+ ).and("to emit from", runner, "end");
});
});
- describe('when Runner is STOPPED', function () {
+ describe("when Runner is STOPPED", function () {
beforeEach(function () {
runner.state = STATE_STOPPED;
});
- it('should not emit start/end events, since this presumably would have already happened', function () {
+ it("should not emit start/end events, since this presumably would have already happened", function () {
expect(
function () {
try {
runner.uncaught(err);
} catch (ignored) {}
},
- 'not to emit from',
+ "not to emit from",
runner,
- 'start'
- ).and('not to emit from', runner, 'end');
+ "start",
+ ).and("not to emit from", runner, "end");
});
- it('should throw', function () {
+ it("should throw", function () {
expect(function () {
runner.uncaught(err);
- }, 'to throw');
+ }, "to throw");
});
});
});
- describe('when a Runnable is running or has run', function () {
+ describe("when a Runnable is running or has run", function () {
var runnable;
beforeEach(function () {
runnable = new Runnable();
runnable.parent = runner.suite;
- sinon.stub(runnable, 'clearTimeout');
+ sinon.stub(runnable, "clearTimeout");
runner.currentRunnable = runnable;
});
- it('should clear any pending timeouts', function () {
+ it("should clear any pending timeouts", function () {
runnable.callback = sinon.fake();
runner.uncaught(err);
- expect(runnable.clearTimeout, 'was called times', 1);
+ expect(runnable.clearTimeout, "was called times", 1);
});
- describe('when current Runnable has already failed', function () {
+ describe("when current Runnable has already failed", function () {
beforeEach(function () {
- sinon.stub(runnable, 'isFailed').returns(true);
+ sinon.stub(runnable, "isFailed").returns(true);
});
- it('should not attempt to fail again', function () {
+ it("should not attempt to fail again", function () {
runner.uncaught(err);
- expect(runner.fail, 'was not called');
+ expect(runner.fail, "was not called");
});
});
- describe('when current Runnable has been marked pending', function () {
+ describe("when current Runnable has been marked pending", function () {
beforeEach(function () {
- sinon.stub(runnable, 'isPending').returns(true);
+ sinon.stub(runnable, "isPending").returns(true);
});
- it('should attempt to fail', function () {
+ it("should attempt to fail", function () {
runner.uncaught(err);
- expect(runner.fail, 'was called once');
+ expect(runner.fail, "was called once");
});
});
- describe('when the current Runnable has already passed', function () {
+ describe("when the current Runnable has already passed", function () {
beforeEach(function () {
- sinon.stub(runnable, 'isPassed').returns(true);
+ sinon.stub(runnable, "isPassed").returns(true);
});
- it('should fail with the current Runnable and the error', function () {
+ it("should fail with the current Runnable and the error", function () {
runner.uncaught(err);
- expect(runner.fail, 'to have all calls satisfying', [
- expect.it('to be', runnable),
- err
- ]).and('was called once');
+ expect(runner.fail, "to have all calls satisfying", [
+ expect.it("to be", runnable),
+ err,
+ ]).and("was called once");
});
- it('should abort the runner without emitting end event', function () {
+ it("should abort the runner without emitting end event", function () {
expect(
function () {
runner.uncaught(err);
},
- 'not to emit from',
+ "not to emit from",
runner,
- 'end'
+ "end",
);
- expect(runner._abort, 'to be', true);
+ expect(runner._abort, "to be", true);
});
});
- describe('when the current Runnable is still running', function () {
- describe('when the current Runnable is a Test', function () {
+ describe("when the current Runnable is still running", function () {
+ describe("when the current Runnable is a Test", function () {
beforeEach(function () {
- runnable = new Test('goomba', noop);
+ runnable = new Test("goomba", noop);
runnable.parent = runner.suite;
runner.currentRunnable = runnable;
runnable.callback = sinon.fake();
});
- it('should run callback(err) to handle failing and hooks', function () {
+ it("should run callback(err) to handle failing and hooks", function () {
runner.uncaught(err);
- expect(runner.fail, 'was not called');
- expect(runnable.callback, 'to have all calls satisfying', [
- err
- ]).and('was called once');
+ expect(runner.fail, "was not called");
+ expect(runnable.callback, "to have all calls satisfying", [
+ err,
+ ]).and("was called once");
});
- it('should not notify test has ended', function () {
+ it("should not notify test has ended", function () {
expect(
function () {
runner.uncaught(err);
},
- 'not to emit from',
+ "not to emit from",
runner,
- EVENT_TEST_END
+ EVENT_TEST_END,
);
});
- it('should not notify run has ended', function () {
+ it("should not notify run has ended", function () {
expect(
function () {
runner.uncaught(err);
},
- 'not to emit from',
+ "not to emit from",
runner,
- EVENT_RUN_END
+ EVENT_RUN_END,
);
});
});
- describe('when the current Runnable is a Hook', function () {
+ describe("when the current Runnable is a Hook", function () {
beforeEach(function () {
runnable = new Hook();
runnable.parent = runner.suite;
@@ -1174,34 +1174,34 @@ describe('Runner', function () {
runnable.callback = sinon.fake();
});
- it('should run callback(err) to handle failing hook pattern', function () {
+ it("should run callback(err) to handle failing hook pattern", function () {
runner.uncaught(err);
- expect(runner.fail, 'was not called');
- expect(runnable.callback, 'to have all calls satisfying', [
- err
- ]).and('was called once');
+ expect(runner.fail, "was not called");
+ expect(runnable.callback, "to have all calls satisfying", [
+ err,
+ ]).and("was called once");
});
- it('should not notify test has ended', function () {
+ it("should not notify test has ended", function () {
expect(
function () {
runner.uncaught(err);
},
- 'not to emit from',
+ "not to emit from",
runner,
- EVENT_TEST_END
+ EVENT_TEST_END,
);
});
- it('should not notify run has ended', function () {
+ it("should not notify run has ended", function () {
expect(
function () {
runner.uncaught(err);
},
- 'not to emit from',
+ "not to emit from",
runner,
- EVENT_RUN_END
+ EVENT_RUN_END,
);
});
});
@@ -1211,21 +1211,23 @@ describe('Runner', function () {
});
});
- describe('linkPartialObjects()', function () {
- it('should return the Runner', function () {
- expect(runner.linkPartialObjects(), 'to be', runner);
+ describe("linkPartialObjects()", function () {
+ it("should return the Runner", function () {
+ expect(runner.linkPartialObjects(), "to be", runner);
});
});
- describe('isParallelMode()', function () {
- it('should return false', function () {
- expect(runner.isParallelMode(), 'to be false');
+ describe("isParallelMode()", function () {
+ it("should return false", function () {
+ expect(runner.isParallelMode(), "to be false");
});
});
- describe('workerReporter()', function () {
- it('should throw', function () {
- expect(() => runner.workerReporter(), 'to throw', {code: UNSUPPORTED});
+ describe("workerReporter()", function () {
+ it("should throw", function () {
+ expect(() => runner.workerReporter(), "to throw", {
+ code: UNSUPPORTED,
+ });
});
});
});
diff --git a/test/unit/suite.spec.js b/test/unit/suite.spec.js
index e7dc8e4f..01b1e959 100644
--- a/test/unit/suite.spec.js
+++ b/test/unit/suite.spec.js
@@ -1,188 +1,188 @@
-'use strict';
+"use strict";
-const Mocha = require('../../lib/mocha');
-const {Suite, Test, Context} = Mocha;
-const sinon = require('sinon');
-const errors = require('../../lib/errors');
+const Mocha = require("../../lib/mocha");
+const { Suite, Test, Context } = Mocha;
+const sinon = require("sinon");
+const errors = require("../../lib/errors");
function supportsFunctionNames() {
// eslint-disable-next-line no-extra-parens
- return function foo() {}.name === 'foo';
+ return function foo() {}.name === "foo";
}
-describe('Suite', function () {
+describe("Suite", function () {
afterEach(function () {
sinon.restore();
});
- describe('instance method', function () {
+ describe("instance method", function () {
let suite;
- describe('clone()', function () {
+ describe("clone()", function () {
beforeEach(function () {
- suite = new Suite('To be cloned', {}, true);
+ suite = new Suite("To be cloned", {}, true);
suite._timeout = 3043;
suite._slow = 101;
suite._bail = true;
suite.suites.push(1);
- suite.tests.push('hello');
+ suite.tests.push("hello");
suite._beforeEach.push(2);
suite._beforeAll.push(3);
suite._afterEach.push(4);
suite._afterAll.push(5);
});
- it('should clone the Suite, omitting children', function () {
- expect(suite.clone(), 'to satisfy', {
- title: 'To be cloned',
+ it("should clone the Suite, omitting children", function () {
+ expect(suite.clone(), "to satisfy", {
+ title: "To be cloned",
_timeout: 3043,
_slow: 101,
_bail: true,
- suites: expect.it('to be empty'),
- tests: expect.it('to be empty'),
- _beforeEach: expect.it('to be empty'),
- _beforeAll: expect.it('to be empty'),
- _afterEach: expect.it('to be empty'),
- _afterAll: expect.it('to be empty'),
- root: true
- }).and('not to be', suite);
+ suites: expect.it("to be empty"),
+ tests: expect.it("to be empty"),
+ _beforeEach: expect.it("to be empty"),
+ _beforeAll: expect.it("to be empty"),
+ _afterEach: expect.it("to be empty"),
+ _afterAll: expect.it("to be empty"),
+ root: true,
+ }).and("not to be", suite);
});
});
- describe('reset()', function () {
+ describe("reset()", function () {
beforeEach(function () {
- suite = new Suite('Suite to be reset', function () {});
+ suite = new Suite("Suite to be reset", function () {});
});
- it('should reset the `delayed` state', function () {
+ it("should reset the `delayed` state", function () {
suite.delayed = true;
suite.reset();
- expect(suite.delayed, 'to be', false);
+ expect(suite.delayed, "to be", false);
});
- it('should forward reset to suites and tests', function () {
- const childSuite = new Suite('child suite', suite.context);
- const test = new Test('test', function () {});
+ it("should forward reset to suites and tests", function () {
+ const childSuite = new Suite("child suite", suite.context);
+ const test = new Test("test", function () {});
suite.addSuite(childSuite);
suite.addTest(test);
- const testResetStub = sinon.stub(test, 'reset');
- const suiteResetStub = sinon.stub(childSuite, 'reset');
+ const testResetStub = sinon.stub(test, "reset");
+ const suiteResetStub = sinon.stub(childSuite, "reset");
suite.reset();
- expect(testResetStub, 'was called once');
- expect(suiteResetStub, 'was called once');
+ expect(testResetStub, "was called once");
+ expect(suiteResetStub, "was called once");
});
- it('should forward reset to all hooks', function () {
+ it("should forward reset to all hooks", function () {
suite.beforeEach(function () {});
suite.afterEach(function () {});
suite.beforeAll(function () {});
suite.afterAll(function () {});
- sinon.stub(suite.getHooks('beforeEach')[0], 'reset');
- sinon.stub(suite.getHooks('afterEach')[0], 'reset');
- sinon.stub(suite.getHooks('beforeAll')[0], 'reset');
- sinon.stub(suite.getHooks('afterAll')[0], 'reset');
+ sinon.stub(suite.getHooks("beforeEach")[0], "reset");
+ sinon.stub(suite.getHooks("afterEach")[0], "reset");
+ sinon.stub(suite.getHooks("beforeAll")[0], "reset");
+ sinon.stub(suite.getHooks("afterAll")[0], "reset");
suite.reset();
- expect(suite.getHooks('beforeEach')[0].reset, 'was called once');
- expect(suite.getHooks('afterEach')[0].reset, 'was called once');
- expect(suite.getHooks('beforeAll')[0].reset, 'was called once');
- expect(suite.getHooks('afterAll')[0].reset, 'was called once');
+ expect(suite.getHooks("beforeEach")[0].reset, "was called once");
+ expect(suite.getHooks("afterEach")[0].reset, "was called once");
+ expect(suite.getHooks("beforeAll")[0].reset, "was called once");
+ expect(suite.getHooks("afterAll")[0].reset, "was called once");
});
});
- describe('timeout()', function () {
+ describe("timeout()", function () {
beforeEach(function () {
- suite = new Suite('A Suite');
+ suite = new Suite("A Suite");
});
- describe('when no argument is passed', function () {
- it('should return the timeout value', function () {
- expect(suite.timeout(), 'to be', 2000);
+ describe("when no argument is passed", function () {
+ it("should return the timeout value", function () {
+ expect(suite.timeout(), "to be", 2000);
});
});
- describe('when argument is passed', function () {
- it('should return the Suite object', function () {
+ describe("when argument is passed", function () {
+ it("should return the Suite object", function () {
const newSuite = suite.timeout(5000);
- expect(newSuite.timeout(), 'to be', 5000);
+ expect(newSuite.timeout(), "to be", 5000);
});
});
});
- describe('slow()', function () {
+ describe("slow()", function () {
beforeEach(function () {
- suite = new Suite('A Suite');
+ suite = new Suite("A Suite");
});
- describe('when given a string', function () {
- it('should parse it', function () {
- suite.slow('5 seconds');
- expect(suite.slow(), 'to be', 5000);
+ describe("when given a string", function () {
+ it("should parse it", function () {
+ suite.slow("5 seconds");
+ expect(suite.slow(), "to be", 5000);
});
});
- describe('when no argument is passed', function () {
- it('should return the slow value', function () {
- expect(suite.slow(), 'to be', 75);
+ describe("when no argument is passed", function () {
+ it("should return the slow value", function () {
+ expect(suite.slow(), "to be", 75);
});
});
- describe('when argument is passed', function () {
- it('should return the Suite object', function () {
+ describe("when argument is passed", function () {
+ it("should return the Suite object", function () {
const newSuite = suite.slow(5000);
- expect(newSuite.slow(), 'to be', 5000);
+ expect(newSuite.slow(), "to be", 5000);
});
});
});
- describe('bail()', function () {
+ describe("bail()", function () {
beforeEach(function () {
- suite = new Suite('A Suite');
+ suite = new Suite("A Suite");
suite._bail = true;
});
- describe('when no argument is passed', function () {
- it('should return the bail value', function () {
- expect(suite.bail(), 'to be', true);
+ describe("when no argument is passed", function () {
+ it("should return the bail value", function () {
+ expect(suite.bail(), "to be", true);
});
});
- describe('when argument is passed', function () {
- it('should return the Suite object', function () {
+ describe("when argument is passed", function () {
+ it("should return the Suite object", function () {
const newSuite = suite.bail(false);
- expect(newSuite.bail(), 'to be', false);
+ expect(newSuite.bail(), "to be", false);
});
});
});
- describe('beforeAll()', function () {
+ describe("beforeAll()", function () {
beforeEach(function () {
- suite = new Suite('A Suite');
+ suite = new Suite("A Suite");
});
- describe('wraps the passed in function in a Hook', function () {
- it('adds it to _beforeAll', function () {
+ describe("wraps the passed in function in a Hook", function () {
+ it("adds it to _beforeAll", function () {
const fn = function () {};
suite.beforeAll(fn);
- expect(suite._beforeAll, 'to have length', 1);
+ expect(suite._beforeAll, "to have length", 1);
const beforeAllItem = suite._beforeAll[0];
- expect(beforeAllItem.title, 'to match', /^"before all" hook/);
- expect(beforeAllItem.fn, 'to be', fn);
+ expect(beforeAllItem.title, "to match", /^"before all" hook/);
+ expect(beforeAllItem.fn, "to be", fn);
});
- it('appends title to hook', function () {
+ it("appends title to hook", function () {
const fn = function () {};
- suite.beforeAll('test', fn);
+ suite.beforeAll("test", fn);
- expect(suite._beforeAll, 'to have length', 1);
+ expect(suite._beforeAll, "to have length", 1);
const beforeAllItem = suite._beforeAll[0];
- expect(beforeAllItem.title, 'to be', '"before all" hook: test');
- expect(beforeAllItem.fn, 'to be', fn);
+ expect(beforeAllItem.title, "to be", '"before all" hook: test');
+ expect(beforeAllItem.fn, "to be", fn);
});
- it('uses function name if available', function () {
+ it("uses function name if available", function () {
if (!supportsFunctionNames()) {
this.skip();
return;
@@ -190,38 +190,38 @@ describe('Suite', function () {
function namedFn() {}
suite.beforeAll(namedFn);
const beforeAllItem = suite._beforeAll[0];
- expect(beforeAllItem.title, 'to be', '"before all" hook: namedFn');
- expect(beforeAllItem.fn, 'to be', namedFn);
+ expect(beforeAllItem.title, "to be", '"before all" hook: namedFn');
+ expect(beforeAllItem.fn, "to be", namedFn);
});
});
});
- describe('afterAll()', function () {
+ describe("afterAll()", function () {
beforeEach(function () {
- suite = new Suite('A Suite');
+ suite = new Suite("A Suite");
});
- describe('wraps the passed in function in a Hook', function () {
- it('adds it to _afterAll', function () {
+ describe("wraps the passed in function in a Hook", function () {
+ it("adds it to _afterAll", function () {
const fn = function () {};
suite.afterAll(fn);
- expect(suite._afterAll, 'to have length', 1);
+ expect(suite._afterAll, "to have length", 1);
const afterAllItem = suite._afterAll[0];
- expect(afterAllItem.title, 'to match', /^"after all" hook/);
- expect(afterAllItem.fn, 'to be', fn);
+ expect(afterAllItem.title, "to match", /^"after all" hook/);
+ expect(afterAllItem.fn, "to be", fn);
});
- it('appends title to hook', function () {
+ it("appends title to hook", function () {
const fn = function () {};
- suite.afterAll('test', fn);
+ suite.afterAll("test", fn);
- expect(suite._afterAll, 'to have length', 1);
+ expect(suite._afterAll, "to have length", 1);
const beforeAllItem = suite._afterAll[0];
- expect(beforeAllItem.title, 'to be', '"after all" hook: test');
- expect(beforeAllItem.fn, 'to be', fn);
+ expect(beforeAllItem.title, "to be", '"after all" hook: test');
+ expect(beforeAllItem.fn, "to be", fn);
});
- it('uses function name if available', function () {
+ it("uses function name if available", function () {
if (!supportsFunctionNames()) {
this.skip();
return;
@@ -229,41 +229,41 @@ describe('Suite', function () {
function namedFn() {}
suite.afterAll(namedFn);
const afterAllItem = suite._afterAll[0];
- expect(afterAllItem.title, 'to be', '"after all" hook: namedFn');
- expect(afterAllItem.fn, 'to be', namedFn);
+ expect(afterAllItem.title, "to be", '"after all" hook: namedFn');
+ expect(afterAllItem.fn, "to be", namedFn);
});
});
});
- describe('beforeEach()', function () {
+ describe("beforeEach()", function () {
let suite;
beforeEach(function () {
- suite = new Suite('A Suite');
+ suite = new Suite("A Suite");
});
- describe('wraps the passed in function in a Hook', function () {
- it('adds it to _beforeEach', function () {
+ describe("wraps the passed in function in a Hook", function () {
+ it("adds it to _beforeEach", function () {
const fn = function () {};
suite.beforeEach(fn);
- expect(suite._beforeEach, 'to have length', 1);
+ expect(suite._beforeEach, "to have length", 1);
const beforeEachItem = suite._beforeEach[0];
- expect(beforeEachItem.title, 'to match', /^"before each" hook/);
- expect(beforeEachItem.fn, 'to be', fn);
+ expect(beforeEachItem.title, "to match", /^"before each" hook/);
+ expect(beforeEachItem.fn, "to be", fn);
});
- it('appends title to hook', function () {
+ it("appends title to hook", function () {
const fn = function () {};
- suite.beforeEach('test', fn);
+ suite.beforeEach("test", fn);
- expect(suite._beforeEach, 'to have length', 1);
+ expect(suite._beforeEach, "to have length", 1);
const beforeAllItem = suite._beforeEach[0];
- expect(beforeAllItem.title, 'to be', '"before each" hook: test');
- expect(beforeAllItem.fn, 'to be', fn);
+ expect(beforeAllItem.title, "to be", '"before each" hook: test');
+ expect(beforeAllItem.fn, "to be", fn);
});
- it('uses function name if available', function () {
+ it("uses function name if available", function () {
if (!supportsFunctionNames()) {
this.skip();
return;
@@ -271,50 +271,50 @@ describe('Suite', function () {
function namedFn() {}
suite.beforeEach(namedFn);
const beforeEachItem = suite._beforeEach[0];
- expect(beforeEachItem.title, 'to be', '"before each" hook: namedFn');
- expect(beforeEachItem.fn, 'to be', namedFn);
+ expect(beforeEachItem.title, "to be", '"before each" hook: namedFn');
+ expect(beforeEachItem.fn, "to be", namedFn);
});
});
- describe('when the suite is pending', function () {
+ describe("when the suite is pending", function () {
beforeEach(function () {
suite.pending = true;
});
- it('should not create a hook', function () {
+ it("should not create a hook", function () {
suite.beforeEach(function () {});
- expect(suite._beforeEach, 'to be empty');
+ expect(suite._beforeEach, "to be empty");
});
});
});
- describe('afterEach()', function () {
+ describe("afterEach()", function () {
beforeEach(function () {
- suite = new Suite('A Suite');
+ suite = new Suite("A Suite");
});
- describe('wraps the passed in function in a Hook', function () {
- it('adds it to _afterEach', function () {
+ describe("wraps the passed in function in a Hook", function () {
+ it("adds it to _afterEach", function () {
const fn = function () {};
suite.afterEach(fn);
- expect(suite._afterEach, 'to have length', 1);
+ expect(suite._afterEach, "to have length", 1);
const afterEachItem = suite._afterEach[0];
- expect(afterEachItem.title, 'to match', /^"after each" hook/);
- expect(afterEachItem.fn, 'to be', fn);
+ expect(afterEachItem.title, "to match", /^"after each" hook/);
+ expect(afterEachItem.fn, "to be", fn);
});
- it('appends title to hook', function () {
+ it("appends title to hook", function () {
const fn = function () {};
- suite.afterEach('test', fn);
+ suite.afterEach("test", fn);
- expect(suite._afterEach, 'to have length', 1);
+ expect(suite._afterEach, "to have length", 1);
const beforeAllItem = suite._afterEach[0];
- expect(beforeAllItem.title, 'to be', '"after each" hook: test');
- expect(beforeAllItem.fn, 'to be', fn);
+ expect(beforeAllItem.title, "to be", '"after each" hook: test');
+ expect(beforeAllItem.fn, "to be", fn);
});
- it('uses function name if available', function () {
+ it("uses function name if available", function () {
if (!supportsFunctionNames()) {
this.skip();
return;
@@ -322,199 +322,199 @@ describe('Suite', function () {
function namedFn() {}
suite.afterEach(namedFn);
const afterEachItem = suite._afterEach[0];
- expect(afterEachItem.title, 'to be', '"after each" hook: namedFn');
- expect(afterEachItem.fn, 'to be', namedFn);
+ expect(afterEachItem.title, "to be", '"after each" hook: namedFn');
+ expect(afterEachItem.fn, "to be", namedFn);
});
});
});
- describe('create()', function () {
+ describe("create()", function () {
let first;
let second;
before(function () {
- first = new Suite('Root suite', {}, true);
- second = new Suite('RottenRoot suite', {}, true);
+ first = new Suite("Root suite", {}, true);
+ second = new Suite("RottenRoot suite", {}, true);
first.addSuite(second);
});
- it('does not create a second root suite', function () {
- expect(second.parent, 'to be', first);
- expect(first.root, 'to be', true);
- expect(second.root, 'to be', false);
+ it("does not create a second root suite", function () {
+ expect(second.parent, "to be", first);
+ expect(first.root, "to be", true);
+ expect(second.root, "to be", false);
});
- it('does not denote the root suite by being titleless', function () {
- const emptyTitleSuite = Suite.create(second, '');
- expect(emptyTitleSuite.parent, 'to be', second);
- expect(emptyTitleSuite.root, 'to be', false);
- expect(second.root, 'to be', false);
+ it("does not denote the root suite by being titleless", function () {
+ const emptyTitleSuite = Suite.create(second, "");
+ expect(emptyTitleSuite.parent, "to be", second);
+ expect(emptyTitleSuite.root, "to be", false);
+ expect(second.root, "to be", false);
});
});
- describe('addSuite()', function () {
+ describe("addSuite()", function () {
let first;
let second;
beforeEach(function () {
- first = new Suite('First suite');
+ first = new Suite("First suite");
first.timeout(4002);
first.slow(200);
- second = new Suite('Second suite');
+ second = new Suite("Second suite");
first.addSuite(second);
});
- it('sets the parent on the added Suite', function () {
- expect(second.parent, 'to be', first);
+ it("sets the parent on the added Suite", function () {
+ expect(second.parent, "to be", first);
});
- it('copies the timeout value', function () {
- expect(second.timeout(), 'to be', 4002);
+ it("copies the timeout value", function () {
+ expect(second.timeout(), "to be", 4002);
});
- it('copies the slow value', function () {
- expect(second.slow(), 'to be', 200);
+ it("copies the slow value", function () {
+ expect(second.slow(), "to be", 200);
});
- it('adds the suite to the suites collection', function () {
- expect(first.suites, 'to have length', 1);
- expect(first.suites[0], 'to be', second);
+ it("adds the suite to the suites collection", function () {
+ expect(first.suites, "to have length", 1);
+ expect(first.suites[0], "to be", second);
});
- it('treats suite as pending if its parent is pending', function () {
+ it("treats suite as pending if its parent is pending", function () {
first.pending = true;
- expect(second.isPending(), 'to be', true);
+ expect(second.isPending(), "to be", true);
});
});
- describe('addTest()', function () {
+ describe("addTest()", function () {
let test;
beforeEach(function () {
- suite = new Suite('A Suite', new Context());
+ suite = new Suite("A Suite", new Context());
suite.timeout(4002);
- test = new Test('test');
+ test = new Test("test");
suite.addTest(test);
});
- it('sets the parent on the added test', function () {
- expect(test.parent, 'to be', suite);
+ it("sets the parent on the added test", function () {
+ expect(test.parent, "to be", suite);
});
- it('copies the timeout value', function () {
- expect(test.timeout(), 'to be', 4002);
+ it("copies the timeout value", function () {
+ expect(test.timeout(), "to be", 4002);
});
- it('adds the test to the tests collection', function () {
- expect(suite.tests, 'to satisfy', [test]).and('to have length', 1);
+ it("adds the test to the tests collection", function () {
+ expect(suite.tests, "to satisfy", [test]).and("to have length", 1);
});
});
- describe('fullTitle()', function () {
+ describe("fullTitle()", function () {
beforeEach(function () {
- suite = new Suite('A Suite');
+ suite = new Suite("A Suite");
});
- describe('when there is no parent', function () {
- it('returns the suite title', function () {
- expect(suite.fullTitle(), 'to be', 'A Suite');
+ describe("when there is no parent", function () {
+ it("returns the suite title", function () {
+ expect(suite.fullTitle(), "to be", "A Suite");
});
});
- describe('when there is a parent', function () {
+ describe("when there is a parent", function () {
it("returns the combination of parent's and suite's title", function () {
- const parentSuite = new Suite('I am a parent');
+ const parentSuite = new Suite("I am a parent");
parentSuite.addSuite(suite);
- expect(suite.fullTitle(), 'to be', 'I am a parent A Suite');
+ expect(suite.fullTitle(), "to be", "I am a parent A Suite");
});
});
});
- describe('titlePath()', function () {
+ describe("titlePath()", function () {
beforeEach(function () {
- suite = new Suite('A Suite');
+ suite = new Suite("A Suite");
});
- describe('when there is no parent', function () {
- it('returns the suite title', function () {
- expect(suite.titlePath(), 'to equal', ['A Suite']);
+ describe("when there is no parent", function () {
+ it("returns the suite title", function () {
+ expect(suite.titlePath(), "to equal", ["A Suite"]);
});
});
- describe('when there is a parent', function () {
- describe('the parent is the root suite', function () {
- it('returns the suite title', function () {
- const rootSuite = new Suite('', {}, true);
+ describe("when there is a parent", function () {
+ describe("the parent is the root suite", function () {
+ it("returns the suite title", function () {
+ const rootSuite = new Suite("", {}, true);
rootSuite.addSuite(suite);
- expect(suite.titlePath(), 'to equal', ['A Suite']);
+ expect(suite.titlePath(), "to equal", ["A Suite"]);
});
});
- describe('the parent is not the root suite', function () {
+ describe("the parent is not the root suite", function () {
it("returns the concatenation of parent's and suite's title", function () {
- const parentSuite = new Suite('I am a parent');
+ const parentSuite = new Suite("I am a parent");
parentSuite.addSuite(suite);
- expect(suite.titlePath(), 'to equal', ['I am a parent', 'A Suite']);
+ expect(suite.titlePath(), "to equal", ["I am a parent", "A Suite"]);
});
});
});
});
- describe('total()', function () {
+ describe("total()", function () {
beforeEach(function () {
- suite = new Suite('A Suite');
+ suite = new Suite("A Suite");
});
- describe('when there are no nested suites or tests', function () {
- it('should return 0', function () {
- expect(suite.total(), 'to be', 0);
+ describe("when there are no nested suites or tests", function () {
+ it("should return 0", function () {
+ expect(suite.total(), "to be", 0);
});
});
- describe('when there are several tests in the suite', function () {
- it('should return the number', function () {
- suite.addTest(new Test('a child test'));
- suite.addTest(new Test('another child test'));
- expect(suite.total(), 'to be', 2);
+ describe("when there are several tests in the suite", function () {
+ it("should return the number", function () {
+ suite.addTest(new Test("a child test"));
+ suite.addTest(new Test("another child test"));
+ expect(suite.total(), "to be", 2);
});
});
});
- describe('eachTest(fn)', function () {
+ describe("eachTest(fn)", function () {
beforeEach(function () {
- suite = new Suite('A Suite');
+ suite = new Suite("A Suite");
});
- describe('when there are no nested suites or tests', function () {
- it('should return 0', function () {
+ describe("when there are no nested suites or tests", function () {
+ it("should return 0", function () {
let n = 0;
function fn() {
n++;
}
suite.eachTest(fn);
- expect(n, 'to be', 0);
+ expect(n, "to be", 0);
});
});
- describe('when there are several tests in the suite', function () {
- it('should return the number', function () {
- suite.addTest(new Test('a child test'));
- suite.addTest(new Test('another child test'));
+ describe("when there are several tests in the suite", function () {
+ it("should return the number", function () {
+ suite.addTest(new Test("a child test"));
+ suite.addTest(new Test("another child test"));
let n = 0;
function fn() {
n++;
}
suite.eachTest(fn);
- expect(n, 'to be', 2);
+ expect(n, "to be", 2);
});
});
- describe('when there are several levels of nested suites', function () {
- it('should return the number', function () {
- suite.addTest(new Test('a child test'));
- const childSuite = new Suite('a child suite');
- childSuite.addTest(new Test('a test in a child suite'));
+ describe("when there are several levels of nested suites", function () {
+ it("should return the number", function () {
+ suite.addTest(new Test("a child test"));
+ const childSuite = new Suite("a child suite");
+ childSuite.addTest(new Test("a test in a child suite"));
suite.addSuite(childSuite);
let n = 0;
@@ -522,91 +522,91 @@ describe('Suite', function () {
n++;
}
suite.eachTest(fn);
- expect(n, 'to be', 2);
+ expect(n, "to be", 2);
});
});
});
- describe('constructor', function () {
+ describe("constructor", function () {
beforeEach(function () {
- sinon.stub(errors, 'deprecate');
+ sinon.stub(errors, "deprecate");
});
/* eslint no-new: off */
it("should throw an error if the title isn't a string", function () {
expect(function () {
- new Suite(undefined, 'root');
- }, 'to throw');
+ new Suite(undefined, "root");
+ }, "to throw");
expect(function () {
- new Suite(function () {}, 'root');
- }, 'to throw');
+ new Suite(function () {}, "root");
+ }, "to throw");
});
- it('should not throw if the title is a string', function () {
+ it("should not throw if the title is a string", function () {
expect(function () {
- new Suite('Bdd suite', 'root');
- }, 'not to throw');
+ new Suite("Bdd suite", "root");
+ }, "not to throw");
});
});
- describe('timeout()', function () {
- it('should convert a string to milliseconds', function () {
- const suite = new Suite('some suite');
- suite.timeout('100');
- expect(suite.timeout(), 'to be', 100);
+ describe("timeout()", function () {
+ it("should convert a string to milliseconds", function () {
+ const suite = new Suite("some suite");
+ suite.timeout("100");
+ expect(suite.timeout(), "to be", 100);
});
});
- describe('hasOnly()', function () {
- it('should return true if a test has `only`', function () {
- const suite = new Suite('foo');
- const test = new Test('bar');
+ describe("hasOnly()", function () {
+ it("should return true if a test has `only`", function () {
+ const suite = new Suite("foo");
+ const test = new Test("bar");
suite.appendOnlyTest(test);
- expect(suite.hasOnly(), 'to be', true);
+ expect(suite.hasOnly(), "to be", true);
});
- it('should return true if a suite has `only`', function () {
- const suite = new Suite('foo');
- const nested = new Suite('bar');
+ it("should return true if a suite has `only`", function () {
+ const suite = new Suite("foo");
+ const nested = new Suite("bar");
suite.appendOnlySuite(nested);
- expect(suite.hasOnly(), 'to be', true);
+ expect(suite.hasOnly(), "to be", true);
});
- it('should return true if nested suite has `only`', function () {
- const suite = new Suite('foo');
- const nested = new Suite('bar');
- const test = new Test('baz');
+ it("should return true if nested suite has `only`", function () {
+ const suite = new Suite("foo");
+ const nested = new Suite("bar");
+ const test = new Test("baz");
nested.appendOnlyTest(test);
// `nested` has a `only` test, but `suite` doesn't know about it
suite.suites.push(nested);
- expect(suite.hasOnly(), 'to be', true);
+ expect(suite.hasOnly(), "to be", true);
});
- it('should return false if no suite or test is marked `only`', function () {
- const suite = new Suite('foo');
- const nested = new Suite('bar');
- const test = new Test('baz');
+ it("should return false if no suite or test is marked `only`", function () {
+ const suite = new Suite("foo");
+ const nested = new Suite("bar");
+ const test = new Test("baz");
suite.suites.push(nested);
nested.tests.push(test);
- expect(suite.hasOnly(), 'to be', false);
+ expect(suite.hasOnly(), "to be", false);
});
});
- describe('filterOnly()', function () {
- it('should filter out all other tests and suites if a test has `only`', function () {
- const suite = new Suite('a');
- const nested = new Suite('b');
- const test = new Test('c');
- const test2 = new Test('d');
+ describe("filterOnly()", function () {
+ it("should filter out all other tests and suites if a test has `only`", function () {
+ const suite = new Suite("a");
+ const nested = new Suite("b");
+ const test = new Test("c");
+ const test2 = new Test("d");
suite.suites.push(nested);
suite.appendOnlyTest(test);
@@ -614,20 +614,20 @@ describe('Suite', function () {
suite.filterOnly();
- expect(suite, 'to satisfy', {
- suites: expect.it('to be empty'),
+ expect(suite, "to satisfy", {
+ suites: expect.it("to be empty"),
tests: expect
- .it('to have length', 1)
- .and('to have an item satisfying', {title: 'c'})
+ .it("to have length", 1)
+ .and("to have an item satisfying", { title: "c" }),
});
});
- it('should filter out all other tests and suites if a suite has `only`', function () {
- const suite = new Suite('a');
- const nested1 = new Suite('b');
- const nested2 = new Suite('c');
- const test = new Test('d');
- const nestedTest = new Test('e');
+ it("should filter out all other tests and suites if a suite has `only`", function () {
+ const suite = new Suite("a");
+ const nested1 = new Suite("b");
+ const nested2 = new Suite("c");
+ const test = new Test("d");
+ const nestedTest = new Test("e");
nested1.appendOnlyTest(nestedTest);
@@ -638,48 +638,48 @@ describe('Suite', function () {
suite.filterOnly();
- expect(suite, 'to satisfy', {
+ expect(suite, "to satisfy", {
suites: expect
- .it('to have length', 1)
- .and('to have an item satisfying', {title: 'b'}),
- tests: expect.it('to be empty')
+ .it("to have length", 1)
+ .and("to have an item satisfying", { title: "b" }),
+ tests: expect.it("to be empty"),
});
});
});
- describe('markOnly()', function () {
- it('should call appendOnlySuite on parent', function () {
- const suite = new Suite('foo');
+ describe("markOnly()", function () {
+ it("should call appendOnlySuite on parent", function () {
+ const suite = new Suite("foo");
const spy = sinon.spy();
suite.parent = {
- appendOnlySuite: spy
+ appendOnlySuite: spy,
};
suite.markOnly();
- expect(spy, 'to have a call exhaustively satisfying', [suite]).and(
- 'was called once'
+ expect(spy, "to have a call exhaustively satisfying", [suite]).and(
+ "was called once",
);
});
});
});
});
-describe('Test', function () {
- describe('initialization', function () {
+describe("Test", function () {
+ describe("initialization", function () {
it("should throw an error if the title isn't a string", function () {
expect(function () {
new Test(function () {});
- }, 'to throw');
+ }, "to throw");
expect(() => {
new Test(undefined, function () {});
- }, 'to throw');
+ }, "to throw");
});
- it('should not throw if the title is a string', function () {
+ it("should not throw if the title is a string", function () {
expect(function () {
- new Test('test-case', function () {});
- }, 'not to throw');
+ new Test("test-case", function () {});
+ }, "not to throw");
});
});
});
diff --git a/test/unit/test.spec.js b/test/unit/test.spec.js
index 8bd394cc..c6a67708 100644
--- a/test/unit/test.spec.js
+++ b/test/unit/test.spec.js
@@ -1,123 +1,123 @@
-'use strict';
+"use strict";
-var sinon = require('sinon');
-var mocha = require('../../lib/mocha');
+var sinon = require("sinon");
+var mocha = require("../../lib/mocha");
var Test = mocha.Test;
var Runnable = mocha.Runnable;
-describe('Test', function () {
+describe("Test", function () {
afterEach(function () {
sinon.restore();
});
- describe('.clone()', function () {
+ describe(".clone()", function () {
beforeEach(function () {
- this._test = new Test('To be cloned', function () {});
+ this._test = new Test("To be cloned", function () {});
this._test._timeout = 3043;
this._test._slow = 101;
this._test._retries = 3;
this._test._currentRetry = 1;
- this._test._allowedGlobals = ['foo'];
- this._test.parent = 'foo';
- this._test.file = 'bar';
+ this._test._allowedGlobals = ["foo"];
+ this._test.parent = "foo";
+ this._test.file = "bar";
});
- it('should copy the title', function () {
- expect(this._test.clone().title, 'to be', 'To be cloned');
+ it("should copy the title", function () {
+ expect(this._test.clone().title, "to be", "To be cloned");
});
- it('should copy the timeout value', function () {
- expect(this._test.clone().timeout(), 'to be', 3043);
+ it("should copy the timeout value", function () {
+ expect(this._test.clone().timeout(), "to be", 3043);
});
- it('should copy the slow value', function () {
- expect(this._test.clone().slow(), 'to be', 101);
+ it("should copy the slow value", function () {
+ expect(this._test.clone().slow(), "to be", 101);
});
- it('should copy the retries value', function () {
- expect(this._test.clone().retries(), 'to be', 3);
+ it("should copy the retries value", function () {
+ expect(this._test.clone().retries(), "to be", 3);
});
- it('should copy the currentRetry value', function () {
- expect(this._test.clone().currentRetry(), 'to be', 1);
+ it("should copy the currentRetry value", function () {
+ expect(this._test.clone().currentRetry(), "to be", 1);
});
- it('should add/keep the retriedTest value', function () {
+ it("should add/keep the retriedTest value", function () {
var clone1 = this._test.clone();
- expect(clone1.retriedTest(), 'to be', this._test);
- expect(clone1.clone().retriedTest(), 'to be', this._test);
+ expect(clone1.retriedTest(), "to be", this._test);
+ expect(clone1.clone().retriedTest(), "to be", this._test);
});
- it('should copy the globals value', function () {
- expect(this._test.clone().globals(), 'not to be empty');
+ it("should copy the globals value", function () {
+ expect(this._test.clone().globals(), "not to be empty");
});
- it('should copy the parent value', function () {
- expect(this._test.clone().parent, 'to be', 'foo');
+ it("should copy the parent value", function () {
+ expect(this._test.clone().parent, "to be", "foo");
});
- it('should copy the file value', function () {
- expect(this._test.clone().file, 'to be', 'bar');
+ it("should copy the file value", function () {
+ expect(this._test.clone().file, "to be", "bar");
});
});
- describe('.reset()', function () {
+ describe(".reset()", function () {
beforeEach(function () {
- this._test = new Test('Test to be reset', function () {});
+ this._test = new Test("Test to be reset", function () {});
});
- it('should reset the run state', function () {
+ it("should reset the run state", function () {
this._test.pending = true;
this._test.reset();
- expect(this._test.pending, 'to be', false);
+ expect(this._test.pending, "to be", false);
});
- it('should call Runnable.reset', function () {
- var runnableResetStub = sinon.stub(Runnable.prototype, 'reset');
+ it("should call Runnable.reset", function () {
+ var runnableResetStub = sinon.stub(Runnable.prototype, "reset");
this._test.reset();
- expect(runnableResetStub, 'was called once');
+ expect(runnableResetStub, "was called once");
});
});
- describe('.isPending()', function () {
+ describe(".isPending()", function () {
beforeEach(function () {
- this._test = new Test('Is it skipped', function () {});
+ this._test = new Test("Is it skipped", function () {});
});
- it('should not be pending by default', function () {
- expect(this._test.isPending(), 'not to be', true);
+ it("should not be pending by default", function () {
+ expect(this._test.isPending(), "not to be", true);
});
- it('should be pending when marked as such', function () {
+ it("should be pending when marked as such", function () {
this._test.pending = true;
- expect(this._test.isPending(), 'to be', true);
+ expect(this._test.isPending(), "to be", true);
});
- it('should be pending when its parent is pending', function () {
+ it("should be pending when its parent is pending", function () {
this._test.parent = {
isPending: function () {
return true;
- }
+ },
};
- expect(this._test.isPending(), 'to be', true);
+ expect(this._test.isPending(), "to be", true);
});
});
- describe('.markOnly()', function () {
+ describe(".markOnly()", function () {
afterEach(function () {
sinon.restore();
});
- it('should call appendOnlyTest on parent', function () {
- var test = new Test('foo');
+ it("should call appendOnlyTest on parent", function () {
+ var test = new Test("foo");
var spy = sinon.spy();
test.parent = {
- appendOnlyTest: spy
+ appendOnlyTest: spy,
};
test.markOnly();
- expect(spy, 'to have a call exhaustively satisfying', [test]).and(
- 'was called once'
+ expect(spy, "to have a call exhaustively satisfying", [test]).and(
+ "was called once",
);
});
});
diff --git a/test/unit/throw.spec.js b/test/unit/throw.spec.js
index 464673aa..429f7337 100644
--- a/test/unit/throw.spec.js
+++ b/test/unit/throw.spec.js
@@ -1,9 +1,9 @@
-'use strict';
+"use strict";
/* eslint no-throw-literal: off */
-var sinon = require('sinon');
-var Mocha = require('../../lib/mocha');
+var sinon = require("sinon");
+var Mocha = require("../../lib/mocha");
var Suite = Mocha.Suite;
var Test = Mocha.Test;
var Runnable = Mocha.Runnable;
@@ -11,105 +11,105 @@ var Runner = Mocha.Runner;
var EVENT_RUN_END = Runner.constants.EVENT_RUN_END;
var STATE_FAILED = Runnable.constants.STATE_FAILED;
-describe('a test that throws', function () {
+describe("a test that throws", function () {
var suite;
var runner;
var uncaughtHandlers;
beforeEach(function () {
- suite = new Suite('Suite', 'root');
+ suite = new Suite("Suite", "root");
runner = new Runner(suite);
// see https://github.com/mochajs/mocha/pull/2983#issuecomment-350428522
- uncaughtHandlers = process.listeners('uncaughtException') || [];
- process.removeAllListeners('uncaughtException');
+ uncaughtHandlers = process.listeners("uncaughtException") || [];
+ process.removeAllListeners("uncaughtException");
});
afterEach(function () {
- process.removeAllListeners('uncaughtException');
+ process.removeAllListeners("uncaughtException");
uncaughtHandlers.forEach(function (listener) {
- process.on('uncaughtException', listener);
+ process.on("uncaughtException", listener);
});
sinon.restore();
});
- describe('non-extensible', function () {
- it('should not pass if throwing sync and test is sync', function (done) {
- var test = new Test('im sync and throw string sync', function () {
- throw 'non-extensible';
+ describe("non-extensible", function () {
+ it("should not pass if throwing sync and test is sync", function (done) {
+ var test = new Test("im sync and throw string sync", function () {
+ throw "non-extensible";
});
suite.addTest(test);
runner = new Runner(suite);
runner.on(EVENT_RUN_END, function () {
- expect(runner.failures, 'to be', 1);
- expect(test.state, 'to be', STATE_FAILED);
+ expect(runner.failures, "to be", 1);
+ expect(test.state, "to be", STATE_FAILED);
done();
});
runner.run();
});
- it('should not pass if throwing sync and test is async', function (done) {
- var test = new Test('im async and throw string sync', function () {
- throw 'non-extensible';
+ it("should not pass if throwing sync and test is async", function (done) {
+ var test = new Test("im async and throw string sync", function () {
+ throw "non-extensible";
});
suite.addTest(test);
runner = new Runner(suite);
runner.on(EVENT_RUN_END, function () {
- expect(runner.failures, 'to be', 1);
- expect(test.state, 'to be', STATE_FAILED);
+ expect(runner.failures, "to be", 1);
+ expect(test.state, "to be", STATE_FAILED);
done();
});
runner.run();
});
- it('should not pass if throwing async and test is async', function (done) {
- var test = new Test('im async and throw string async', function () {
+ it("should not pass if throwing async and test is async", function (done) {
+ var test = new Test("im async and throw string async", function () {
process.nextTick(function () {
- throw 'non-extensible';
+ throw "non-extensible";
});
});
suite.addTest(test);
runner = new Runner(suite);
runner.on(EVENT_RUN_END, function () {
- expect(runner.failures, 'to be', 1);
- expect(test.state, 'to be', STATE_FAILED);
+ expect(runner.failures, "to be", 1);
+ expect(test.state, "to be", STATE_FAILED);
done();
});
runner.run();
});
});
- describe('undefined', function () {
- it('should not pass if throwing sync and test is sync', function (done) {
- var test = new Test('im sync and throw undefined sync', function () {
+ describe("undefined", function () {
+ it("should not pass if throwing sync and test is sync", function (done) {
+ var test = new Test("im sync and throw undefined sync", function () {
throw undefined;
});
suite.addTest(test);
runner = new Runner(suite);
runner.on(EVENT_RUN_END, function () {
- expect(runner.failures, 'to be', 1);
- expect(test.state, 'to be', STATE_FAILED);
+ expect(runner.failures, "to be", 1);
+ expect(test.state, "to be", STATE_FAILED);
done();
});
runner.run();
});
- it('should not pass if throwing sync and test is async', function (done) {
- var test = new Test('im async and throw undefined sync', function () {
+ it("should not pass if throwing sync and test is async", function (done) {
+ var test = new Test("im async and throw undefined sync", function () {
throw undefined;
});
suite.addTest(test);
runner = new Runner(suite);
runner.on(EVENT_RUN_END, function () {
- expect(runner.failures, 'to be', 1);
- expect(test.state, 'to be', STATE_FAILED);
+ expect(runner.failures, "to be", 1);
+ expect(test.state, "to be", STATE_FAILED);
done();
});
runner.run();
});
- it('should not pass if throwing async and test is async', function (done) {
- var test = new Test('im async and throw undefined async', function () {
+ it("should not pass if throwing async and test is async", function (done) {
+ var test = new Test("im async and throw undefined async", function () {
process.nextTick(function () {
throw undefined;
});
@@ -117,45 +117,45 @@ describe('a test that throws', function () {
suite.addTest(test);
runner = new Runner(suite);
runner.on(EVENT_RUN_END, function () {
- expect(runner.failures, 'to be', 1);
- expect(test.state, 'to be', STATE_FAILED);
+ expect(runner.failures, "to be", 1);
+ expect(test.state, "to be", STATE_FAILED);
done();
});
runner.run();
});
});
- describe('null', function () {
- it('should not pass if throwing sync and test is sync', function (done) {
- var test = new Test('im sync and throw null sync', function () {
+ describe("null", function () {
+ it("should not pass if throwing sync and test is sync", function (done) {
+ var test = new Test("im sync and throw null sync", function () {
throw null;
});
suite.addTest(test);
runner = new Runner(suite);
runner.on(EVENT_RUN_END, function () {
- expect(runner.failures, 'to be', 1);
- expect(test.state, 'to be', STATE_FAILED);
+ expect(runner.failures, "to be", 1);
+ expect(test.state, "to be", STATE_FAILED);
done();
});
runner.run();
});
- it('should not pass if throwing sync and test is async', function (done) {
- var test = new Test('im async and throw null sync', function () {
+ it("should not pass if throwing sync and test is async", function (done) {
+ var test = new Test("im async and throw null sync", function () {
throw null;
});
suite.addTest(test);
runner = new Runner(suite);
runner.on(EVENT_RUN_END, function () {
- expect(runner.failures, 'to be', 1);
- expect(test.state, 'to be', STATE_FAILED);
+ expect(runner.failures, "to be", 1);
+ expect(test.state, "to be", STATE_FAILED);
done();
});
runner.run();
});
- it('should not pass if throwing async and test is async', function (done) {
- var test = new Test('im async and throw null async', function () {
+ it("should not pass if throwing async and test is async", function (done) {
+ var test = new Test("im async and throw null async", function () {
process.nextTick(function () {
throw null;
});
@@ -163,35 +163,35 @@ describe('a test that throws', function () {
suite.addTest(test);
runner = new Runner(suite);
runner.on(EVENT_RUN_END, function () {
- expect(runner.failures, 'to be', 1);
- expect(test.state, 'to be', STATE_FAILED);
+ expect(runner.failures, "to be", 1);
+ expect(test.state, "to be", STATE_FAILED);
done();
});
runner.run();
});
});
- describe('stack', function () {
- it('should include the stack when throwing async', function (done) {
- var test = new Test('im async and throw null async', function () {
+ describe("stack", function () {
+ it("should include the stack when throwing async", function (done) {
+ var test = new Test("im async and throw null async", function () {
process.nextTick(function throwError() {
- throw new Error('test error');
+ throw new Error("test error");
});
});
suite.addTest(test);
runner = new Runner(suite);
- sinon.stub(runner, 'fail');
+ sinon.stub(runner, "fail");
runner.on(EVENT_RUN_END, function () {
try {
- expect(runner.fail, 'to have all calls satisfying', [
- expect.it('to be a', Runnable),
- expect.it('to be an', Error).and('to satisfy', {
+ expect(runner.fail, "to have all calls satisfying", [
+ expect.it("to be a", Runnable),
+ expect.it("to be an", Error).and("to satisfy", {
message: /test error/i,
stack: /throwError/i,
- uncaught: true
- })
- ]).and('was called once');
+ uncaught: true,
+ }),
+ ]).and("was called once");
} catch (err) {
return done(err);
}
diff --git a/test/unit/timeout.spec.js b/test/unit/timeout.spec.js
index bb758a5e..dbf6a379 100644
--- a/test/unit/timeout.spec.js
+++ b/test/unit/timeout.spec.js
@@ -1,55 +1,55 @@
-'use strict';
+"use strict";
-describe('timeouts', function () {
+describe("timeouts", function () {
beforeEach(function (done) {
// uncomment
// setTimeout(done, 3000);
done();
});
- it('should error on timeout', function (done) {
+ it("should error on timeout", function (done) {
// uncomment
// setTimeout(done, 3000);
done();
});
- it('should allow overriding per-test', function (done) {
+ it("should allow overriding per-test", function (done) {
this.timeout(1500);
setTimeout(function () {
done();
}, 50);
});
- describe('disabling', function () {
- it('should work with timeout(0)', function (done) {
+ describe("disabling", function () {
+ it("should work with timeout(0)", function (done) {
this.timeout(0);
setTimeout(done, 1);
});
- describe('using beforeEach', function () {
+ describe("using beforeEach", function () {
beforeEach(function () {
this.timeout(0);
});
- it('should work with timeout(0)', function (done) {
+ it("should work with timeout(0)", function (done) {
setTimeout(done, 1);
});
});
- describe('using before', function () {
+ describe("using before", function () {
before(function () {
this.timeout(0);
});
- it('should work with timeout(0)', function (done) {
+ it("should work with timeout(0)", function (done) {
setTimeout(done, 1);
});
});
- describe('using timeout(0)', function () {
+ describe("using timeout(0)", function () {
this.timeout(4);
- it('should suppress timeout(4)', function (done) {
+ it("should suppress timeout(4)", function (done) {
this.slow(100);
// The test is in the before() call.
this.timeout(0);
@@ -57,40 +57,40 @@ describe('timeouts', function () {
});
});
- describe('suite-level', function () {
+ describe("suite-level", function () {
this.timeout(0);
- it('should work with timeout(0)', function (done) {
+ it("should work with timeout(0)", function (done) {
setTimeout(done, 1);
});
- describe('nested suite', function () {
- it('should work with timeout(0)', function (done) {
+ describe("nested suite", function () {
+ it("should work with timeout(0)", function (done) {
setTimeout(done, 1);
});
});
});
- describe('chaining calls', function () {
+ describe("chaining calls", function () {
before(function (done) {
setTimeout(function () {
done();
}, 50);
}).timeout(1500);
- it('should allow overriding via chaining', function (done) {
+ it("should allow overriding via chaining", function (done) {
setTimeout(function () {
done();
}, 50);
}).timeout(1500);
- describe('suite-level', function () {
- it('should work with timeout(0)', function (done) {
+ describe("suite-level", function () {
+ it("should work with timeout(0)", function (done) {
setTimeout(done, 1);
});
- describe('nested suite', function () {
- it('should work with timeout(0)', function (done) {
+ describe("nested suite", function () {
+ it("should work with timeout(0)", function (done) {
setTimeout(done, 1);
});
});
diff --git a/test/unit/utils.spec.js b/test/unit/utils.spec.js
index 0e54bf39..2a7356b5 100644
--- a/test/unit/utils.spec.js
+++ b/test/unit/utils.spec.js
@@ -1,222 +1,222 @@
/* global BigInt */
-'use strict';
+"use strict";
-var utils = require('../../lib/utils');
-var sinon = require('sinon');
+var utils = require("../../lib/utils");
+var sinon = require("sinon");
-describe('lib/utils', function () {
+describe("lib/utils", function () {
afterEach(function () {
sinon.restore();
});
- describe('clean()', function () {
- it('should remove the wrapping function declaration', function () {
+ describe("clean()", function () {
+ it("should remove the wrapping function declaration", function () {
expect(
- utils.clean('function (one, two, three) {\n//code\n}'),
- 'to be',
- '//code'
+ utils.clean("function (one, two, three) {\n//code\n}"),
+ "to be",
+ "//code",
);
});
- it('should handle newlines in the function declaration', function () {
+ it("should handle newlines in the function declaration", function () {
expect(
- utils.clean('function (one, two, three)\n {\n//code\n}'),
- 'to be',
- '//code'
+ utils.clean("function (one, two, three)\n {\n//code\n}"),
+ "to be",
+ "//code",
);
});
- it('should remove space character indentation from the function body', function () {
+ it("should remove space character indentation from the function body", function () {
expect(
- utils.clean(' //line1\n //line2'),
- 'to be',
- '//line1\n //line2'
+ utils.clean(" //line1\n //line2"),
+ "to be",
+ "//line1\n //line2",
);
});
- it('should remove tab character indentation from the function body', function () {
+ it("should remove tab character indentation from the function body", function () {
expect(
- utils.clean('\t//line1\n\t\t//line2'),
- 'to be',
- '//line1\n\t//line2'
+ utils.clean("\t//line1\n\t\t//line2"),
+ "to be",
+ "//line1\n\t//line2",
);
});
- it('should handle functions with tabs in their declarations', function () {
- expect(utils.clean('function\t(\t)\t{\n//code\n}'), 'to be', '//code');
+ it("should handle functions with tabs in their declarations", function () {
+ expect(utils.clean("function\t(\t)\t{\n//code\n}"), "to be", "//code");
});
- it('should handle named functions without space after name', function () {
+ it("should handle named functions without space after name", function () {
expect(
- utils.clean('function withName() {\n//code\n}'),
- 'to be',
- '//code'
+ utils.clean("function withName() {\n//code\n}"),
+ "to be",
+ "//code",
);
});
- it('should handle named functions with space after name', function () {
+ it("should handle named functions with space after name", function () {
expect(
- utils.clean('function withName () {\n//code\n}'),
- 'to be',
- '//code'
+ utils.clean("function withName () {\n//code\n}"),
+ "to be",
+ "//code",
);
});
- it('should handle functions with no space between the end and the closing brace', function () {
- expect(utils.clean('function() {/*code*/}'), 'to be', '/*code*/');
+ it("should handle functions with no space between the end and the closing brace", function () {
+ expect(utils.clean("function() {/*code*/}"), "to be", "/*code*/");
});
- it('should handle functions with parentheses in the same line', function () {
+ it("should handle functions with parentheses in the same line", function () {
expect(
- utils.clean('function() { if (true) { /* code */ } }'),
- 'to be',
- 'if (true) { /* code */ }'
+ utils.clean("function() { if (true) { /* code */ } }"),
+ "to be",
+ "if (true) { /* code */ }",
);
});
- it('should handle empty functions', function () {
- expect(utils.clean('function() {}'), 'to be', '');
+ it("should handle empty functions", function () {
+ expect(utils.clean("function() {}"), "to be", "");
});
- it('should format a single line test function', function () {
- var fn = ['function () {', ' var a = 1;', '}'].join('\n');
- expect(utils.clean(fn), 'to be', 'var a = 1;');
+ it("should format a single line test function", function () {
+ var fn = ["function () {", " var a = 1;", "}"].join("\n");
+ expect(utils.clean(fn), "to be", "var a = 1;");
});
- it('should format a multi line test indented with spaces', function () {
+ it("should format a multi line test indented with spaces", function () {
// and no new lines after curly braces, shouldn't matter
var fn = [
- 'function(){ var a = 1;',
+ "function(){ var a = 1;",
// this one has more spaces
- ' var b = 2;',
- ' var c = 3; }'
- ].join('\n');
- expect(utils.clean(fn), 'to be', 'var a = 1;\n var b = 2;\nvar c = 3;');
+ " var b = 2;",
+ " var c = 3; }",
+ ].join("\n");
+ expect(utils.clean(fn), "to be", "var a = 1;\n var b = 2;\nvar c = 3;");
});
- it('should format a multi line test indented with tabs', function () {
+ it("should format a multi line test indented with tabs", function () {
var fn = [
- 'function (arg1, arg2) {',
- '\tif (true) {',
- '\t\tvar a = 1;',
- '\t}',
- '}'
- ].join('\n');
- expect(utils.clean(fn), 'to be', 'if (true) {\n\tvar a = 1;\n}');
+ "function (arg1, arg2) {",
+ "\tif (true) {",
+ "\t\tvar a = 1;",
+ "\t}",
+ "}",
+ ].join("\n");
+ expect(utils.clean(fn), "to be", "if (true) {\n\tvar a = 1;\n}");
});
- it('should format functions saved in windows style - spaces', function () {
+ it("should format functions saved in windows style - spaces", function () {
var fn = [
- 'function (one) {',
- ' do {',
+ "function (one) {",
+ " do {",
' "nothing";',
- ' } while (false);',
- ' }'
- ].join('\r\n');
- expect(utils.clean(fn), 'to be', 'do {\n "nothing";\n} while (false);');
+ " } while (false);",
+ " }",
+ ].join("\r\n");
+ expect(utils.clean(fn), "to be", 'do {\n "nothing";\n} while (false);');
});
- it('should format functions saved in windows style - tabs', function () {
+ it("should format functions saved in windows style - tabs", function () {
var fn = [
- 'function ( ) {',
- '\tif (false) {',
- '\t\tvar json = {',
- '\t\t\tone : 1',
- '\t\t};',
- '\t}',
- '}'
- ].join('\r\n');
+ "function ( ) {",
+ "\tif (false) {",
+ "\t\tvar json = {",
+ "\t\t\tone : 1",
+ "\t\t};",
+ "\t}",
+ "}",
+ ].join("\r\n");
expect(
utils.clean(fn),
- 'to be',
- 'if (false) {\n\tvar json = {\n\t\tone : 1\n\t};\n}'
+ "to be",
+ "if (false) {\n\tvar json = {\n\t\tone : 1\n\t};\n}",
);
});
- it('should format es6 arrow functions', function () {
- var fn = ['() => {', ' var a = 1;', '}'].join('\n');
- expect(utils.clean(fn), 'to be', 'var a = 1;');
+ it("should format es6 arrow functions", function () {
+ var fn = ["() => {", " var a = 1;", "}"].join("\n");
+ expect(utils.clean(fn), "to be", "var a = 1;");
});
- it('should format es6 arrow functions with implicit return', function () {
- var fn = '() => foo()';
- expect(utils.clean(fn), 'to be', 'foo()');
+ it("should format es6 arrow functions with implicit return", function () {
+ var fn = "() => foo()";
+ expect(utils.clean(fn), "to be", "foo()");
});
});
- describe('stringify()', function () {
+ describe("stringify()", function () {
var stringify = utils.stringify;
- it('should return an object representation of a string created with a String constructor', function () {
+ it("should return an object representation of a string created with a String constructor", function () {
/* eslint no-new-wrappers: off */
expect(
- stringify(new String('foo')),
- 'to be',
- '{\n "0": "f"\n "1": "o"\n "2": "o"\n}'
+ stringify(new String("foo")),
+ "to be",
+ '{\n "0": "f"\n "1": "o"\n "2": "o"\n}',
);
});
- it('should return Buffer with .toJSON representation', function () {
- expect(stringify(Buffer.from([0x01])), 'to be', '[\n 1\n]');
- expect(stringify(Buffer.from([0x01, 0x02])), 'to be', '[\n 1\n 2\n]');
+ it("should return Buffer with .toJSON representation", function () {
+ expect(stringify(Buffer.from([0x01])), "to be", "[\n 1\n]");
+ expect(stringify(Buffer.from([0x01, 0x02])), "to be", "[\n 1\n 2\n]");
expect(
- stringify(Buffer.from('ABCD')),
- 'to be',
- '[\n 65\n 66\n 67\n 68\n]'
+ stringify(Buffer.from("ABCD")),
+ "to be",
+ "[\n 65\n 66\n 67\n 68\n]",
);
});
- it('should return Date object with .toISOString() + string prefix', function () {
+ it("should return Date object with .toISOString() + string prefix", function () {
expect(
stringify(new Date(0)),
- 'to be',
- '[Date: ' + new Date(0).toISOString() + ']'
+ "to be",
+ "[Date: " + new Date(0).toISOString() + "]",
);
var date = new Date(); // now
- expect(stringify(date), 'to be', '[Date: ' + date.toISOString() + ']');
+ expect(stringify(date), "to be", "[Date: " + date.toISOString() + "]");
});
- it('should return invalid Date object with .toString() + string prefix', function () {
+ it("should return invalid Date object with .toString() + string prefix", function () {
expect(
- stringify(new Date('')),
- 'to be',
- '[Date: ' + new Date('').toString() + ']'
+ stringify(new Date("")),
+ "to be",
+ "[Date: " + new Date("").toString() + "]",
);
});
- describe('#Number', function () {
- it('should show the handle -0 situations', function () {
- expect(stringify(-0), 'to be', '-0');
- expect(stringify(0), 'to be', '0');
- expect(stringify('-0'), 'to be', '"-0"');
+ describe("#Number", function () {
+ it("should show the handle -0 situations", function () {
+ expect(stringify(-0), "to be", "-0");
+ expect(stringify(0), "to be", "0");
+ expect(stringify("-0"), "to be", '"-0"');
});
- it('should work well with `NaN` and `Infinity`', function () {
- expect(stringify(NaN), 'to be', 'NaN');
- expect(stringify(Infinity), 'to be', 'Infinity');
- expect(stringify(-Infinity), 'to be', '-Infinity');
+ it("should work well with `NaN` and `Infinity`", function () {
+ expect(stringify(NaN), "to be", "NaN");
+ expect(stringify(Infinity), "to be", "Infinity");
+ expect(stringify(-Infinity), "to be", "-Infinity");
});
- it('floats and ints', function () {
- expect(stringify(1), 'to be', '1');
- expect(stringify(1.2), 'to be', '1.2');
- expect(stringify(1e9), 'to be', '1000000000');
+ it("floats and ints", function () {
+ expect(stringify(1), "to be", "1");
+ expect(stringify(1.2), "to be", "1.2");
+ expect(stringify(1e9), "to be", "1000000000");
});
- if (typeof BigInt === 'function') {
- it('should work with bigints when possible', function () {
- expect(stringify(BigInt(1)), 'to be', '1n');
- expect(stringify(BigInt(2)), 'to be', '2n');
+ if (typeof BigInt === "function") {
+ it("should work with bigints when possible", function () {
+ expect(stringify(BigInt(1)), "to be", "1n");
+ expect(stringify(BigInt(2)), "to be", "2n");
});
}
});
- describe('canonicalize example', function () {
- it('should represent the actual full result', function () {
+ describe("canonicalize example", function () {
+ it("should represent the actual full result", function () {
var expected = {
- str: 'string',
+ str: "string",
int: 90,
float: 9.99,
boolean: false,
@@ -232,30 +232,30 @@ describe('lib/utils', function () {
array: [1, 2, 3],
empArr: [],
matrix: [[1], [2, 3, 4]],
- object: {a: 1, b: 2},
- canObj: {a: {b: 1, c: 2}, b: {}},
- empObj: {}
+ object: { a: 1, b: 2 },
+ canObj: { a: { b: 1, c: 2 }, b: {} },
+ empObj: {},
};
expected.circular = expected; // Make `Circular` situation
var actual = [
- '{',
+ "{",
' "array": [',
- ' 1',
- ' 2',
- ' 3',
- ' ]',
+ " 1",
+ " 2",
+ " 3",
+ " ]",
' "boolean": false',
' "buffer": [Buffer: [',
- ' 1',
- ' 2',
- ' ]]',
+ " 1",
+ " 2",
+ " ]]",
' "canObj": {',
' "a": {',
' "b": 1',
' "c": 2',
- ' }',
+ " }",
' "b": {}',
- ' }',
+ " }",
' "circular": [Circular]',
' "date": [Date: 1970-01-01T00:00:00.000Z]',
' "empArr": []',
@@ -265,268 +265,268 @@ describe('lib/utils', function () {
' "infi": Infinity',
' "int": 90',
' "matrix": [',
- ' [',
- ' 1',
- ' ]',
- ' [',
- ' 2',
- ' 3',
- ' 4',
- ' ]',
- ' ]',
+ " [",
+ " 1",
+ " ]",
+ " [",
+ " 2",
+ " 3",
+ " 4",
+ " ]",
+ " ]",
' "nan": NaN',
' "nil": [null]',
' "object": {',
' "a": 1',
' "b": 2',
- ' }',
+ " }",
' "regex": /^[a-z|A-Z]/',
' "str": "string"',
' "undef": [undefined]',
' "zero": -0',
- '}'
- ].join('\n');
- expect(stringify(expected), 'to be', actual);
+ "}",
+ ].join("\n");
+ expect(stringify(expected), "to be", actual);
});
- describe('should represent null prototypes', function () {
- it('With explicit names', function () {
+ describe("should represent null prototypes", function () {
+ it("With explicit names", function () {
const foo = Object.create(null, {
- [Symbol.toStringTag]: {value: 'Foo'},
- bing: {get: () => 'bong', enumerable: true}
+ [Symbol.toStringTag]: { value: "Foo" },
+ bing: { get: () => "bong", enumerable: true },
});
const expected = [
- '{',
+ "{",
' "[Symbol.toStringTag]": "Foo"',
' "bing": "bong"',
- '}'
- ].join('\n');
+ "}",
+ ].join("\n");
- expect(stringify(foo), 'to be', expected);
+ expect(stringify(foo), "to be", expected);
});
- it('Without names', function () {
+ it("Without names", function () {
const unnamed = {
- bing: 'bong',
- abc: 123
+ bing: "bong",
+ abc: 123,
};
unnamed.self = unnamed;
const expected = [
- '{',
+ "{",
' "abc": 123',
' "bing": "bong"',
' "self": [Circular]',
- '}'
- ].join('\n');
+ "}",
+ ].join("\n");
expect(
stringify(Object.setPrototypeOf(unnamed, null)),
- 'to be',
- expected
+ "to be",
+ expected,
);
});
});
});
- it('should canonicalize the object', function () {
- var travis = {name: 'travis', age: 24};
- var travis2 = {age: 24, name: 'travis'};
+ it("should canonicalize the object", function () {
+ var travis = { name: "travis", age: 24 };
+ var travis2 = { age: 24, name: "travis" };
- expect(stringify(travis), 'to be', stringify(travis2));
+ expect(stringify(travis), "to be", stringify(travis2));
});
- it('should handle circular structures in objects', function () {
- var travis = {name: 'travis'};
+ it("should handle circular structures in objects", function () {
+ var travis = { name: "travis" };
travis.whoami = travis;
expect(
stringify(travis),
- 'to be',
- '{\n "name": "travis"\n "whoami": [Circular]\n}'
+ "to be",
+ '{\n "name": "travis"\n "whoami": [Circular]\n}',
);
});
- it('should handle circular structures in arrays', function () {
- var travis = ['travis'];
+ it("should handle circular structures in arrays", function () {
+ var travis = ["travis"];
travis.push(travis);
- expect(stringify(travis), 'to be', '[\n "travis"\n [Circular]\n]');
+ expect(stringify(travis), "to be", '[\n "travis"\n [Circular]\n]');
});
- it('should handle circular structures in functions', function () {
+ it("should handle circular structures in functions", function () {
var travis = function () {};
travis.fn = travis;
- expect(stringify(travis), 'to be', '{\n "fn": [Circular]\n}');
+ expect(stringify(travis), "to be", '{\n "fn": [Circular]\n}');
});
- it('should handle various non-undefined, non-null, non-object, non-array, non-date, and non-function values', function () {
+ it("should handle various non-undefined, non-null, non-object, non-array, non-date, and non-function values", function () {
var regexp = /(?:)/;
- var regExpObj = {regexp};
- var regexpString = '/(?:)/';
+ var regExpObj = { regexp };
+ var regexpString = "/(?:)/";
expect(
stringify(regExpObj),
- 'to be',
- '{\n "regexp": ' + regexpString + '\n}'
+ "to be",
+ '{\n "regexp": ' + regexpString + "\n}",
);
- expect(stringify(regexp), 'to be', regexpString);
+ expect(stringify(regexp), "to be", regexpString);
var number = 1;
- var numberObj = {number};
- var numberString = '1';
+ var numberObj = { number };
+ var numberString = "1";
- expect(stringify(numberObj), 'to be', '{\n "number": ' + number + '\n}');
- expect(stringify(number), 'to be', numberString);
+ expect(stringify(numberObj), "to be", '{\n "number": ' + number + "\n}");
+ expect(stringify(number), "to be", numberString);
var boolean = false;
- var booleanObj = {boolean};
- var booleanString = 'false';
+ var booleanObj = { boolean };
+ var booleanString = "false";
expect(
stringify(booleanObj),
- 'to be',
- '{\n "boolean": ' + boolean + '\n}'
+ "to be",
+ '{\n "boolean": ' + boolean + "\n}",
);
- expect(stringify(boolean), 'to be', booleanString);
+ expect(stringify(boolean), "to be", booleanString);
- var string = 'sneepy';
- var stringObj = {string};
+ var string = "sneepy";
+ var stringObj = { string };
expect(
stringify(stringObj),
- 'to be',
- '{\n "string": "' + string + '"\n}'
+ "to be",
+ '{\n "string": "' + string + '"\n}',
);
- expect(stringify(string), 'to be', JSON.stringify(string));
+ expect(stringify(string), "to be", JSON.stringify(string));
var nullValue = null;
- var nullObj = {null: null};
- var nullString = '[null]';
+ var nullObj = { null: null };
+ var nullString = "[null]";
- expect(stringify(nullObj), 'to be', '{\n "null": [null]\n}');
- expect(stringify(nullValue), 'to be', nullString);
+ expect(stringify(nullObj), "to be", '{\n "null": [null]\n}');
+ expect(stringify(nullValue), "to be", nullString);
});
- it('should handle arrays', function () {
- var array = ['dave', 'dave', 'dave', 'dave'];
- var arrayObj = {array};
+ it("should handle arrays", function () {
+ var array = ["dave", "dave", "dave", "dave"];
+ var arrayObj = { array };
var arrayString = ' "dave"\n "dave"\n "dave"\n "dave"';
expect(
stringify(arrayObj),
- 'to be',
- '{\n "array": [\n' + arrayString + '\n ]\n}'
+ "to be",
+ '{\n "array": [\n' + arrayString + "\n ]\n}",
);
expect(
stringify(array),
- 'to be',
- '[' + arrayString.replace(/\s+/g, '\n ') + '\n]'
+ "to be",
+ "[" + arrayString.replace(/\s+/g, "\n ") + "\n]",
);
});
- it('should handle functions', function () {
+ it("should handle functions", function () {
var fn = function () {};
- var fnObj = {fn};
- var fnString = '[Function]';
+ var fnObj = { fn };
+ var fnString = "[Function]";
- expect(stringify(fnObj), 'to be', '{\n "fn": ' + fnString + '\n}');
- expect(stringify(fn), 'to be', '[Function]');
+ expect(stringify(fnObj), "to be", '{\n "fn": ' + fnString + "\n}");
+ expect(stringify(fn), "to be", "[Function]");
});
- it('should handle empty objects', function () {
- expect(stringify({}), 'to be', '{}');
- expect(stringify({foo: {}}), 'to be', '{\n "foo": {}\n}');
+ it("should handle empty objects", function () {
+ expect(stringify({}), "to be", "{}");
+ expect(stringify({ foo: {} }), "to be", '{\n "foo": {}\n}');
});
- it('should handle empty arrays', function () {
- expect(stringify([]), 'to be', '[]');
- expect(stringify({foo: []}), 'to be', '{\n "foo": []\n}');
+ it("should handle empty arrays", function () {
+ expect(stringify([]), "to be", "[]");
+ expect(stringify({ foo: [] }), "to be", '{\n "foo": []\n}');
});
- it('should handle non-empty arrays', function () {
- expect(stringify(['a', 'b', 'c']), 'to be', '[\n "a"\n "b"\n "c"\n]');
+ it("should handle non-empty arrays", function () {
+ expect(stringify(["a", "b", "c"]), "to be", '[\n "a"\n "b"\n "c"\n]');
});
- it('should handle empty functions (with no properties)', function () {
+ it("should handle empty functions (with no properties)", function () {
expect(
stringify(function () {}),
- 'to be',
- '[Function]'
+ "to be",
+ "[Function]",
);
expect(
- stringify({foo: function () {}}),
- 'to be',
- '{\n "foo": [Function]\n}'
+ stringify({ foo: function () {} }),
+ "to be",
+ '{\n "foo": [Function]\n}',
);
expect(
- stringify({foo: function () {}, bar: 'baz'}),
- 'to be',
- '{\n "bar": "baz"\n "foo": [Function]\n}'
+ stringify({ foo: function () {}, bar: "baz" }),
+ "to be",
+ '{\n "bar": "baz"\n "foo": [Function]\n}',
);
});
- it('should handle functions w/ properties', function () {
+ it("should handle functions w/ properties", function () {
var fn = function () {};
- fn.bar = 'baz';
- expect(stringify(fn), 'to be', '{\n "bar": "baz"\n}');
+ fn.bar = "baz";
+ expect(stringify(fn), "to be", '{\n "bar": "baz"\n}');
expect(
- stringify({foo: fn}),
- 'to be',
- '{\n "foo": {\n "bar": "baz"\n }\n}'
+ stringify({ foo: fn }),
+ "to be",
+ '{\n "foo": {\n "bar": "baz"\n }\n}',
);
});
- it('should handle undefined values', function () {
+ it("should handle undefined values", function () {
expect(
- stringify({foo: undefined}),
- 'to be',
- '{\n "foo": [undefined]\n}'
+ stringify({ foo: undefined }),
+ "to be",
+ '{\n "foo": [undefined]\n}',
);
expect(
- stringify({foo: 'bar', baz: undefined}),
- 'to be',
- '{\n "baz": [undefined]\n "foo": "bar"\n}'
+ stringify({ foo: "bar", baz: undefined }),
+ "to be",
+ '{\n "baz": [undefined]\n "foo": "bar"\n}',
);
- expect(stringify(), 'to be', '[undefined]');
+ expect(stringify(), "to be", "[undefined]");
});
- it('should recurse', function () {
+ it("should recurse", function () {
expect(
- stringify({foo: {bar: {baz: {quux: {herp: 'derp'}}}}}),
- 'to be',
- '{\n "foo": {\n "bar": {\n "baz": {\n "quux": {\n "herp": "derp"\n }\n }\n }\n }\n}'
+ stringify({ foo: { bar: { baz: { quux: { herp: "derp" } } } } }),
+ "to be",
+ '{\n "foo": {\n "bar": {\n "baz": {\n "quux": {\n "herp": "derp"\n }\n }\n }\n }\n}',
);
});
- it('might get confusing', function () {
- expect(stringify(null), 'to be', '[null]');
+ it("might get confusing", function () {
+ expect(stringify(null), "to be", "[null]");
});
- it('should not freak out if it sees a primitive twice', function () {
+ it("should not freak out if it sees a primitive twice", function () {
expect(
- stringify({foo: null, bar: null}),
- 'to be',
- '{\n "bar": [null]\n "foo": [null]\n}'
+ stringify({ foo: null, bar: null }),
+ "to be",
+ '{\n "bar": [null]\n "foo": [null]\n}',
);
expect(
- stringify({foo: 1, bar: 1}),
- 'to be',
- '{\n "bar": 1\n "foo": 1\n}'
+ stringify({ foo: 1, bar: 1 }),
+ "to be",
+ '{\n "bar": 1\n "foo": 1\n}',
);
});
- it('should stringify dates', function () {
+ it("should stringify dates", function () {
var date = new Date(0);
- expect(stringify(date), 'to be', '[Date: 1970-01-01T00:00:00.000Z]');
+ expect(stringify(date), "to be", "[Date: 1970-01-01T00:00:00.000Z]");
expect(
- stringify({date}),
- 'to be',
- '{\n "date": [Date: 1970-01-01T00:00:00.000Z]\n}'
+ stringify({ date }),
+ "to be",
+ '{\n "date": [Date: 1970-01-01T00:00:00.000Z]\n}',
);
});
- it('should handle object without an Object prototype', function () {
+ it("should handle object without an Object prototype", function () {
var a;
if (Object.create) {
a = Object.create(null);
@@ -535,33 +535,33 @@ describe('lib/utils', function () {
}
a.foo = 1;
- expect(stringify(a), 'to be', '{\n "foo": 1\n}');
+ expect(stringify(a), "to be", '{\n "foo": 1\n}');
});
// In old version node.js, Symbol is not available by default.
- if (typeof global.Symbol === 'function') {
- it('should handle Symbol', function () {
- var symbol = Symbol('value');
- expect(stringify(symbol), 'to match', /^Symbol\(value\)/);
- expect(stringify({symbol}), 'to match', /"symbol": Symbol\(value\)/);
+ if (typeof global.Symbol === "function") {
+ it("should handle Symbol", function () {
+ var symbol = Symbol("value");
+ expect(stringify(symbol), "to match", /^Symbol\(value\)/);
+ expect(stringify({ symbol }), "to match", /"symbol": Symbol\(value\)/);
});
}
- it('should handle length properties that cannot be coerced to a number', function () {
+ it("should handle length properties that cannot be coerced to a number", function () {
expect(
- stringify({length: {nonBuiltinProperty: 0}}),
- 'to be',
- '{\n "length": {\n "nonBuiltinProperty": 0\n }\n}'
+ stringify({ length: { nonBuiltinProperty: 0 } }),
+ "to be",
+ '{\n "length": {\n "nonBuiltinProperty": 0\n }\n}',
);
expect(
- stringify({length: 'a string where length should be'}),
- 'to be',
- '{\n "length": "a string where length should be"\n}'
+ stringify({ length: "a string where length should be" }),
+ "to be",
+ '{\n "length": "a string where length should be"\n}',
);
});
});
- describe('type()', function () {
+ describe("type()", function () {
/* eslint no-extend-native: off */
var type = utils.type;
@@ -571,42 +571,42 @@ describe('lib/utils', function () {
// some JS engines such as PhantomJS 1.x exhibit this behavior
Object.prototype.toString = function () {
if (this === global) {
- return '[object DOMWindow]';
+ return "[object DOMWindow]";
}
return toString.call(this);
};
});
- it('should recognize various types', function () {
- expect(type({}), 'to be', 'object');
- expect(type([]), 'to be', 'array');
- expect(type(1), 'to be', 'number');
- expect(type(Infinity), 'to be', 'number');
- expect(type(null), 'to be', 'null');
- expect(type(undefined), 'to be', 'undefined');
- expect(type(new Date()), 'to be', 'object');
- expect(type(/foo/), 'to be', 'object');
- expect(type('type'), 'to be', 'string');
- expect(type(new Error()), 'to be', 'error');
- expect(type(global), 'to be', 'object');
- expect(type(true), 'to be', 'boolean');
- expect(type(Buffer.from('ff', 'hex')), 'to be', 'object');
- expect(type(Symbol.iterator), 'to be', 'symbol');
- expect(type(new Map()), 'to be', 'object');
- expect(type(new WeakMap()), 'to be', 'object');
- expect(type(new Set()), 'to be', 'object');
- expect(type(new WeakSet()), 'to be', 'object');
+ it("should recognize various types", function () {
+ expect(type({}), "to be", "object");
+ expect(type([]), "to be", "array");
+ expect(type(1), "to be", "number");
+ expect(type(Infinity), "to be", "number");
+ expect(type(null), "to be", "null");
+ expect(type(undefined), "to be", "undefined");
+ expect(type(new Date()), "to be", "object");
+ expect(type(/foo/), "to be", "object");
+ expect(type("type"), "to be", "string");
+ expect(type(new Error()), "to be", "error");
+ expect(type(global), "to be", "object");
+ expect(type(true), "to be", "boolean");
+ expect(type(Buffer.from("ff", "hex")), "to be", "object");
+ expect(type(Symbol.iterator), "to be", "symbol");
+ expect(type(new Map()), "to be", "object");
+ expect(type(new WeakMap()), "to be", "object");
+ expect(type(new Set()), "to be", "object");
+ expect(type(new WeakSet()), "to be", "object");
expect(
type(async () => {}),
- 'to be',
- 'function'
+ "to be",
+ "function",
);
});
- describe('when toString on null or undefined stringifies window', function () {
- it('should recognize null and undefined', function () {
- expect(type(null), 'to be', 'null');
- expect(type(undefined), 'to be', 'undefined');
+ describe("when toString on null or undefined stringifies window", function () {
+ it("should recognize null and undefined", function () {
+ expect(type(null), "to be", "null");
+ expect(type(undefined), "to be", "undefined");
});
});
@@ -615,7 +615,7 @@ describe('lib/utils', function () {
});
});
- describe('canonicalType()', function () {
+ describe("canonicalType()", function () {
/* eslint no-extend-native: off */
var type = utils.canonicalType;
@@ -625,30 +625,30 @@ describe('lib/utils', function () {
// some JS engines such as PhantomJS 1.x exhibit this behavior
Object.prototype.toString = function () {
if (this === global) {
- return '[object DOMWindow]';
+ return "[object DOMWindow]";
}
return toString.call(this);
};
});
- it('should recognize various types', function () {
- expect(type({}), 'to be', 'object');
- expect(type([]), 'to be', 'array');
- expect(type(1), 'to be', 'number');
- expect(type(Infinity), 'to be', 'number');
- expect(type(null), 'to be', 'null');
- expect(type(undefined), 'to be', 'undefined');
- expect(type(new Date()), 'to be', 'date');
- expect(type(/foo/), 'to be', 'regexp');
- expect(type('type'), 'to be', 'string');
- expect(type(global), 'to be', 'domwindow');
- expect(type(true), 'to be', 'boolean');
- });
-
- describe('when toString on null or undefined stringifies window', function () {
- it('should recognize null and undefined', function () {
- expect(type(null), 'to be', 'null');
- expect(type(undefined), 'to be', 'undefined');
+ it("should recognize various types", function () {
+ expect(type({}), "to be", "object");
+ expect(type([]), "to be", "array");
+ expect(type(1), "to be", "number");
+ expect(type(Infinity), "to be", "number");
+ expect(type(null), "to be", "null");
+ expect(type(undefined), "to be", "undefined");
+ expect(type(new Date()), "to be", "date");
+ expect(type(/foo/), "to be", "regexp");
+ expect(type("type"), "to be", "string");
+ expect(type(global), "to be", "domwindow");
+ expect(type(true), "to be", "boolean");
+ });
+
+ describe("when toString on null or undefined stringifies window", function () {
+ it("should recognize null and undefined", function () {
+ expect(type(null), "to be", "null");
+ expect(type(undefined), "to be", "undefined");
});
});
@@ -657,149 +657,149 @@ describe('lib/utils', function () {
});
});
- describe('isPromise()', function () {
- it('should return true if the value is Promise-ish', function () {
+ describe("isPromise()", function () {
+ it("should return true if the value is Promise-ish", function () {
expect(
utils.isPromise({
- then: function () {}
+ then: function () {},
}),
- 'to be',
- true
+ "to be",
+ true,
);
});
- it('should return false if the value is not an object', function () {
- expect(utils.isPromise(1), 'to be', false);
+ it("should return false if the value is not an object", function () {
+ expect(utils.isPromise(1), "to be", false);
});
it('should return false if the value is an object w/o a "then" function', function () {
- expect(utils.isPromise({}), 'to be', false);
+ expect(utils.isPromise({}), "to be", false);
});
- it('should return false if the object is null', function () {
- expect(utils.isPromise(null), 'to be', false);
+ it("should return false if the object is null", function () {
+ expect(utils.isPromise(null), "to be", false);
});
});
- describe('escape()', function () {
- it('replaces the usual xml suspects', function () {
- expect(utils.escape('<a<bc<d<'), 'to be', '&#x3C;a&#x3C;bc&#x3C;d&#x3C;');
- expect(utils.escape('>a>bc>d>'), 'to be', '&#x3E;a&#x3E;bc&#x3E;d&#x3E;');
- expect(utils.escape('"a"bc"d"'), 'to be', '&#x22;a&#x22;bc&#x22;d&#x22;');
- expect(utils.escape('<>"&'), 'to be', '&#x3C;&#x3E;&#x22;&#x26;');
+ describe("escape()", function () {
+ it("replaces the usual xml suspects", function () {
+ expect(utils.escape("<a<bc<d<"), "to be", "&#x3C;a&#x3C;bc&#x3C;d&#x3C;");
+ expect(utils.escape(">a>bc>d>"), "to be", "&#x3E;a&#x3E;bc&#x3E;d&#x3E;");
+ expect(utils.escape('"a"bc"d"'), "to be", "&#x22;a&#x22;bc&#x22;d&#x22;");
+ expect(utils.escape('<>"&'), "to be", "&#x3C;&#x3E;&#x22;&#x26;");
- expect(utils.escape('&a&bc&d&'), 'to be', '&#x26;a&#x26;bc&#x26;d&#x26;');
- expect(utils.escape('&amp;&lt;'), 'to be', '&#x26;amp;&#x26;lt;');
+ expect(utils.escape("&a&bc&d&"), "to be", "&#x26;a&#x26;bc&#x26;d&#x26;");
+ expect(utils.escape("&amp;&lt;"), "to be", "&#x26;amp;&#x26;lt;");
});
- it('replaces invalid xml characters', function () {
+ it("replaces invalid xml characters", function () {
expect(
- utils.escape('\x1B[32mfoo\x1B[0m'),
- 'to be',
- '&#x1B;[32mfoo&#x1B;[0m'
+ utils.escape("\x1B[32mfoo\x1B[0m"),
+ "to be",
+ "&#x1B;[32mfoo&#x1B;[0m",
);
// Ensure we can handle non-trivial unicode characters as well
- expect(utils.escape('💩'), 'to be', '&#x1F4A9;');
+ expect(utils.escape("💩"), "to be", "&#x1F4A9;");
});
});
- describe('createMap()', function () {
- it('should return an object with a null prototype', function () {
- expect(Object.getPrototypeOf(utils.createMap()), 'to be', null);
+ describe("createMap()", function () {
+ it("should return an object with a null prototype", function () {
+ expect(Object.getPrototypeOf(utils.createMap()), "to be", null);
});
- it('should add props to the object', function () {
- expect(utils.createMap({foo: 'bar'}), 'to exhaustively satisfy', {
- foo: 'bar'
+ it("should add props to the object", function () {
+ expect(utils.createMap({ foo: "bar" }), "to exhaustively satisfy", {
+ foo: "bar",
});
});
- it('should add props from all object parameters to the object', function () {
+ it("should add props from all object parameters to the object", function () {
expect(
- utils.createMap({foo: 'bar'}, {bar: 'baz'}),
- 'to exhaustively satisfy',
- {foo: 'bar', bar: 'baz'}
+ utils.createMap({ foo: "bar" }, { bar: "baz" }),
+ "to exhaustively satisfy",
+ { foo: "bar", bar: "baz" },
);
});
});
- describe('slug()', function () {
- it('should convert the string to lowercase', function () {
- expect(utils.slug('FOO'), 'to be', 'foo');
+ describe("slug()", function () {
+ it("should convert the string to lowercase", function () {
+ expect(utils.slug("FOO"), "to be", "foo");
});
- it('should convert whitespace to dashes', function () {
+ it("should convert whitespace to dashes", function () {
expect(
- utils.slug('peanut butter\nand\tjelly'),
- 'to be',
- 'peanut-butter-and-jelly'
+ utils.slug("peanut butter\nand\tjelly"),
+ "to be",
+ "peanut-butter-and-jelly",
);
});
- it('should strip non-alphanumeric and non-dash characters', function () {
- expect(utils.slug('murder-hornets!!'), 'to be', 'murder-hornets');
+ it("should strip non-alphanumeric and non-dash characters", function () {
+ expect(utils.slug("murder-hornets!!"), "to be", "murder-hornets");
});
- it('should disallow consecutive dashes', function () {
- expect(utils.slug('poppies & fritz'), 'to be', 'poppies-fritz');
+ it("should disallow consecutive dashes", function () {
+ expect(utils.slug("poppies & fritz"), "to be", "poppies-fritz");
});
});
- describe('castArray()', function () {
- describe('when provided an array value', function () {
- it('should return a copy of the array', function () {
- const v = ['foo', 'bar', 'baz'];
- expect(utils.castArray(v), 'to equal', ['foo', 'bar', 'baz']).and(
- 'not to be',
- v
+ describe("castArray()", function () {
+ describe("when provided an array value", function () {
+ it("should return a copy of the array", function () {
+ const v = ["foo", "bar", "baz"];
+ expect(utils.castArray(v), "to equal", ["foo", "bar", "baz"]).and(
+ "not to be",
+ v,
);
});
});
describe('when provided an "arguments" value', function () {
- it('should return an array containing the arguments', function () {
+ it("should return an array containing the arguments", function () {
(function () {
- expect(utils.castArray(arguments), 'to equal', [
- 'foo',
- 'bar',
- 'baz'
- ]).and('not to be', arguments);
- })('foo', 'bar', 'baz');
+ expect(utils.castArray(arguments), "to equal", [
+ "foo",
+ "bar",
+ "baz",
+ ]).and("not to be", arguments);
+ })("foo", "bar", "baz");
});
});
- describe('when provided an object', function () {
- it('should return an array containing the object only', function () {
- const v = {foo: 'bar'};
- expect(utils.castArray(v), 'to equal', [v]);
+ describe("when provided an object", function () {
+ it("should return an array containing the object only", function () {
+ const v = { foo: "bar" };
+ expect(utils.castArray(v), "to equal", [v]);
});
});
- describe('when provided no parameters', function () {
- it('should return an empty array', function () {
- expect(utils.castArray(), 'to equal', []);
+ describe("when provided no parameters", function () {
+ it("should return an empty array", function () {
+ expect(utils.castArray(), "to equal", []);
});
});
- describe('when provided a primitive value', function () {
- it('should return an array containing the primitive value only', function () {
- expect(utils.castArray('butts'), 'to equal', ['butts']);
+ describe("when provided a primitive value", function () {
+ it("should return an array containing the primitive value only", function () {
+ expect(utils.castArray("butts"), "to equal", ["butts"]);
});
});
- describe('when provided null', function () {
- it('should return an array containing a null value only', function () {
- expect(utils.castArray(null), 'to equal', [null]);
+ describe("when provided null", function () {
+ it("should return an array containing a null value only", function () {
+ expect(utils.castArray(null), "to equal", [null]);
});
});
});
- describe('uniqueID()', function () {
- it('should return a non-empty string', function () {
- expect(utils.uniqueID(), 'to be a string').and('not to be empty');
+ describe("uniqueID()", function () {
+ it("should return a non-empty string", function () {
+ expect(utils.uniqueID(), "to be a string").and("not to be empty");
});
- it('should have length of 21', function () {
- expect(utils.uniqueID().length, 'to equal', 21);
+ it("should have length of 21", function () {
+ expect(utils.uniqueID().length, "to equal", 21);
});
});
});