☕️ Classic, reliable, trusted test framework for Node.js and the browser
chore: switch reporters from util.inherits to ES2015 classes (#5180)
Josh Goldberg ✨c3f32ce7e2f3
diff --git a/lib/reporters/base.js b/lib/reporters/base.jsindex 8aa87d95..81b427ac 100644--- a/lib/reporters/base.js+++ b/lib/reporters/base.js@@ -31,12 +31,6 @@ function getBrowserWindowSize() {return [640, 480];}-/**- * Expose `Base`.- */--exports = module.exports = Base;-/*** Check if both stdio streams are associated with a tty.*/@@ -49,9 +43,109 @@ var isatty = isBrowser || (process.stdout.isTTY && process.stderr.isTTY);var consoleLog = console.log;/**- * Enable coloring by default, except in the browser interface.+ * @abstract+ * @description+ * All other reporters generally inherit from this reporter.*/+class Base {+ /**+ * Constructs a new `Base` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ var failures = (this.failures = []);++ if (!runner) {+ throw new TypeError("Missing runner argument");+ }+ this.options = options || {};+ this.runner = runner;+ this.stats = runner.stats; // assigned so Reporters keep a closer reference++ var maxDiffSizeOpt =+ this.options.reporterOption && this.options.reporterOption.maxDiffSize;+ if (maxDiffSizeOpt !== undefined && !isNaN(Number(maxDiffSizeOpt))) {+ exports.maxDiffSize = Number(maxDiffSizeOpt);+ }++ runner.on(EVENT_TEST_PASS, function (test) {+ if (test.duration > test.slow()) {+ test.speed = "slow";+ } else if (test.duration > test.slow() / 2) {+ test.speed = "medium";+ } else {+ test.speed = "fast";+ }+ });++ runner.on(EVENT_TEST_FAIL, function (test, err) {+ if (showDiff(err)) {+ stringifyDiffObjs(err);+ }+ // more than one error per test+ if (test.err && err instanceof Error) {+ test.err.multiple = (test.err.multiple || []).concat(err);+ } else {+ test.err = err;+ }+ failures.push(test);+ });+ }++ /**+ * Outputs common epilogue used by many of the bundled reporters.+ *+ * @public+ * @memberof Mocha.reporters+ */+ epilogue() {+ var stats = this.stats;+ var fmt;++ Base.consoleLog();++ // passes+ fmt =+ 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");++ Base.consoleLog(fmt, stats.pending);+ }++ // failures+ if (stats.failures) {+ fmt = color("fail", " %d failing");++ Base.consoleLog(fmt, stats.failures);++ Base.list(this.failures);+ Base.consoleLog();+ }++ Base.consoleLog();+ }+}++Base.consoleLog = consoleLog;++Base.abstract = true;++exports = module.exports = Base;++/**+ * Enable coloring by default, except in the browser interface.+ */exports.useColors =!isBrowser &&(supportsColor.stdout || process.env.MOCHA_COLORS !== undefined);@@ -347,98 +441,6 @@ exports.list = function (failures) {});};-/**- * Constructs a new `Base` reporter instance.- *- * @description- * All other reporters generally inherit from this reporter.- *- * @public- * @class- * @memberof Mocha.reporters- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function Base(runner, options) {- var failures = (this.failures = []);-- if (!runner) {- throw new TypeError("Missing runner argument");- }- this.options = options || {};- this.runner = runner;- this.stats = runner.stats; // assigned so Reporters keep a closer reference-- var maxDiffSizeOpt =- this.options.reporterOption && this.options.reporterOption.maxDiffSize;- if (maxDiffSizeOpt !== undefined && !isNaN(Number(maxDiffSizeOpt))) {- exports.maxDiffSize = Number(maxDiffSizeOpt);- }-- runner.on(EVENT_TEST_PASS, function (test) {- if (test.duration > test.slow()) {- test.speed = "slow";- } else if (test.duration > test.slow() / 2) {- test.speed = "medium";- } else {- test.speed = "fast";- }- });-- runner.on(EVENT_TEST_FAIL, function (test, err) {- if (showDiff(err)) {- stringifyDiffObjs(err);- }- // more than one error per test- if (test.err && err instanceof Error) {- test.err.multiple = (test.err.multiple || []).concat(err);- } else {- test.err = err;- }- failures.push(test);- });-}--/**- * Outputs common epilogue used by many of the bundled reporters.- *- * @public- * @memberof Mocha.reporters- */-Base.prototype.epilogue = function () {- var stats = this.stats;- var fmt;-- Base.consoleLog();-- // passes- fmt =- 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");-- Base.consoleLog(fmt, stats.pending);- }-- // failures- if (stats.failures) {- fmt = color("fail", " %d failing");-- Base.consoleLog(fmt, stats.failures);-- Base.list(this.failures);- Base.consoleLog();- }-- Base.consoleLog();-};-/*** Pads the given `str` to `len`.*@@ -585,7 +587,3 @@ var objToString = Object.prototype.toString;function sameType(a, b) {return objToString.call(a) === objToString.call(b);}--Base.consoleLog = consoleLog;--Base.abstract = true;diff --git a/lib/reporters/doc.js b/lib/reporters/doc.jsindex da8e5d11..e1c02fa0 100644--- a/lib/reporters/doc.js+++ b/lib/reporters/doc.js@@ -19,82 +19,83 @@ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;var EVENT_SUITE_BEGIN = constants.EVENT_SUITE_BEGIN;var EVENT_SUITE_END = constants.EVENT_SUITE_END;-/**- * Expose `Doc`.- */--exports = module.exports = Doc;--/**- * Constructs a new `Doc` reporter instance.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function Doc(runner, options) {- Base.call(this, runner, options);+class Doc extends Base {+ static description = "HTML documentation";- var indents = 2;+ /**+ * Constructs a new `Doc` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);- function indent() {- return Array(indents).join(" ");- }+ var indents = 2;- runner.on(EVENT_SUITE_BEGIN, function (suite) {- if (suite.root) {- return;+ function indent() {+ return Array(indents).join(" ");}- ++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());- });- runner.on(EVENT_SUITE_END, function (suite) {- if (suite.root) {- return;- }- Base.consoleLog("%s</dl>", indent());- --indents;- Base.consoleLog("%s</section>", indent());- --indents;- });+ runner.on(EVENT_SUITE_BEGIN, function (suite) {+ if (suite.root) {+ return;+ }+ ++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());+ });- 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));- var code = utils.escape(utils.clean(test.body));- Base.consoleLog("%s <dd><pre><code>%s</code></pre></dd>", indent(), code);- });+ runner.on(EVENT_SUITE_END, function (suite) {+ if (suite.root) {+ return;+ }+ Base.consoleLog("%s</dl>", indent());+ --indents;+ Base.consoleLog("%s</section>", indent());+ --indents;+ });- runner.on(EVENT_TEST_FAIL, function (test, err) {- Base.consoleLog(- '%s <dt class="error">%s</dt>',- indent(),- utils.escape(test.title),- );- Base.consoleLog(- '%s <dt class="error">%s</dt>',- indent(),- 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,- );- Base.consoleLog(- '%s <dd class="error">%s</dd>',- indent(),- utils.escape(err),- );- });+ 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));+ var code = utils.escape(utils.clean(test.body));+ 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),+ );+ Base.consoleLog(+ '%s <dt class="error">%s</dt>',+ indent(),+ 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,+ );+ Base.consoleLog(+ '%s <dd class="error">%s</dd>',+ indent(),+ utils.escape(err),+ );+ });+ }}-Doc.description = "HTML documentation";+exports = module.exports = Doc;diff --git a/lib/reporters/dot.js b/lib/reporters/dot.jsindex f87c36c8..7ce11b44 100644--- a/lib/reporters/dot.js+++ b/lib/reporters/dot.js@@ -12,7 +12,6 @@*/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;@@ -20,67 +19,59 @@ var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;var EVENT_RUN_END = constants.EVENT_RUN_END;-/**- * Expose `Dot`.- */+class Dot extends Base {+ static description = "dot matrix representation";-exports = module.exports = Dot;--/**- * Constructs a new `Dot` reporter instance.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function Dot(runner, options) {- Base.call(this, runner, options);+ /**+ * Constructs a new `Dot` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);- var self = this;- var width = (Base.window.width * 0.75) | 0;- var n = -1;+ var self = this;+ var width = (Base.window.width * 0.75) | 0;+ var n = -1;- runner.on(EVENT_RUN_BEGIN, function () {- process.stdout.write("\n");- });+ runner.on(EVENT_RUN_BEGIN, function () {+ process.stdout.write("\n");+ });- runner.on(EVENT_TEST_PENDING, function () {- if (++n % width === 0) {- process.stdout.write("\n ");- }- process.stdout.write(Base.color("pending", Base.symbols.comma));- });+ runner.on(EVENT_TEST_PENDING, function () {+ if (++n % width === 0) {+ process.stdout.write("\n ");+ }+ process.stdout.write(Base.color("pending", Base.symbols.comma));+ });- runner.on(EVENT_TEST_PASS, function (test) {- if (++n % width === 0) {- process.stdout.write("\n ");- }- 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));- }- });+ runner.on(EVENT_TEST_PASS, function (test) {+ if (++n % width === 0) {+ process.stdout.write("\n ");+ }+ 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));+ }+ });- runner.on(EVENT_TEST_FAIL, function () {- if (++n % width === 0) {- process.stdout.write("\n ");- }- process.stdout.write(Base.color("fail", Base.symbols.bang));- });+ runner.on(EVENT_TEST_FAIL, function () {+ if (++n % width === 0) {+ process.stdout.write("\n ");+ }+ process.stdout.write(Base.color("fail", Base.symbols.bang));+ });- runner.once(EVENT_RUN_END, function () {- process.stdout.write("\n");- self.epilogue();- });+ runner.once(EVENT_RUN_END, function () {+ process.stdout.write("\n");+ self.epilogue();+ });+ }}-/**- * Inherit from `Base.prototype`.- */-inherits(Dot, Base);--Dot.description = "dot matrix representation";+exports = module.exports = Dot;diff --git a/lib/reporters/html.js b/lib/reporters/html.jsindex 3da435c5..f20117f6 100644--- a/lib/reporters/html.js+++ b/lib/reporters/html.js@@ -28,12 +28,6 @@ var escape = utils.escape;var Date = global.Date;-/**- * Expose `HTML`.- */--exports = module.exports = HTML;-/*** Stats template: Result, progress, passes, failures, and duration.*/@@ -49,236 +43,275 @@ var statsTemplate =var playIcon = "‣";-/**- * Constructs a new `HTML` reporter instance.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function HTML(runner, options) {- Base.call(this, runner, options);-- var self = this;- var stats = this.stats;- var stat = fragment(statsTemplate);- var items = stat.getElementsByTagName("li");- const resultIndex = 0;- const progressIndex = 1;- const passesIndex = 2;- const failuresIndex = 3;- const durationIndex = 4;- /** Stat item containing the root suite pass or fail indicator (hasFailures ? '✖' : '✓') */- var resultIndicator = items[resultIndex];- /** 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];- /** Stat item linking to filter to show only passing tests */- 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];- /** Stat item linking to filter to show only failing tests */- 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 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 progressRing = [- items[progressIndex].getElementsByClassName("ring-flatlight")[0],- items[progressIndex].getElementsByClassName("ring-highlight")[0],- ];- var root = document.getElementById("mocha");-- if (!root) {- return error("#mocha div missing, add it to your document");- }-- // pass toggle- on(passesLink, "click", function (evt) {- evt.preventDefault();- unhide();- var name = /pass/.test(report.className) ? "" : " pass";- report.className = report.className.replace(/fail|pass/g, "") + name;- if (report.className.trim()) {- hideSuitesWithout("test pass");+class HTML extends Base {+ static browserOnly = true;++ /**+ * Constructs a new `HTML` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);++ var self = this;+ var stats = this.stats;+ var stat = fragment(statsTemplate);+ var items = stat.getElementsByTagName("li");+ const resultIndex = 0;+ const progressIndex = 1;+ const passesIndex = 2;+ const failuresIndex = 3;+ const durationIndex = 4;+ /** Stat item containing the root suite pass or fail indicator (hasFailures ? '✖' : '✓') */+ var resultIndicator = items[resultIndex];+ /** 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];+ /** Stat item linking to filter to show only passing tests */+ 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];+ /** Stat item linking to filter to show only failing tests */+ 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 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 progressRing = [+ items[progressIndex].getElementsByClassName("ring-flatlight")[0],+ items[progressIndex].getElementsByClassName("ring-highlight")[0],+ ];+ var root = document.getElementById("mocha");++ if (!root) {+ return error("#mocha div missing, add it to your document");}- });- // failure toggle- on(failuresLink, "click", function (evt) {- evt.preventDefault();- unhide();- var name = /fail/.test(report.className) ? "" : " fail";- report.className = report.className.replace(/fail|pass/g, "") + name;- if (report.className.trim()) {- hideSuitesWithout("test fail");- }- });+ // pass toggle+ on(passesLink, "click", function (evt) {+ evt.preventDefault();+ unhide();+ var name = /pass/.test(report.className) ? "" : " pass";+ report.className = report.className.replace(/fail|pass/g, "") + name;+ if (report.className.trim()) {+ hideSuitesWithout("test pass");+ }+ });++ // failure toggle+ on(failuresLink, "click", function (evt) {+ evt.preventDefault();+ unhide();+ var name = /fail/.test(report.className) ? "" : " fail";+ report.className = report.className.replace(/fail|pass/g, "") + name;+ if (report.className.trim()) {+ hideSuitesWithout("test fail");+ }+ });- root.appendChild(stat);- root.appendChild(report);+ root.appendChild(stat);+ root.appendChild(report);- runner.on(EVENT_SUITE_BEGIN, function (suite) {- if (suite.root) {- return;- }+ runner.on(EVENT_SUITE_BEGIN, function (suite) {+ if (suite.root) {+ return;+ }- // suite- var url = self.suiteURL(suite);- var el = fragment(- '<li class="suite"><h1><a href="%s">%s</a></h1></li>',- url,- escape(suite.title),- );-- // container- stack[0].appendChild(el);- stack.unshift(document.createElement("ul"));- el.appendChild(stack[0]);- });+ // suite+ var url = self.suiteURL(suite);+ var el = fragment(+ '<li class="suite"><h1><a href="%s">%s</a></h1></li>',+ url,+ escape(suite.title),+ );- runner.on(EVENT_SUITE_END, function (suite) {- if (suite.root) {- if (stats.failures === 0) {- text(resultIndicator, "✓");- stat.className += " pass";+ // container+ stack[0].appendChild(el);+ 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";+ }+ updateStats();+ return;}+ stack.shift();+ });++ runner.on(EVENT_TEST_PASS, function (test) {+ var url = self.testURL(test);+ var markup =+ '<li class="test pass %e"><h2>%e<span class="duration">%ems</span> ' ++ '<a href="%s" class="replay">' ++ playIcon ++ "</a></h2></li>";+ var el = fragment(markup, test.speed, test.title, test.duration, url);+ self.addCodeToggle(el, test.body);+ appendToStack(el);updateStats();- return;- }- stack.shift();- });+ });++ runner.on(EVENT_TEST_FAIL, function (test) {+ // Update stat items+ text(resultIndicator, "✖");+ stat.className += " fail";++ var el = fragment(+ '<li class="test fail"><h2>%e <a href="%e" class="replay">' ++ playIcon ++ "</a></h2></li>",+ test.title,+ self.testURL(test),+ );+ var stackString; // Note: Includes leading newline+ var message = test.err.toString();- runner.on(EVENT_TEST_PASS, function (test) {- var url = self.testURL(test);- var markup =- '<li class="test pass %e"><h2>%e<span class="duration">%ems</span> ' +- '<a href="%s" class="replay">' +- playIcon +- "</a></h2></li>";- var el = fragment(markup, test.speed, test.title, test.duration, url);- self.addCodeToggle(el, test.body);- appendToStack(el);- updateStats();- });+ // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we+ // check for the result of the stringifying.+ if (message === "[object Error]") {+ message = test.err.message;+ }- runner.on(EVENT_TEST_FAIL, function (test) {- // Update stat items- text(resultIndicator, "✖");- stat.className += " fail";+ if (test.err.stack) {+ var indexOfMessage = test.err.stack.indexOf(test.err.message);+ if (indexOfMessage === -1) {+ stackString = test.err.stack;+ } else {+ stackString = test.err.stack.slice(+ 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 + ")";+ }- var el = fragment(- '<li class="test fail"><h2>%e <a href="%e" class="replay">' +- playIcon +- "</a></h2></li>",- test.title,- 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]") {- message = test.err.message;- }+ stackString = stackString || "";- if (test.err.stack) {- var indexOfMessage = test.err.stack.indexOf(test.err.message);- if (indexOfMessage === -1) {- stackString = test.err.stack;+ if (test.err.htmlMessage && stackString) {+ el.appendChild(+ fragment(+ '<div class="html-error">%s\n<pre class="error">%e</pre></div>',+ test.err.htmlMessage,+ stackString,+ ),+ );+ } else if (test.err.htmlMessage) {+ el.appendChild(+ fragment('<div class="html-error">%s</div>', test.err.htmlMessage),+ );} else {- stackString = test.err.stack.slice(- test.err.message.length + indexOfMessage,+ el.appendChild(+ fragment('<pre class="error">%e%e</pre>', message, stackString),);}- } 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 = stackString || "";+ self.addCodeToggle(el, test.body);+ appendToStack(el);+ updateStats();+ });- if (test.err.htmlMessage && stackString) {- el.appendChild(- fragment(- '<div class="html-error">%s\n<pre class="error">%e</pre></div>',- test.err.htmlMessage,- stackString,- ),- );- } else if (test.err.htmlMessage) {- el.appendChild(- fragment('<div class="html-error">%s</div>', test.err.htmlMessage),- );- } else {- el.appendChild(- fragment('<pre class="error">%e%e</pre>', message, stackString),+ runner.on(EVENT_TEST_PENDING, function (test) {+ var el = fragment(+ '<li class="test pass pending"><h2>%e</h2></li>',+ test.title,);- }+ appendToStack(el);+ updateStats();+ });- self.addCodeToggle(el, test.body);- appendToStack(el);- updateStats();- });+ function appendToStack(el) {+ // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.+ if (stack[0]) {+ stack[0].appendChild(el);+ }+ }- runner.on(EVENT_TEST_PENDING, function (test) {- var el = fragment(- '<li class="test pass pending"><h2>%e</h2></li>',- test.title,- );- appendToStack(el);- updateStats();- });+ function updateStats() {+ var percent = ((stats.tests / runner.total) * 100) | 0;+ progressBar.value = percent;+ if (progressText) {+ // setting a toFixed that is too low, makes small changes to progress not shown+ // setting it too high, makes the progress text longer then it needs to+ // to address this, calculate the toFixed based on the magnitude of total+ var decimalPlaces = Math.ceil(Math.log10(runner.total / 100));+ text(+ progressText,+ percent.toFixed(Math.min(Math.max(decimalPlaces, 0), 100)) + "%",+ );+ }+ if (progressRing) {+ 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`;+ }- function appendToStack(el) {- // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack.- if (stack[0]) {- stack[0].appendChild(el);+ // update stats+ var ms = new Date() - stats.start;+ text(passesCount, stats.passes);+ text(failuresCount, stats.failures);+ text(duration, (ms / 1000).toFixed(2));}}- function updateStats() {- var percent = ((stats.tests / runner.total) * 100) | 0;- progressBar.value = percent;- if (progressText) {- // setting a toFixed that is too low, makes small changes to progress not shown- // setting it too high, makes the progress text longer then it needs to- // to address this, calculate the toFixed based on the magnitude of total- var decimalPlaces = Math.ceil(Math.log10(runner.total / 100));- text(- progressText,- percent.toFixed(Math.min(Math.max(decimalPlaces, 0), 100)) + "%",- );- }- if (progressRing) {- 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`;- }+ /**+ * Provide suite URL.+ *+ * @param {Object} [suite]+ */+ suiteURL(suite) {+ return makeUrl("^" + escapeRe(suite.fullTitle()) + " ");+ }++ /**+ * Provide test URL.+ *+ * @param {Object} [test]+ */+ testURL(test) {+ return makeUrl("^" + escapeRe(test.fullTitle()) + "$");+ }- // update stats- var ms = new Date() - stats.start;- text(passesCount, stats.passes);- text(failuresCount, stats.failures);- text(duration, (ms / 1000).toFixed(2));+ /**+ * Adds code toggle functionality for the provided test's list element.+ *+ * @param {HTMLLIElement} el+ * @param {string} contents+ */+ addCodeToggle(el, contents) {+ var h2 = el.getElementsByTagName("h2")[0];++ on(h2, "click", function () {+ pre.style.display = pre.style.display === "none" ? "block" : "none";+ });++ var pre = fragment("<pre><code>%e</code></pre>", utils.clean(contents));+ el.appendChild(pre);+ pre.style.display = "none";}}@@ -306,42 +339,6 @@ function makeUrl(s) {);}-/**- * Provide suite URL.- *- * @param {Object} [suite]- */-HTML.prototype.suiteURL = function (suite) {- return makeUrl("^" + escapeRe(suite.fullTitle()) + " ");-};--/**- * Provide test URL.- *- * @param {Object} [test]- */-HTML.prototype.testURL = function (test) {- return makeUrl("^" + escapeRe(test.fullTitle()) + "$");-};--/**- * Adds code toggle functionality for the provided test's list element.- *- * @param {HTMLLIElement} el- * @param {string} contents- */-HTML.prototype.addCodeToggle = function (el, contents) {- var h2 = el.getElementsByTagName("h2")[0];-- on(h2, "click", function () {- pre.style.display = pre.style.display === "none" ? "block" : "none";- });-- var pre = fragment("<pre><code>%e</code></pre>", utils.clean(contents));- el.appendChild(pre);- pre.style.display = "none";-};-/*** Display error `msg`.*@@ -425,4 +422,4 @@ function on(el, event, fn) {}}-HTML.browserOnly = true;+exports = module.exports = HTML;diff --git a/lib/reporters/json-stream.js b/lib/reporters/json-stream.jsindex 9d157e1e..c7d238d3 100644--- a/lib/reporters/json-stream.js+++ b/lib/reporters/json-stream.js@@ -19,46 +19,43 @@ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;var EVENT_RUN_BEGIN = constants.EVENT_RUN_BEGIN;var EVENT_RUN_END = constants.EVENT_RUN_END;-/**- * Expose `JSONStream`.- */--exports = module.exports = JSONStream;+class JSONStream extends Base {+ static description = "newline delimited JSON events";-/**- * Constructs a new `JSONStream` reporter instance.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function JSONStream(runner, options) {- Base.call(this, runner, options);+ /**+ * Constructs a new `JSONStream` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);- var self = this;- var total = runner.total;+ var self = this;+ var total = runner.total;- runner.once(EVENT_RUN_BEGIN, function () {- writeEvent(["start", { total }]);- });+ runner.once(EVENT_RUN_BEGIN, function () {+ writeEvent(["start", { total }]);+ });- runner.on(EVENT_TEST_PASS, function (test) {- writeEvent(["pass", clean(test)]);- });+ runner.on(EVENT_TEST_PASS, function (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]);- });+ runner.on(EVENT_TEST_FAIL, function (test, err) {+ test = clean(test);+ test.err = err.message;+ test.stack = err.stack || null;+ writeEvent(["fail", test]);+ });- runner.once(EVENT_RUN_END, function () {- writeEvent(["end", self.stats]);- });+ runner.once(EVENT_RUN_END, function () {+ writeEvent(["end", self.stats]);+ });+ }}/**@@ -90,4 +87,4 @@ function clean(test) {};}-JSONStream.description = "newline delimited JSON events";+exports = module.exports = JSONStream;diff --git a/lib/reporters/json.js b/lib/reporters/json.jsindex 8ceef6bd..94f8a048 100644--- a/lib/reporters/json.js+++ b/lib/reporters/json.js@@ -23,81 +23,78 @@ var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;var EVENT_TEST_END = constants.EVENT_TEST_END;var EVENT_RUN_END = constants.EVENT_RUN_END;-/**- * Expose `JSON`.- */--exports = module.exports = JSONReporter;--/**- * Constructs a new `JSON` reporter instance.- *- * @public- * @class JSON- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function JSONReporter(runner, options = {}) {- Base.call(this, runner, options);-- var self = this;- var tests = [];- var pending = [];- var failures = [];- var passes = [];- var output;-- if (options.reporterOption && options.reporterOption.output) {- if (utils.isBrowser()) {- throw createUnsupportedError("file output not supported in browser");+class JSONReporter extends Base {+ static description = "single JSON object";++ /**+ * Constructs a new `JSON` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options = {}) {+ super(runner, options);++ var self = this;+ var tests = [];+ var pending = [];+ var failures = [];+ var passes = [];+ var output;++ if (options.reporterOption && options.reporterOption.output) {+ if (utils.isBrowser()) {+ throw createUnsupportedError("file output not supported in browser");+ }+ output = options.reporterOption.output;}- output = options.reporterOption.output;- }- runner.on(EVENT_TEST_END, function (test) {- tests.push(test);- });-- runner.on(EVENT_TEST_PASS, function (test) {- passes.push(test);- });-- runner.on(EVENT_TEST_FAIL, function (test) {- failures.push(test);- });-- runner.on(EVENT_TEST_PENDING, function (test) {- pending.push(test);- });-- runner.once(EVENT_RUN_END, function () {- var obj = {- stats: self.stats,- tests: tests.map(clean),- pending: pending.map(clean),- failures: failures.map(clean),- passes: passes.map(clean),- };-- runner.testResults = obj;-- var json = JSON.stringify(obj, null, 2);- if (output) {- try {- 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`,- );+ runner.on(EVENT_TEST_END, function (test) {+ tests.push(test);+ });++ runner.on(EVENT_TEST_PASS, function (test) {+ passes.push(test);+ });++ runner.on(EVENT_TEST_FAIL, function (test) {+ failures.push(test);+ });++ runner.on(EVENT_TEST_PENDING, function (test) {+ pending.push(test);+ });++ runner.once(EVENT_RUN_END, function () {+ var obj = {+ stats: self.stats,+ tests: tests.map(clean),+ pending: pending.map(clean),+ failures: failures.map(clean),+ passes: passes.map(clean),+ };++ runner.testResults = obj;++ var json = JSON.stringify(obj, null, 2);+ if (output) {+ try {+ 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`,+ );+ process.stdout.write(json);+ }+ } else {process.stdout.write(json);}- } else {- process.stdout.write(json);- }- });+ });+ }}/**@@ -164,4 +161,4 @@ function errorJSON(err) {return res;}-JSONReporter.description = "single JSON object";+exports = module.exports = JSONReporter;diff --git a/lib/reporters/landing.js b/lib/reporters/landing.jsindex bbb01c4e..2151aea6 100644--- a/lib/reporters/landing.js+++ b/lib/reporters/landing.js@@ -12,7 +12,6 @@*/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;@@ -22,12 +21,6 @@ var STATE_FAILED = require("../runnable").constants.STATE_FAILED;var cursor = Base.cursor;var color = Base.color;-/**- * Expose `Landing`.- */--exports = module.exports = Landing;-/*** Airplane color.*/@@ -46,76 +39,74 @@ Base.colors["plane crash"] = 31;Base.colors.runway = 90;-/**- * Constructs a new `Landing` reporter instance.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function Landing(runner, options) {- Base.call(this, runner, options);-- var self = this;- var width = (Base.window.width * 0.75) | 0;- var stream = process.stdout;+class Landing extends Base {+ static description = "Unicode landing strip";++ /**+ * Constructs a new `Landing` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);++ var self = this;+ var width = (Base.window.width * 0.75) | 0;+ var stream = process.stdout;++ 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 plane = color("plane", "✈");- var crashed = -1;- var n = 0;- var total = 0;+ runner.on(EVENT_RUN_BEGIN, function () {+ stream.write("\n\n\n ");+ cursor.hide();+ });- function runway() {- var buf = Array(width).join("-");- return " " + color("runway", buf);- }+ runner.on(EVENT_TEST_END, function (test) {+ // check if the plane crashed+ var col = crashed === -1 ? ((width * ++n) / ++total) | 0 : crashed;+ // show the crash+ if (test.state === STATE_FAILED) {+ plane = color("plane crash", "✈");+ crashed = col;+ }++ // render landing strip+ stream.write("\u001b[" + (width + 1) + "D\u001b[2A");+ stream.write(runway());+ stream.write("\n ");+ stream.write(color("runway", Array(col).join("⋅")));+ stream.write(plane);+ stream.write(color("runway", Array(width - col).join("⋅") + "\n"));+ stream.write(runway());+ stream.write("\u001b[0m");+ });- runner.on(EVENT_RUN_BEGIN, function () {- stream.write("\n\n\n ");- cursor.hide();- });-- runner.on(EVENT_TEST_END, function (test) {- // check if the plane crashed- var col = crashed === -1 ? ((width * ++n) / ++total) | 0 : crashed;- // show the crash- if (test.state === STATE_FAILED) {- plane = color("plane crash", "✈");- crashed = col;- }+ runner.once(EVENT_RUN_END, function () {+ cursor.show();+ process.stdout.write("\n");+ self.epilogue();+ });- // render landing strip- stream.write("\u001b[" + (width + 1) + "D\u001b[2A");- stream.write(runway());- stream.write("\n ");- stream.write(color("runway", Array(col).join("⋅")));- stream.write(plane);- stream.write(color("runway", Array(width - col).join("⋅") + "\n"));- stream.write(runway());- stream.write("\u001b[0m");- });-- runner.once(EVENT_RUN_END, function () {- cursor.show();- process.stdout.write("\n");- self.epilogue();- });-- // if cursor is hidden when we ctrl-C, then it will remain hidden unless...- process.once("SIGINT", function () {- cursor.show();- process.nextTick(function () {- process.kill(process.pid, "SIGINT");+ // if cursor is hidden when we ctrl-C, then it will remain hidden unless...+ process.once("SIGINT", function () {+ cursor.show();+ process.nextTick(function () {+ process.kill(process.pid, "SIGINT");+ });});- });+ }}-/**- * Inherit from `Base.prototype`.- */-inherits(Landing, Base);--Landing.description = "Unicode landing strip";+exports = module.exports = Landing;diff --git a/lib/reporters/list.js b/lib/reporters/list.jsindex ff372124..5d9485b6 100644--- a/lib/reporters/list.js+++ b/lib/reporters/list.js@@ -12,7 +12,6 @@*/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;@@ -23,61 +22,52 @@ var EVENT_TEST_PENDING = constants.EVENT_TEST_PENDING;var color = Base.color;var cursor = Base.cursor;-/**- * Expose `List`.- */+class List extends Base {+ static description = 'like "spec" reporter but flat';-exports = module.exports = List;--/**- * Constructs a new `List` reporter instance.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function List(runner, options) {- Base.call(this, runner, options);+ /**+ * Constructs a new `List` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);- var self = this;- var n = 0;+ var n = 0;- runner.on(EVENT_RUN_BEGIN, function () {- Base.consoleLog();- });+ runner.on(EVENT_RUN_BEGIN, function () {+ Base.consoleLog();+ });- runner.on(EVENT_TEST_BEGIN, function (test) {- process.stdout.write(color("pass", " " + test.fullTitle() + ": "));- });+ runner.on(EVENT_TEST_BEGIN, function (test) {+ process.stdout.write(color("pass", " " + test.fullTitle() + ": "));+ });- runner.on(EVENT_TEST_PENDING, function (test) {- var fmt = color("checkmark", " -") + color("pending", " %s");- Base.consoleLog(fmt, test.fullTitle());- });+ runner.on(EVENT_TEST_PENDING, function (test) {+ 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");- cursor.CR();- Base.consoleLog(fmt, test.fullTitle(), test.duration);- });+ runner.on(EVENT_TEST_PASS, function (test) {+ var fmt =+ 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());- });+ runner.on(EVENT_TEST_FAIL, function (test) {+ cursor.CR();+ Base.consoleLog(color("fail", " %d) %s"), ++n, test.fullTitle());+ });- runner.once(EVENT_RUN_END, self.epilogue.bind(self));+ runner.once(EVENT_RUN_END, (...args) => this.epilogue(...args));+ }}-/**- * Inherit from `Base.prototype`.- */-inherits(List, Base);--List.description = 'like "spec" reporter but flat';+exports = module.exports = List;diff --git a/lib/reporters/markdown.js b/lib/reporters/markdown.jsindex 5c2e487d..c288dd8b 100644--- a/lib/reporters/markdown.js+++ b/lib/reporters/markdown.js@@ -25,93 +25,90 @@ var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;var SUITE_PREFIX = "$";-/**- * Expose `Markdown`.- */+class Markdown extends Base {+ static description = "GitHub Flavored Markdown";++ /**+ * Constructs a new `Markdown` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);++ var level = 0;+ var buf = "";-exports = module.exports = Markdown;+ function title(str) {+ return Array(level).join("#") + " " + str;+ }-/**- * Constructs a new `Markdown` reporter instance.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function Markdown(runner, options) {- Base.call(this, runner, options);+ function mapTOC(suite, obj) {+ var ret = obj;+ var key = SUITE_PREFIX + suite.title;- var level = 0;- var buf = "";+ obj = obj[key] = obj[key] || { suite };+ suite.suites.forEach(function (suite) {+ mapTOC(suite, obj);+ });- function title(str) {- return Array(level).join("#") + " " + str;- }+ return ret;+ }++ function stringifyTOC(obj, level) {+ ++level;+ var buf = "";+ var link;+ for (var key in obj) {+ 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;+ }+ buf += stringifyTOC(obj[key], level);+ }+ return buf;+ }- function mapTOC(suite, obj) {- var ret = obj;- var key = SUITE_PREFIX + suite.title;+ function generateTOC(suite) {+ var obj = mapTOC(suite, {});+ return stringifyTOC(obj, 0);+ }- obj = obj[key] = obj[key] || { suite };- suite.suites.forEach(function (suite) {- mapTOC(suite, obj);+ generateTOC(runner.suite);++ 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";});- return ret;- }+ runner.on(EVENT_SUITE_END, function () {+ --level;+ });- function stringifyTOC(obj, level) {- ++level;- var buf = "";- var link;- for (var key in obj) {- 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;- }- buf += stringifyTOC(obj[key], level);- }- return buf;- }+ 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";+ });- function generateTOC(suite) {- var obj = mapTOC(suite, {});- return stringifyTOC(obj, 0);+ runner.once(EVENT_RUN_END, function () {+ process.stdout.write("# TOC\n");+ process.stdout.write(generateTOC(runner.suite));+ process.stdout.write(buf);+ });}-- generateTOC(runner.suite);-- 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";- });-- runner.on(EVENT_SUITE_END, function () {- --level;- });-- 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";- });-- runner.once(EVENT_RUN_END, function () {- process.stdout.write("# TOC\n");- process.stdout.write(generateTOC(runner.suite));- process.stdout.write(buf);- });}-Markdown.description = "GitHub Flavored Markdown";+exports = module.exports = Markdown;diff --git a/lib/reporters/min.js b/lib/reporters/min.jsindex a825e629..3f8915ac 100644--- a/lib/reporters/min.js+++ b/lib/reporters/min.js@@ -12,46 +12,37 @@*/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;-/**- * Expose `Min`.- */--exports = module.exports = Min;--/**- * Constructs a new `Min` reporter instance.- *- * @description- * This minimal test reporter is best used with '--watch'.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function Min(runner, options) {- Base.call(this, runner, options);-- runner.on(EVENT_RUN_BEGIN, function () {- // clear screen- process.stdout.write("\u001b[2J");- // set cursor position- process.stdout.write("\u001b[1;3H");- });-- runner.once(EVENT_RUN_END, this.epilogue.bind(this));+class Min extends Base {+ static description = "essentially just a summary";++ /**+ * Constructs a new `Min` reporter instance.+ *+ * @description+ * This minimal test reporter is best used with '--watch'.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);++ runner.on(EVENT_RUN_BEGIN, function () {+ // clear screen+ process.stdout.write("\u001b[2J");+ // set cursor position+ process.stdout.write("\u001b[1;3H");+ });++ runner.once(EVENT_RUN_END, (...args) => this.epilogue(...args));+ }}-/**- * Inherit from `Base.prototype`.- */-inherits(Min, Base);--Min.description = "essentially just a summary";+exports = module.exports = Min;diff --git a/lib/reporters/nyan.js b/lib/reporters/nyan.jsindex bb446d5c..465c8649 100644--- a/lib/reporters/nyan.js+++ b/lib/reporters/nyan.js@@ -13,260 +13,251 @@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;var EVENT_RUN_END = constants.EVENT_RUN_END;var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;-/**- * Expose `Dot`.- */--exports = module.exports = NyanCat;--/**- * Constructs a new `Nyan` reporter instance.- *- * @public- * @class Nyan- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function NyanCat(runner, options) {- Base.call(this, runner, options);-- var self = this;- var width = (Base.window.width * 0.75) | 0;- var nyanCatWidth = (this.nyanCatWidth = 11);-- this.colorIndex = 0;- this.numberOfLines = 4;- this.rainbowColors = self.generateColors();- this.scoreboardWidth = 5;- this.tick = 0;- this.trajectories = [[], [], [], []];- this.trajectoryWidthMax = width - nyanCatWidth;-- runner.on(EVENT_RUN_BEGIN, function () {- Base.cursor.hide();- self.draw();- });-- runner.on(EVENT_TEST_PENDING, function () {- self.draw();- });-- runner.on(EVENT_TEST_PASS, function () {- self.draw();- });-- runner.on(EVENT_TEST_FAIL, function () {- self.draw();- });-- runner.once(EVENT_RUN_END, function () {- Base.cursor.show();- for (var i = 0; i < self.numberOfLines; i++) {- process.stdout.write("\n");- }- self.epilogue();- });-}--/**- * Inherit from `Base.prototype`.- */-inherits(NyanCat, Base);+class NyanCat extends Base {+ static description = '"nyan cat"';++ /**+ * Constructs a new `Nyan` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);++ var self = this;+ var width = (Base.window.width * 0.75) | 0;+ var nyanCatWidth = (this.nyanCatWidth = 11);++ this.colorIndex = 0;+ this.numberOfLines = 4;+ this.rainbowColors = self.generateColors();+ this.scoreboardWidth = 5;+ this.tick = 0;+ this.trajectories = [[], [], [], []];+ this.trajectoryWidthMax = width - nyanCatWidth;++ runner.on(EVENT_RUN_BEGIN, function () {+ Base.cursor.hide();+ self.draw();+ });++ runner.on(EVENT_TEST_PENDING, function () {+ self.draw();+ });++ runner.on(EVENT_TEST_PASS, function () {+ self.draw();+ });++ runner.on(EVENT_TEST_FAIL, function () {+ self.draw();+ });++ runner.once(EVENT_RUN_END, function () {+ Base.cursor.show();+ for (var i = 0; i < self.numberOfLines; i++) {+ process.stdout.write("\n");+ }+ self.epilogue();+ });+ }-/**- * Draw the nyan cat- *- * @private- */+ /**+ * Draw the nyan cat+ *+ * @private+ */++ draw() {+ this.appendRainbow();+ this.drawScoreboard();+ this.drawRainbow();+ this.drawNyanCat();+ this.tick = !this.tick;+ }-NyanCat.prototype.draw = function () {- this.appendRainbow();- this.drawScoreboard();- this.drawRainbow();- this.drawNyanCat();- this.tick = !this.tick;-};+ /**+ * Draw the "scoreboard" showing the number+ * of passes, failures and pending tests.+ *+ * @private+ */-/**- * Draw the "scoreboard" showing the number- * of passes, failures and pending tests.- *- * @private- */+ drawScoreboard() {+ var stats = this.stats;-NyanCat.prototype.drawScoreboard = function () {- var stats = this.stats;+ function draw(type, n) {+ process.stdout.write(" ");+ process.stdout.write(Base.color(type, n));+ process.stdout.write("\n");+ }- function draw(type, n) {- process.stdout.write(" ");- process.stdout.write(Base.color(type, n));+ draw("green", stats.passes);+ draw("fail", stats.failures);+ draw("pending", stats.pending);process.stdout.write("\n");++ this.cursorUp(this.numberOfLines);}- draw("green", stats.passes);- draw("fail", stats.failures);- draw("pending", stats.pending);- process.stdout.write("\n");+ /**+ * Append the rainbow.+ *+ * @private+ */++ appendRainbow() {+ var segment = this.tick ? "_" : "-";+ var rainbowified = this.rainbowify(segment);++ for (var index = 0; index < this.numberOfLines; index++) {+ var trajectory = this.trajectories[index];+ if (trajectory.length >= this.trajectoryWidthMax) {+ trajectory.shift();+ }+ trajectory.push(rainbowified);+ }+ }- this.cursorUp(this.numberOfLines);-};+ /**+ * Draw the rainbow.+ *+ * @private+ */-/**- * Append the rainbow.- *- * @private- */+ drawRainbow() {+ var self = this;-NyanCat.prototype.appendRainbow = function () {- var segment = this.tick ? "_" : "-";- var rainbowified = this.rainbowify(segment);+ this.trajectories.forEach(function (line) {+ process.stdout.write("\u001b[" + self.scoreboardWidth + "C");+ process.stdout.write(line.join(""));+ process.stdout.write("\n");+ });- for (var index = 0; index < this.numberOfLines; index++) {- var trajectory = this.trajectories[index];- if (trajectory.length >= this.trajectoryWidthMax) {- trajectory.shift();- }- trajectory.push(rainbowified);+ this.cursorUp(this.numberOfLines);}-};-/**- * Draw the rainbow.- *- * @private- */--NyanCat.prototype.drawRainbow = function () {- var self = this;-- this.trajectories.forEach(function (line) {- process.stdout.write("\u001b[" + self.scoreboardWidth + "C");- process.stdout.write(line.join(""));+ /**+ * Draw the nyan cat+ *+ * @private+ */+ drawNyanCat() {+ var self = this;+ var startWidth = this.scoreboardWidth + this.trajectories[0].length;+ var dist = "\u001b[" + startWidth + "C";+ var padding;++ process.stdout.write(dist);+ process.stdout.write("_,------,");process.stdout.write("\n");- });- this.cursorUp(this.numberOfLines);-};+ process.stdout.write(dist);+ padding = self.tick ? " " : " ";+ process.stdout.write("_|" + padding + "/\\_/\\ ");+ process.stdout.write("\n");-/**- * Draw the nyan cat- *- * @private- */-NyanCat.prototype.drawNyanCat = function () {- var self = this;- var startWidth = this.scoreboardWidth + this.trajectories[0].length;- var dist = "\u001b[" + startWidth + "C";- var padding;-- process.stdout.write(dist);- process.stdout.write("_,------,");- process.stdout.write("\n");-- process.stdout.write(dist);- 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");-- process.stdout.write(dist);- padding = self.tick ? " " : " ";- process.stdout.write(padding + '"" "" ');- process.stdout.write("\n");-- this.cursorUp(this.numberOfLines);-};+ process.stdout.write(dist);+ padding = self.tick ? "_" : "__";+ var tail = self.tick ? "~" : "^";+ process.stdout.write(tail + "|" + padding + this.face() + " ");+ process.stdout.write("\n");-/**- * Draw nyan cat face.- *- * @private- * @return {string}- */+ process.stdout.write(dist);+ padding = self.tick ? " " : " ";+ process.stdout.write(padding + '"" "" ');+ process.stdout.write("\n");-NyanCat.prototype.face = function () {- var stats = this.stats;- if (stats.failures) {- return "( x .x)";- } else if (stats.pending) {- return "( o .o)";- } else if (stats.passes) {- return "( ^ .^)";+ this.cursorUp(this.numberOfLines);}- return "( - .-)";-};-/**- * Move cursor up `n`.- *- * @private- * @param {number} n- */+ /**+ * Draw nyan cat face.+ *+ * @private+ * @return {string}+ */++ face() {+ var stats = this.stats;+ if (stats.failures) {+ return "( x .x)";+ } else if (stats.pending) {+ return "( o .o)";+ } else if (stats.passes) {+ return "( ^ .^)";+ }+ return "( - .-)";+ }-NyanCat.prototype.cursorUp = function (n) {- process.stdout.write("\u001b[" + n + "A");-};+ /**+ * Move cursor up `n`.+ *+ * @private+ * @param {number} n+ */-/**- * Move cursor down `n`.- *- * @private- * @param {number} n- */+ cursorUp(n) {+ process.stdout.write("\u001b[" + n + "A");+ }-NyanCat.prototype.cursorDown = function (n) {- process.stdout.write("\u001b[" + n + "B");-};+ /**+ * Move cursor down `n`.+ *+ * @private+ * @param {number} n+ */-/**- * Generate rainbow colors.- *- * @private- * @return {Array}- */-NyanCat.prototype.generateColors = function () {- var colors = [];-- for (var i = 0; i < 6 * 7; i++) {- var pi3 = Math.floor(Math.PI / 3);- var n = i * (1.0 / 6);- var r = Math.floor(3 * Math.sin(n) + 3);- var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);- var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);- colors.push(36 * r + 6 * g + b + 16);+ cursorDown(n) {+ process.stdout.write("\u001b[" + n + "B");}- return colors;-};+ /**+ * Generate rainbow colors.+ *+ * @private+ * @return {Array}+ */+ generateColors() {+ var colors = [];++ for (var i = 0; i < 6 * 7; i++) {+ var pi3 = Math.floor(Math.PI / 3);+ var n = i * (1.0 / 6);+ var r = Math.floor(3 * Math.sin(n) + 3);+ var g = Math.floor(3 * Math.sin(n + 2 * pi3) + 3);+ var b = Math.floor(3 * Math.sin(n + 4 * pi3) + 3);+ colors.push(36 * r + 6 * g + b + 16);+ }++ return colors;+ }-/**- * Apply rainbow to the given `str`.- *- * @private- * @param {string} str- * @return {string}- */-NyanCat.prototype.rainbowify = function (str) {- if (!Base.useColors) {- return str;+ /**+ * Apply rainbow to the given `str`.+ *+ * @private+ * @param {string} str+ * @return {string}+ */+ rainbowify(str) {+ if (!Base.useColors) {+ return str;+ }+ var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];+ this.colorIndex += 1;+ return "\u001b[38;5;" + color + "m" + str + "\u001b[0m";}- var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length];- this.colorIndex += 1;- return "\u001b[38;5;" + color + "m" + str + "\u001b[0m";-};+}-NyanCat.description = '"nyan cat"';+exports = module.exports = NyanCat;diff --git a/lib/reporters/progress.js b/lib/reporters/progress.jsindex 9058cdbf..3f86af9d 100644--- a/lib/reporters/progress.js+++ b/lib/reporters/progress.js@@ -16,94 +16,87 @@ 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 color = Base.color;var cursor = Base.cursor;-/**- * Expose `Progress`.- */--exports = module.exports = Progress;-/*** General progress bar color.*/Base.colors.progress = 90;-/**- * Constructs a new `Progress` reporter instance.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function Progress(runner, options) {- Base.call(this, runner, options);-- var self = this;- var width = (Base.window.width * 0.5) | 0;- var total = runner.total;- var complete = 0;- var lastN = -1;-- // default chars- options = options || {};- var reporterOptions = options.reporterOptions || {};-- options.open = reporterOptions.open || "[";- options.complete = reporterOptions.complete || "▬";- options.incomplete = reporterOptions.incomplete || Base.symbols.dot;- options.close = reporterOptions.close || "]";- options.verbose = reporterOptions.verbose || false;-- // tests started- runner.on(EVENT_RUN_BEGIN, function () {- process.stdout.write("\n");- cursor.hide();- });-- // tests complete- runner.on(EVENT_TEST_END, function () {- complete++;-- var percent = complete / total;- var n = (width * percent) | 0;- var i = width - n;-- if (n === lastN && !options.verbose) {- // Don't re-render the line if it hasn't changed- return;- }- lastN = n;-- cursor.CR();- 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));- if (options.verbose) {- process.stdout.write(color("progress", " " + complete + " of " + total));- }- });-- // tests are complete, output some stats- // and the failures if any- runner.once(EVENT_RUN_END, function () {- cursor.show();- process.stdout.write("\n");- self.epilogue();- });+class Progress extends Base {+ static description = "a progress bar";++ /**+ * Constructs a new `Progress` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);++ var self = this;+ var width = (Base.window.width * 0.5) | 0;+ var total = runner.total;+ var complete = 0;+ var lastN = -1;++ // default chars+ options = options || {};+ var reporterOptions = options.reporterOptions || {};++ options.open = reporterOptions.open || "[";+ options.complete = reporterOptions.complete || "▬";+ options.incomplete = reporterOptions.incomplete || Base.symbols.dot;+ options.close = reporterOptions.close || "]";+ options.verbose = reporterOptions.verbose || false;++ // tests started+ runner.on(EVENT_RUN_BEGIN, function () {+ process.stdout.write("\n");+ cursor.hide();+ });++ // tests complete+ runner.on(EVENT_TEST_END, function () {+ complete++;++ var percent = complete / total;+ var n = (width * percent) | 0;+ var i = width - n;++ if (n === lastN && !options.verbose) {+ // Don't re-render the line if it hasn't changed+ return;+ }+ lastN = n;++ cursor.CR();+ 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));+ if (options.verbose) {+ process.stdout.write(+ color("progress", " " + complete + " of " + total),+ );+ }+ });++ // tests are complete, output some stats+ // and the failures if any+ runner.once(EVENT_RUN_END, function () {+ cursor.show();+ process.stdout.write("\n");+ self.epilogue();+ });+ }}-/**- * Inherit from `Base.prototype`.- */-inherits(Progress, Base);--Progress.description = "a progress bar";+exports = module.exports = Progress;diff --git a/lib/reporters/spec.js b/lib/reporters/spec.jsindex 5f2f56d3..fcdff533 100644--- a/lib/reporters/spec.js+++ b/lib/reporters/spec.js@@ -21,85 +21,75 @@ 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 color = Base.color;-/**- * Expose `Spec`.- */--exports = module.exports = Spec;--/**- * Constructs a new `Spec` reporter instance.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function Spec(runner, options) {- Base.call(this, runner, options);-- var self = this;- var indents = 0;- var n = 0;-- function indent() {- return Array(indents).join(" ");- }-- runner.on(EVENT_RUN_BEGIN, function () {- Base.consoleLog();- });-- runner.on(EVENT_SUITE_BEGIN, function (suite) {- ++indents;- Base.consoleLog(color("suite", "%s%s"), indent(), suite.title);- });-- runner.on(EVENT_SUITE_END, function () {- --indents;- if (indents === 1) {- Base.consoleLog();+class Spec extends Base {+ static description = "hierarchical & verbose [default]";++ /**+ * Constructs a new `Spec` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);++ var indents = 0;+ var n = 0;++ function indent() {+ return Array(indents).join(" ");}- });-- runner.on(EVENT_TEST_PENDING, function (test) {- var fmt = indent() + color("pending", " - %s");- Base.consoleLog(fmt, test.title);- });- runner.on(EVENT_TEST_PASS, function (test) {- var fmt;- if (test.speed === "fast") {- fmt =- indent() +- color("checkmark", " " + Base.symbols.ok) +- color("pass", " %s");+ runner.on(EVENT_RUN_BEGIN, function () {+ Base.consoleLog();+ });++ runner.on(EVENT_SUITE_BEGIN, function (suite) {+ ++indents;+ Base.consoleLog(color("suite", "%s%s"), indent(), suite.title);+ });++ runner.on(EVENT_SUITE_END, function () {+ --indents;+ if (indents === 1) {+ Base.consoleLog();+ }+ });++ runner.on(EVENT_TEST_PENDING, function (test) {+ var fmt = indent() + color("pending", " - %s");Base.consoleLog(fmt, test.title);- } else {- fmt =- indent() +- 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);- });-- runner.once(EVENT_RUN_END, self.epilogue.bind(self));+ });++ runner.on(EVENT_TEST_PASS, function (test) {+ var fmt;+ if (test.speed === "fast") {+ fmt =+ indent() ++ 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)");+ Base.consoleLog(fmt, test.title, test.duration);+ }+ });++ runner.on(EVENT_TEST_FAIL, function (test) {+ Base.consoleLog(indent() + color("fail", " %d) %s"), ++n, test.title);+ });++ runner.once(EVENT_RUN_END, (...args) => this.epilogue(...args));+ }}-/**- * Inherit from `Base.prototype`.- */-inherits(Spec, Base);--Spec.description = "hierarchical & verbose [default]";+exports = module.exports = Spec;diff --git a/lib/reporters/tap.js b/lib/reporters/tap.jsindex d34ac981..cb16578e 100644--- a/lib/reporters/tap.js+++ b/lib/reporters/tap.js@@ -21,70 +21,61 @@ 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 sprintf = util.format;-/**- * Expose `TAP`.- */+class TAP extends Base {+ static description = "TAP-compatible output";-exports = module.exports = TAP;--/**- * Constructs a new `TAP` reporter instance.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function TAP(runner, options) {- Base.call(this, runner, options);+ /**+ * Constructs a new `TAP` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);- var self = this;- var n = 1;+ var self = this;+ var n = 1;- var tapVersion = "12";- if (options && options.reporterOptions) {- if (options.reporterOptions.tapVersion) {- tapVersion = options.reporterOptions.tapVersion.toString();+ var tapVersion = "12";+ if (options && options.reporterOptions) {+ if (options.reporterOptions.tapVersion) {+ tapVersion = options.reporterOptions.tapVersion.toString();+ }}- }- this._producer = createProducer(tapVersion);+ this._producer = createProducer(tapVersion);- runner.once(EVENT_RUN_BEGIN, function () {- self._producer.writeVersion();- });+ runner.once(EVENT_RUN_BEGIN, function () {+ self._producer.writeVersion();+ });- runner.on(EVENT_TEST_END, function () {- ++n;- });+ runner.on(EVENT_TEST_END, function () {+ ++n;+ });- runner.on(EVENT_TEST_PENDING, function (test) {- self._producer.writePending(n, test);- });+ runner.on(EVENT_TEST_PENDING, function (test) {+ self._producer.writePending(n, test);+ });- runner.on(EVENT_TEST_PASS, function (test) {- self._producer.writePass(n, test);- });+ runner.on(EVENT_TEST_PASS, function (test) {+ self._producer.writePass(n, test);+ });- runner.on(EVENT_TEST_FAIL, function (test, err) {- self._producer.writeFail(n, test, err);- });+ runner.on(EVENT_TEST_FAIL, function (test, err) {+ self._producer.writeFail(n, test, err);+ });- runner.once(EVENT_RUN_END, function () {- self._producer.writeEpilogue(runner.stats);- });+ runner.once(EVENT_RUN_END, function () {+ self._producer.writeEpilogue(runner.stats);+ });+ }}-/**- * Inherit from `Base.prototype`.- */-inherits(TAP, Base);-/*** Returns a TAP-safe title of `test`.*@@ -143,77 +134,74 @@ function createProducer(tapVersion) {* @private* @constructor*/-function TAPProducer() {}--/**- * Writes the TAP version to reporter output stream.- *- * @abstract- */-TAPProducer.prototype.writeVersion = function () {};+class TAPProducer {+ /**+ * Writes the TAP version to reporter output stream.+ *+ * @abstract+ */+ writeVersion() {}-/**- * Writes the plan to reporter output stream.- *- * @abstract- * @param {number} ntests - Number of tests that are planned to run.- */-TAPProducer.prototype.writePlan = function (ntests) {- println("%d..%d", 1, ntests);-};+ /**+ * Writes the plan to reporter output stream.+ *+ * @abstract+ * @param {number} ntests - Number of tests that are planned to run.+ */+ writePlan(ntests) {+ println("%d..%d", 1, ntests);+ }-/**- * Writes that test passed to reporter output stream.- *- * @abstract- * @param {number} n - Index of test that passed.- * @param {Test} test - Instance containing test information.- */-TAPProducer.prototype.writePass = function (n, test) {- println("ok %d %s", n, title(test));-};+ /**+ * Writes that test passed to reporter output stream.+ *+ * @abstract+ * @param {number} n - Index of test that passed.+ * @param {Test} test - Instance containing test information.+ */+ writePass(n, test) {+ println("ok %d %s", n, title(test));+ }-/**- * Writes that test was skipped to reporter output stream.- *- * @abstract- * @param {number} n - Index of test that was skipped.- * @param {Test} test - Instance containing test information.- */-TAPProducer.prototype.writePending = function (n, test) {- println("ok %d %s # SKIP -", n, title(test));-};+ /**+ * Writes that test was skipped to reporter output stream.+ *+ * @abstract+ * @param {number} n - Index of test that was skipped.+ * @param {Test} test - Instance containing test information.+ */+ writePending(n, test) {+ println("ok %d %s # SKIP -", n, title(test));+ }-/**- * Writes that test failed to reporter output stream.- *- * @abstract- * @param {number} n - Index of test that failed.- * @param {Test} test - Instance containing test information.- */-TAPProducer.prototype.writeFail = function (n, test) {- println("not ok %d %s", n, title(test));-};+ /**+ * Writes that test failed to reporter output stream.+ *+ * @abstract+ * @param {number} n - Index of test that failed.+ * @param {Test} test - Instance containing test information.+ */+ writeFail(n, test) {+ println("not ok %d %s", n, title(test));+ }-/**- * Writes the summary epilogue to reporter output stream.- *- * @abstract- * @param {Object} stats - Object containing run statistics.- */-TAPProducer.prototype.writeEpilogue = function (stats) {- // :TBD: Why is this not counting pending tests?- println("# tests " + (stats.passes + stats.failures));- println("# pass " + stats.passes);- // :TBD: Why are we not showing pending results?- println("# fail " + stats.failures);- this.writePlan(stats.passes + stats.failures + stats.pending);-};+ /**+ * Writes the summary epilogue to reporter output stream.+ *+ * @abstract+ * @param {Object} stats - Object containing run statistics.+ */+ writeEpilogue(stats) {+ // :TBD: Why is this not counting pending tests?+ println("# tests " + (stats.passes + stats.failures));+ println("# pass " + stats.passes);+ // :TBD: Why are we not showing pending results?+ println("# fail " + stats.failures);+ this.writePlan(stats.passes + stats.failures + stats.pending);+ }+}/**- * @summary- * Constructs a new TAP12Producer.- ** @description* Produces output conforming to the TAP12 specification.*@@ -222,27 +210,22 @@ TAPProducer.prototype.writeEpilogue = function (stats) {* @extends TAPProducer* @see {@link https://testanything.org/tap-specification.html|Specification}*/-function TAP12Producer() {+class TAP12Producer extends TAPProducer {/*** Writes that test failed to reporter output stream, with error formatting.* @override*/- this.writeFail = function (n, test, err) {- TAPProducer.prototype.writeFail.call(this, n, test, err);+ writeFail(n, test, err) {+ super.writeFail(n, test, err);if (err.message) {println(err.message.replace(/^/gm, " "));}if (err.stack) {println(err.stack.replace(/^/gm, " "));}- };+ }}-/**- * Inherit from `TAPProducer.prototype`.- */-inherits(TAP12Producer, TAPProducer);-/*** @summary* Constructs a new TAP13Producer.@@ -255,21 +238,21 @@ inherits(TAP12Producer, TAPProducer);* @extends TAPProducer* @see {@link https://testanything.org/tap-version-13-specification.html|Specification}*/-function TAP13Producer() {+class TAP13Producer extends TAPProducer {/*** Writes the TAP version to reporter output stream.* @override*/- this.writeVersion = function () {+ writeVersion() {println("TAP version 13");- };+ }/*** Writes that test failed to reporter output stream, with error formatting.* @override*/- this.writeFail = function (n, test, err) {- TAPProducer.prototype.writeFail.call(this, n, test, err);+ writeFail(n, test, err) {+ super.writeFail(n, test, err);var emitYamlBlock = err.message != null || err.stack != null;if (emitYamlBlock) {println(indent(1) + "---");@@ -283,16 +266,11 @@ function TAP13Producer() {}println(indent(1) + "...");}- };-- function indent(level) {- return Array(level + 1).join(" ");}}-/**- * Inherit from `TAPProducer.prototype`.- */-inherits(TAP13Producer, TAPProducer);+function indent(level) {+ return Array(level + 1).join(" ");+}-TAP.description = "TAP-compatible output";+exports = module.exports = TAP;diff --git a/lib/reporters/xunit.js b/lib/reporters/xunit.jsindex 0eb48fb6..a7129a3d 100644--- a/lib/reporters/xunit.js+++ b/lib/reporters/xunit.js@@ -24,7 +24,6 @@ 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 inherits = utils.inherits;var escape = utils.escape;/**@@ -32,167 +31,159 @@ var escape = utils.escape;*/var Date = global.Date;-/**- * Expose `XUnit`.- */+class XUnit extends Base {+ static description = "XUnit-compatible XML output";++ /**+ * Constructs a new `XUnit` reporter instance.+ *+ * @public+ * @memberof Mocha.reporters+ * @extends Mocha.reporters.Base+ * @param {Runner} runner - Instance triggers reporter actions.+ * @param {Object} [options] - runner options+ */+ constructor(runner, options) {+ super(runner, options);++ var stats = this.stats;+ var tests = [];+ var self = this;++ // the name of the test suite, as it will appear in the resulting XML file+ var suiteName;++ // the default name of the test suite if none is provided+ 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");+ }++ fs.mkdirSync(path.dirname(options.reporterOptions.output), {+ recursive: true,+ });+ self.fileStream = fs.createWriteStream(options.reporterOptions.output);+ }-exports = module.exports = XUnit;+ // get the suite name from the reporter options (if provided)+ suiteName = options.reporterOptions.suiteName;+ }-/**- * Constructs a new `XUnit` reporter instance.- *- * @public- * @class- * @memberof Mocha.reporters- * @extends Mocha.reporters.Base- * @param {Runner} runner - Instance triggers reporter actions.- * @param {Object} [options] - runner options- */-function XUnit(runner, options) {- Base.call(this, runner, options);+ // fall back to the default suite name+ suiteName = suiteName || DEFAULT_SUITE_NAME;- var stats = this.stats;- var tests = [];- var self = this;+ runner.on(EVENT_TEST_PENDING, function (test) {+ tests.push(test);+ });- // the name of the test suite, as it will appear in the resulting XML file- var suiteName;+ runner.on(EVENT_TEST_PASS, function (test) {+ tests.push(test);+ });- // the default name of the test suite if none is provided- var DEFAULT_SUITE_NAME = "Mocha Tests";+ runner.on(EVENT_TEST_FAIL, function (test) {+ tests.push(test);+ });- if (options && options.reporterOptions) {- if (options.reporterOptions.output) {- if (!fs.createWriteStream) {- throw createUnsupportedError("file output not supported in browser");- }+ runner.once(EVENT_RUN_END, function () {+ self.write(+ tag(+ "testsuite",+ {+ name: suiteName,+ tests: stats.tests,+ failures: 0,+ errors: stats.failures,+ skipped: stats.tests - stats.failures - stats.passes,+ timestamp: new Date().toUTCString(),+ time: stats.duration / 1000 || 0,+ },+ false,+ ),+ );- fs.mkdirSync(path.dirname(options.reporterOptions.output), {- recursive: true,+ tests.forEach(function (t) {+ self.test(t, options);});- self.fileStream = fs.createWriteStream(options.reporterOptions.output);- }-- // get the suite name from the reporter options (if provided)- suiteName = options.reporterOptions.suiteName;- }- // fall back to the default suite name- suiteName = suiteName || DEFAULT_SUITE_NAME;-- runner.on(EVENT_TEST_PENDING, function (test) {- tests.push(test);- });-- runner.on(EVENT_TEST_PASS, function (test) {- tests.push(test);- });-- runner.on(EVENT_TEST_FAIL, function (test) {- tests.push(test);- });-- runner.once(EVENT_RUN_END, function () {- self.write(- tag(- "testsuite",- {- name: suiteName,- tests: stats.tests,- failures: 0,- errors: stats.failures,- skipped: stats.tests - stats.failures - stats.passes,- timestamp: new Date().toUTCString(),- time: stats.duration / 1000 || 0,- },- false,- ),- );-- tests.forEach(function (t) {- self.test(t, options);+ self.write("</testsuite>");});+ }- self.write("</testsuite>");- });-}--/**- * Inherit from `Base.prototype`.- */-inherits(XUnit, Base);--/**- * Override done to close the stream (if it's a file).- *- * @param failures- * @param {Function} fn- */-XUnit.prototype.done = function (failures, fn) {- if (this.fileStream) {- this.fileStream.end(function () {+ /**+ * Override done to close the stream (if it's a file).+ *+ * @param failures+ * @param {Function} fn+ */+ done(failures, fn) {+ if (this.fileStream) {+ this.fileStream.end(function () {+ fn(failures);+ });+ } else {fn(failures);- });- } else {- fn(failures);+ }}-};-/**- * Write out the given line.- *- * @param {string} line- */-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");- } else {- Base.consoleLog(line);+ /**+ * Write out the given line.+ *+ * @param {string} line+ */+ write(line) {+ if (this.fileStream) {+ this.fileStream.write(line + "\n");+ } else if (typeof process === "object" && process.stdout) {+ process.stdout.write(line + "\n");+ } else {+ Base.consoleLog(line);+ }}-};-/**- * Output tag for the given `test.`- *- * @param {Test} test- */-XUnit.prototype.test = function (test, options) {- Base.useColors = false;-- var attrs = {- classname: test.parent.fullTitle(),- name: test.title,- file: testFilePath(test.file, options),- 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)- : "";- this.write(- tag(- "testcase",- attrs,- false,+ /**+ * Output tag for the given `test.`+ *+ * @param {Test} test+ */+ test(test, options) {+ Base.useColors = false;++ var attrs = {+ classname: test.parent.fullTitle(),+ name: test.title,+ file: testFilePath(test.file, options),+ 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)+ : "";+ this.write(tag(- "failure",- {},+ "testcase",+ attrs,false,- escape(err.message) + escape(diff) + "\n" + escape(err.stack),+ tag(+ "failure",+ {},+ false,+ escape(err.message) + escape(diff) + "\n" + escape(err.stack),+ ),),- ),- );- } else if (test.isPending()) {- this.write(tag("testcase", attrs, false, tag("skipped", {}, true)));- } else {- this.write(tag("testcase", attrs, true));+ );+ } else if (test.isPending()) {+ this.write(tag("testcase", attrs, false, tag("skipped", {}, true)));+ } else {+ this.write(tag("testcase", attrs, true));+ }}-};+}/*** HTML tag helper.@@ -233,4 +224,4 @@ function testFilePath(filepath, options) {return filepath;}-XUnit.description = "XUnit-compatible XML output";+exports = module.exports = XUnit;diff --git a/test/reporters/doc.spec.js b/test/reporters/doc.spec.jsindex ac55de55..da543ebe 100644--- a/test/reporters/doc.spec.js+++ b/test/reporters/doc.spec.js@@ -6,7 +6,7 @@ var reporters = require("../../").reporters;var Doc = reporters.Doc;var createMockRunner = helpers.createMockRunner;-var makeRunReporter = helpers.createRunReporterFunction;+var createRunReporterFunction = helpers.createRunReporterFunction;var EVENT_SUITE_BEGIN = events.EVENT_SUITE_BEGIN;var EVENT_SUITE_END = events.EVENT_SUITE_END;@@ -16,7 +16,7 @@ var EVENT_TEST_PASS = events.EVENT_TEST_PASS;describe("Doc reporter", function () {var runner;var options = {};- var runReporter = makeRunReporter(Doc);+ var runReporter = createRunReporterFunction(Doc);afterEach(function () {runner = null;@@ -32,7 +32,7 @@ describe("Doc reporter", function () {title: expectedTitle,};- it("should log html with indents and expected title", function () {+ it("should log html with indents and expected title", async function () {runner = createMockRunner("suite",EVENT_SUITE_BEGIN,@@ -40,7 +40,7 @@ describe("Doc reporter", function () {null,suite,);- var stdout = runReporter(this, runner, options);+ var { stdout } = await runReporter({}, runner, options);var expectedArray = [' <section class="suite">\n'," <h1>" + expectedTitle + "</h1>\n",@@ -49,7 +49,7 @@ describe("Doc reporter", function () {expect(stdout, "to equal", expectedArray);});- it("should escape title where necessary", function () {+ it("should escape title where necessary", async function () {var suite = {root: false,title: unescapedTitle,@@ -64,7 +64,7 @@ describe("Doc reporter", function () {null,suite,);- var stdout = runReporter(this, runner, options);+ var { stdout } = await runReporter({}, runner, options);var expectedArray = [' <section class="suite">\n'," <h1>" + expectedTitle + "</h1>\n",@@ -79,7 +79,7 @@ describe("Doc reporter", function () {root: true,};- it("should not log any html", function () {+ it("should not log any html", async function () {runner = createMockRunner("suite",EVENT_SUITE_BEGIN,@@ -87,7 +87,7 @@ describe("Doc reporter", function () {null,suite,);- var stdout = runReporter(this, runner, options);+ var { stdout } = await runReporter({}, runner, options);expect(stdout, "to be empty");});});@@ -99,7 +99,7 @@ describe("Doc reporter", function () {root: false,};- it("should log expected html with indents", function () {+ it("should log expected html with indents", async function () {runner = createMockRunner("suite end",EVENT_SUITE_END,@@ -107,7 +107,7 @@ describe("Doc reporter", function () {null,suite,);- var stdout = runReporter(this, runner, options);+ var { stdout } = await runReporter({}, runner, options);var expectedArray = [" </dl>\n", "</section>\n"];expect(stdout, "to equal", expectedArray);});@@ -118,7 +118,7 @@ describe("Doc reporter", function () {root: true,};- it("should not log any html", function () {+ it("should not log any html", async function () {runner = createMockRunner("suite end",EVENT_SUITE_END,@@ -126,7 +126,7 @@ describe("Doc reporter", function () {null,suite,);- var stdout = runReporter(this, runner, options);+ var { stdout } = await runReporter({}, runner, options);expect(stdout, "to be empty");});});@@ -145,9 +145,9 @@ describe("Doc reporter", function () {},};- it("should log html with indents, expected title, and body", function () {+ it("should log html with indents, expected title, and body", async function () {runner = createMockRunner("pass", EVENT_TEST_PASS, null, null, test);- var stdout = runReporter(this, runner, options);+ var { stdout } = await runReporter({}, runner, options);var expectedArray = [" <dt>" + expectedTitle + "</dt>\n"," <dt>" + expectedFile + "</dt>\n",@@ -156,7 +156,7 @@ describe("Doc reporter", function () {expect(stdout, "to equal", expectedArray);});- it("should escape title and body where necessary", function () {+ it("should escape title and body where necessary", async function () {var unescapedTitle = "<div>" + expectedTitle + "</div>";var unescapedFile = "<div>" + expectedFile + "</div>";var unescapedBody = "<div>" + expectedBody + "</div>";@@ -171,7 +171,7 @@ describe("Doc reporter", function () {var expectedEscapedBody ="<div>" + expectedBody + "</div>";runner = createMockRunner("pass", EVENT_TEST_PASS, null, null, test);- var stdout = runReporter(this, runner, options);+ var { stdout } = await runReporter({}, runner, options);var expectedArray = [" <dt>" + expectedEscapedTitle + "</dt>\n"," <dt>" + expectedEscapedFile + "</dt>\n",@@ -195,7 +195,7 @@ describe("Doc reporter", function () {},};- it("should log html with indents, expected title, body, and error", function () {+ it("should log html with indents, expected title, body, and error", async function () {runner = createMockRunner("fail two args",EVENT_TEST_FAIL,@@ -204,7 +204,7 @@ describe("Doc reporter", function () {test,expectedError,);- var stdout = runReporter(this, runner, options);+ var { stdout } = await runReporter({}, runner, options);var expectedArray = [' <dt class="error">' + expectedTitle + "</dt>\n",' <dt class="error">' + expectedFile + "</dt>\n",@@ -216,7 +216,7 @@ describe("Doc reporter", function () {expect(stdout, "to equal", expectedArray);});- it("should escape title, body, and error where necessary", function () {+ it("should escape title, body, and error where necessary", async function () {var unescapedTitle = "<div>" + expectedTitle + "</div>";var unescapedFile = "<div>" + expectedFile + "</div>";var unescapedBody = "<div>" + expectedBody + "</div>";@@ -241,7 +241,7 @@ describe("Doc reporter", function () {test,unescapedError,);- var stdout = runReporter(this, runner, options);+ var { stdout } = await runReporter({}, runner, options);var expectedArray = [' <dt class="error">' + expectedEscapedTitle + "</dt>\n",' <dt class="error">' + expectedEscapedFile + "</dt>\n",diff --git a/test/reporters/dot.spec.js b/test/reporters/dot.spec.jsindex c04827ff..4adef79d 100644--- a/test/reporters/dot.spec.js+++ b/test/reporters/dot.spec.js@@ -8,7 +8,7 @@ var reporters = require("../../").reporters;var Base = reporters.Base;var Dot = reporters.Dot;var createMockRunner = helpers.createMockRunner;-var makeRunReporter = helpers.createRunReporterFunction;+var createRunReporterFunction = helpers.createRunReporterFunction;var EVENT_RUN_BEGIN = events.EVENT_RUN_BEGIN;var EVENT_RUN_END = events.EVENT_RUN_END;@@ -18,7 +18,7 @@ var EVENT_TEST_PENDING = events.EVENT_TEST_PENDING;describe("Dot reporter", function () {var windowWidthStub;- var runReporter = makeRunReporter(Dot);+ var runReporter = createRunReporterFunction(Dot);var noop = function () {};beforeEach(function () {@@ -35,10 +35,10 @@ describe("Dot reporter", function () {describe("event handlers", function () {describe("on 'start' event", function () {- it("should write a newline", function () {+ it("should write a newline", async function () {var runner = createMockRunner("start", EVENT_RUN_BEGIN);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter({ epilogue: noop }, runner, options);sinon.restore();var expectedArray = ["\n"];@@ -52,10 +52,14 @@ describe("Dot reporter", function () {windowWidthStub.value(2);});- it("should write a newline followed by a comma", function () {+ it("should write a newline followed by a comma", async function () {var runner = createMockRunner("pending", EVENT_TEST_PENDING);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter(+ { epilogue: noop },+ runner,+ options,+ );sinon.restore();var expectedArray = ["\n ", "pending_" + Base.symbols.comma];@@ -64,10 +68,14 @@ describe("Dot reporter", function () {});describe("when window width is less than or equal to 1", function () {- it("should write a comma", function () {+ it("should write a comma", async function () {var runner = createMockRunner("pending", EVENT_TEST_PENDING);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter(+ { epilogue: noop },+ runner,+ options,+ );sinon.restore();var expectedArray = ["pending_" + Base.symbols.comma];@@ -90,7 +98,7 @@ describe("Dot reporter", function () {});describe("when test speed is fast", function () {- it("should write a newline followed by a dot", function () {+ it("should write a newline followed by a dot", async function () {var runner = createMockRunner("pass",EVENT_TEST_PASS,@@ -99,7 +107,11 @@ describe("Dot reporter", function () {test,);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter(+ { epilogue: noop },+ runner,+ options,+ );sinon.restore();expect(test.speed, "to equal", "fast");@@ -111,7 +123,7 @@ describe("Dot reporter", 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 () {+ it("should write a grey dot", async function () {var runner = createMockRunner("pass",EVENT_TEST_PASS,@@ -120,7 +132,11 @@ describe("Dot reporter", function () {test,);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter(+ { epilogue: noop },+ runner,+ options,+ );sinon.restore();expect(test.speed, "to equal", "fast");@@ -130,7 +146,7 @@ describe("Dot reporter", function () {});describe("when test speed is medium", function () {- it("should write a yellow dot", function () {+ it("should write a yellow dot", async function () {test.duration = 2;var runner = createMockRunner("pass",@@ -140,7 +156,11 @@ describe("Dot reporter", function () {test,);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter(+ { epilogue: noop },+ runner,+ options,+ );sinon.restore();expect(test.speed, "to equal", "medium");@@ -150,7 +170,7 @@ describe("Dot reporter", function () {});describe("when test speed is slow", function () {- it("should write a bright yellow dot", function () {+ it("should write a bright yellow dot", async function () {test.duration = 3;var runner = createMockRunner("pass",@@ -160,7 +180,11 @@ describe("Dot reporter", function () {test,);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter(+ { epilogue: noop },+ runner,+ options,+ );sinon.restore();expect(test.speed, "to equal", "slow");@@ -183,7 +207,7 @@ describe("Dot reporter", 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", async function () {var runner = createMockRunner("fail",EVENT_TEST_FAIL,@@ -192,7 +216,11 @@ describe("Dot reporter", function () {test,);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter(+ { epilogue: noop },+ runner,+ options,+ );sinon.restore();var expectedArray = ["\n ", "fail_" + Base.symbols.bang];@@ -201,7 +229,7 @@ describe("Dot reporter", function () {});describe("when window width is less than or equal to 1", function () {- it("should write an exclamation mark", function () {+ it("should write an exclamation mark", async function () {var runner = createMockRunner("fail",EVENT_TEST_FAIL,@@ -210,7 +238,11 @@ describe("Dot reporter", function () {test,);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter(+ { epilogue: noop },+ runner,+ options,+ );sinon.restore();var expectedArray = ["fail_" + Base.symbols.bang];@@ -220,13 +252,13 @@ describe("Dot reporter", function () {});describe("on 'end' event", function () {- it("should call epilogue", function () {+ it("should call epilogue", async function () {var runner = createMockRunner("end", EVENT_RUN_END);var fakeThis = {epilogue: sinon.stub(),};var options = {};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);sinon.restore();expect(fakeThis.epilogue.called, "to be true");diff --git a/test/reporters/helpers.js b/test/reporters/helpers.jsindex e7eabf30..859a4118 100644--- a/test/reporters/helpers.js+++ b/test/reporters/helpers.js@@ -34,6 +34,14 @@ function createMockRunner(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {return mockRunner;}+function afterTick(callback) {+ return async function (...args) {+ // Waiting a tick allows any extensions to be assigned in the constructor+ await Promise.resolve();+ callback(...args);+ };+}+/*** Creates an event handler function to be used by the runner.*@@ -54,11 +62,11 @@ function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {case "start":case "pending":case "end":- return function (event, callback) {+ return afterTick(function (event, callback) {if (event === ifStr1) {callback();}- };+ });case "pending test":case "pass":case "fail":@@ -66,32 +74,32 @@ function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {case "suite end":case "test end":test = arg1;- return function (event, callback) {+ return afterTick(function (event, callback) {if (event === ifStr1) {callback(test);}- };+ });case "fail two args":test = arg1;var expectedError = arg2;- return function (event, callback) {+ return afterTick(function (event, callback) {if (event === ifStr1) {callback(test, expectedError);}- };+ });case "start test":test = arg1;- return function (event, callback) {+ return afterTick(function (event, callback) {if (event === ifStr1) {callback();}if (event === ifStr2) {callback(test);}- };+ });case "suite suite end":var expectedSuite = arg1;- return function (event, callback) {+ return afterTick(function (event, callback) {if (event === ifStr1) {callback(expectedSuite);}@@ -101,30 +109,30 @@ function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {if (event === ifStr3) {callback();}- };+ });case "pass end":test = arg1;- return function (event, callback) {+ return afterTick(function (event, callback) {if (event === ifStr1) {callback(test);}if (event === ifStr2) {callback();}- };+ });case "test end fail":test = arg1;var error = arg2;- return function (event, callback) {+ return afterTick(function (event, callback) {if (event === ifStr1) {callback();}if (event === ifStr2) {callback(test, error);}- };+ });case "fail end pass":- return function (event, callback) {+ return afterTick(function (event, callback) {test = arg1;if (event === ifStr1) {callback(test, {});@@ -135,7 +143,7 @@ function createRunnerFunction(runStr, ifStr1, ifStr2, ifStr3, arg1, arg2) {if (event === ifStr3) {callback(test);}- };+ });default:throw createUnsupportedError("This function does not support the runner string specified.",@@ -184,20 +192,20 @@ function makeExpectedTest(/*** Creates closure with reference to the reporter class constructor.*- * @param {Function} ctor - Reporter class constructor+ * @param {Function} ReporterClass - Reporter class constructor* @return {createRunReporterFunction~runReporter}*/-function createRunReporterFunction(ctor) {+function createRunReporterFunction(ReporterClass) {/*** Run reporter using stream reassignment to capture output.*- * @param {Object} stubSelf - Reporter-like stub instance+ * @param {object} extensions - Any extra properties to add to the instance.* @param {Runner} runner - Mock instance* @param {Object} [options] - Reporter configuration settings* @param {boolean} [tee=false] - Whether to echo output to screen* @return {string[]} Lines of output written to `stdout`*/- var runReporter = function (stubSelf, runner, options, tee) {+ var runReporter = async function (extensions, runner, options, tee) {var origStdoutWrite = process.stdout.write;var stdoutWriteStub = sinon.stub(process.stdout, "write");var stdout = [];@@ -212,19 +220,28 @@ function createRunReporterFunction(ctor) {// Reassign stream in order to make a copy of all reporter outputstdoutWriteStub.callsFake(gather);- // Give `stubSelf` access to `ctor` prototype chain- Object.setPrototypeOf(stubSelf, ctor.prototype);+ // The new instance will have all of `extensions` and still be a `ReporterClass`+ var ReporterClassExtended = class extends ReporterClass {+ constructor(...args) {+ super(...args);+ Object.assign(this, extensions);+ }+ };++ var reporter;try {- // Invoke reporter- ctor.call(stubSelf, runner, options);+ reporter = new ReporterClassExtended(runner, options);++ // Waiting a tick allows any events to fire before this function resolves+ await Promise.resolve();} finally {// Revert stream reassignment here so reporter output// can't be corrupted if any test assertions throwstdoutWriteStub.restore();}- return stdout;+ return { reporter, stdout };};return runReporter;diff --git a/test/reporters/json-stream.spec.js b/test/reporters/json-stream.spec.jsindex 67954865..059da3c3 100644--- a/test/reporters/json-stream.spec.js+++ b/test/reporters/json-stream.spec.js@@ -38,12 +38,12 @@ describe("JSON Stream reporter", function () {describe("event handlers", function () {describe("on 'start' event", function () {- it("should write stringified start with expected total", function () {+ it("should write stringified start with expected total", async function () {var runner = createMockRunner("start", EVENT_RUN_BEGIN);var expectedTotal = 12;runner.total = expectedTotal;var options = {};- var stdout = runReporter({}, runner, options);+ var { stdout } = await runReporter({}, runner, options);expect(stdout[0],@@ -54,7 +54,7 @@ describe("JSON Stream reporter", function () {});describe("on 'pass' event", function () {- it("should write stringified test data", function () {+ it("should write stringified test data", async function () {var runner = createMockRunner("pass",EVENT_TEST_PASS,@@ -63,7 +63,7 @@ describe("JSON Stream reporter", function () {expectedTest,);var options = {};- var stdout = runReporter({}, runner, options);+ var { stdout } = await runReporter({}, runner, options);expect(stdout[0],@@ -87,7 +87,7 @@ describe("JSON Stream reporter", function () {describe("on 'fail' event", function () {describe("when error stack exists", function () {- it("should write stringified test data with error data", function () {+ it("should write stringified test data with error data", async function () {expectedError.stack = expectedErrorStack;var runner = createMockRunner("fail two args",@@ -98,7 +98,7 @@ describe("JSON Stream reporter", function () {expectedError,);var options = {};- var stdout = runReporter({}, runner, options);+ var { stdout } = await runReporter({}, runner, options);expect(stdout[0],@@ -125,7 +125,7 @@ describe("JSON Stream reporter", function () {});describe("when error stack does not exist", function () {- it("should write stringified test data with error data", function () {+ it("should write stringified test data with error data", async function () {expectedError.stack = null;var runner = createMockRunner("fail two args",@@ -136,7 +136,7 @@ describe("JSON Stream reporter", function () {expectedError,);var options = {};- var stdout = runReporter(this, runner, options);+ var { stdout } = await runReporter(this, runner, options);expect(stdout[0],@@ -162,10 +162,10 @@ describe("JSON Stream reporter", function () {});describe("on 'end' event", function () {- it("should write summary statistics", function () {+ it("should write summary statistics", async function () {var runner = createMockRunner("end", EVENT_RUN_END);var options = {};- var stdout = runReporter(this, runner, options);+ var { stdout } = await runReporter(this, runner, options);expect(stdout[0], "to match", /end/);});});diff --git a/test/reporters/landing.spec.js b/test/reporters/landing.spec.jsindex 1635a3ee..c64fbf0a 100644--- a/test/reporters/landing.spec.js+++ b/test/reporters/landing.spec.js@@ -43,23 +43,23 @@ describe("Landing reporter", function () {describe("event handlers", function () {describe("on 'start' event", function () {- it("should write newlines", function () {+ it("should write newlines", async function () {sinon.stub(Base.cursor, "hide");var runner = createMockRunner("start", EVENT_RUN_BEGIN);var options = {};- var stdout = runReporter({}, runner, options);+ var { stdout } = await runReporter({}, runner, options);sinon.restore();expect(stdout[0], "to equal", "\n\n\n ");});- it("should call cursor hide", function () {+ it("should call cursor hide", async function () {var hideCursorStub = sinon.stub(Base.cursor, "hide");var runner = createMockRunner("start", EVENT_RUN_BEGIN);var options = {};- runReporter({}, runner, options);+ await runReporter({}, runner, options);sinon.restore();expect(hideCursorStub.called, "to be true");@@ -68,7 +68,7 @@ describe("Landing reporter", function () {describe("on 'test end' event", function () {describe("when test passes", function () {- it("should write expected landing strip", function () {+ it("should write expected landing strip", async function () {var test = {state: STATE_PASSED,};@@ -80,7 +80,7 @@ describe("Landing reporter", function () {test,);var options = {};- var stdout = runReporter({}, runner, options);+ var { stdout } = await runReporter({}, runner, options);sinon.restore();expect(stdout, "to equal", expectedArray);@@ -88,7 +88,7 @@ describe("Landing reporter", function () {});describe("when test fails", function () {- it("should write expected landing strip", function () {+ it("should write expected landing strip", async function () {var test = {state: STATE_FAILED,};@@ -101,7 +101,7 @@ describe("Landing reporter", function () {);runner.total = 12;var options = {};- var stdout = runReporter({}, runner, options);+ var { stdout } = await runReporter({}, runner, options);sinon.restore();expect(stdout, "to equal", expectedArray);@@ -110,7 +110,7 @@ describe("Landing reporter", function () {});describe("on 'end' event", function () {- it("should call cursor show and epilogue", function () {+ it("should call cursor show and epilogue", async function () {var showCursorStub = sinon.stub(Base.cursor, "show");var fakeThis = {@@ -118,7 +118,7 @@ describe("Landing reporter", function () {};var runner = createMockRunner("end", EVENT_RUN_END);var options = {};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);sinon.restore();expect(fakeThis.epilogue.calledOnce, "to be true");diff --git a/test/reporters/list.spec.js b/test/reporters/list.spec.jsindex 8bff0c57..9c7b2684 100644--- a/test/reporters/list.spec.js+++ b/test/reporters/list.spec.js@@ -40,7 +40,7 @@ describe("List reporter", 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", async function () {var runner = createMockRunner("start test",EVENT_RUN_BEGIN,@@ -52,7 +52,7 @@ describe("List reporter", function () {var fakeThis = {epilogue: noop,};- var stdout = runReporter(fakeThis, runner, options);+ var { stdout } = await runReporter(fakeThis, runner, options);sinon.restore();var startString = "\n";@@ -63,7 +63,7 @@ describe("List reporter", function () {});describe("on 'pending' event", function () {- it("should write expected title", function () {+ it("should write expected title", async function () {var runner = createMockRunner("pending test",EVENT_TEST_PENDING,@@ -75,7 +75,7 @@ describe("List reporter", function () {var fakeThis = {epilogue: noop,};- var stdout = runReporter(fakeThis, runner, options);+ var { stdout } = await runReporter(fakeThis, runner, options);sinon.restore();expect(stdout[0], "to equal", " - " + expectedTitle + "\n");@@ -89,7 +89,7 @@ describe("List reporter", function () {crStub = sinon.stub(Base.cursor, "CR").callsFake(noop);});- it("should call cursor CR", function () {+ it("should call cursor CR", async function () {var runner = createMockRunner("pass",EVENT_TEST_PASS,@@ -101,13 +101,13 @@ describe("List reporter", function () {var fakeThis = {epilogue: noop,};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);sinon.restore();expect(crStub.called, "to be true");});- it("should write expected symbol, title, and duration", function () {+ it("should write expected symbol, title, and duration", async function () {var expectedOkSymbol = "OK";sinon.stub(Base.symbols, "ok").value(expectedOkSymbol);@@ -122,7 +122,7 @@ describe("List reporter", function () {var fakeThis = {epilogue: noop,};- var stdout = runReporter(fakeThis, runner, options);+ var { stdout } = await runReporter(fakeThis, runner, options);sinon.restore();expect(@@ -146,7 +146,7 @@ describe("List reporter", function () {crStub = sinon.stub(Base.cursor, "CR").callsFake(noop);});- it("should call cursor CR", function () {+ it("should call cursor CR", async function () {var runner = createMockRunner("fail",EVENT_TEST_FAIL,@@ -158,13 +158,13 @@ describe("List reporter", function () {var fakeThis = {epilogue: noop,};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);sinon.restore();expect(crStub.called, "to be true");});- it("should write expected error number and title", function () {+ it("should write expected error number and title", async function () {var expectedErrorCount = 1;var runner = createMockRunner("fail",@@ -177,7 +177,7 @@ describe("List reporter", function () {var fakeThis = {epilogue: noop,};- var stdout = runReporter(fakeThis, runner, options);+ var { stdout } = await runReporter(fakeThis, runner, options);sinon.restore();expect(@@ -187,7 +187,7 @@ describe("List reporter", function () {);});- it("should immediately construct fail strings", function () {+ it("should immediately construct fail strings", async function () {var actual = { a: "actual" };var expected = { a: "expected" };var checked = false;@@ -219,7 +219,7 @@ describe("List reporter", function () {var fakeThis = {epilogue: noop,};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);sinon.restore();expect(typeof err.actual, "to be", "string");@@ -228,13 +228,13 @@ describe("List reporter", function () {});describe("on 'end' event", function () {- it("should call epilogue", function () {+ it("should call epilogue", async function () {var runner = createMockRunner("end", EVENT_RUN_END);var options = {};var fakeThis = {epilogue: sinon.spy(),};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);sinon.restore();expect(fakeThis.epilogue.calledOnce, "to be true");diff --git a/test/reporters/markdown.spec.js b/test/reporters/markdown.spec.jsindex c46a563f..e14a8474 100644--- a/test/reporters/markdown.spec.js+++ b/test/reporters/markdown.spec.js@@ -22,7 +22,7 @@ describe("Markdown reporter", function () {describe("event handlers", function () {describe("on 'suite' event", function () {- it("should write expected slugged titles on 'end' event", function () {+ it("should write expected slugged titles on 'end' event", async function () {var expectedSuite = {title: expectedTitle,fullTitle: function () {@@ -47,7 +47,7 @@ describe("Markdown reporter", function () {);runner.suite = expectedSuite;var options = {};- var stdout = runReporter({}, runner, options);+ var { stdout } = await runReporter({}, runner, options);var expectedArray = ["# TOC\n",@@ -68,7 +68,7 @@ describe("Markdown reporter", function () {});describe("on 'pass' event", function () {- it("should write test code inside js code block, on 'end' event", function () {+ it("should write test code inside js code block, on 'end' event", async function () {var expectedSuite = {title: expectedTitle,fullTitle: function () {@@ -100,7 +100,7 @@ describe("Markdown reporter", function () {);runner.suite = expectedSuite;var options = {};- var stdout = runReporter({}, runner, options);+ var { stdout } = await runReporter({}, runner, options);var expectedArray = ["# TOC\n",diff --git a/test/reporters/min.spec.js b/test/reporters/min.spec.jsindex 521ba9a5..74041e83 100644--- a/test/reporters/min.spec.js+++ b/test/reporters/min.spec.js@@ -18,13 +18,13 @@ describe("Min reporter", function () {describe("event handlers", function () {describe("on 'start' event", function () {- it("should clear screen then set cursor position", function () {+ it("should clear screen then set cursor position", async function () {var runner = createMockRunner("start", EVENT_RUN_BEGIN);var options = {};var fakeThis = {epilogue: noop,};- var stdout = runReporter(fakeThis, runner, options);+ var { stdout } = await runReporter(fakeThis, runner, options);var expectedArray = ["\u001b[2J", "\u001b[1;3H"];expect(stdout, "to equal", expectedArray);@@ -32,13 +32,13 @@ describe("Min reporter", function () {});describe("on 'end' event", function () {- it("should call epilogue", function () {+ it("should call epilogue", async function () {var fakeThis = {epilogue: sinon.stub().callsFake(noop),};var runner = createMockRunner("end", EVENT_RUN_END);var options = {};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);expect(fakeThis.epilogue.called, "to be true");});diff --git a/test/reporters/nyan.spec.js b/test/reporters/nyan.spec.jsindex aac0fd47..8be87748 100644--- a/test/reporters/nyan.spec.js+++ b/test/reporters/nyan.spec.js@@ -27,7 +27,7 @@ describe("Nyan reporter", function () {var runReporter = makeRunReporter(NyanCat);describe("on 'start' event", function () {- it("should call draw", function () {+ it("should call draw", async function () {var fakeThis = {draw: sinon.stub().callsFake(noop),generateColors: noop,@@ -35,28 +35,28 @@ describe("Nyan reporter", function () {var runner = createMockRunner("start", EVENT_RUN_BEGIN);var options = {};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);expect(fakeThis.draw.called, "to be true");});});describe("on 'pending' event", function () {- it("should call draw", function () {+ it("should call draw", async function () {var fakeThis = {draw: sinon.stub().callsFake(noop),generateColors: noop,};var runner = createMockRunner("pending", EVENT_TEST_PENDING);var options = {};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);expect(fakeThis.draw.called, "to be true");});});describe("on 'pass' event", function () {- it("should call draw", function () {+ it("should call draw", async function () {var test = {duration: "",slow: noop,@@ -73,14 +73,14 @@ describe("Nyan reporter", function () {test,);var options = {};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);expect(fakeThis.draw.called, "to be true");});});describe("on 'fail' event", function () {- it("should call draw", function () {+ it("should call draw", async function () {var test = {err: "",};@@ -96,14 +96,14 @@ describe("Nyan reporter", function () {test,);var options = {};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);expect(fakeThis.draw.called, "to be true");});});describe("on 'end' event", function () {- it("should call epilogue", function () {+ it("should call epilogue", async function () {var fakeThis = {draw: noop,epilogue: sinon.stub().callsFake(noop),@@ -111,12 +111,12 @@ describe("Nyan reporter", function () {};var runner = createMockRunner("end", EVENT_RUN_END);var options = {};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);expect(fakeThis.epilogue.called, "to be true");});- it("should write numberOfLines amount of newlines", function () {+ it("should write numberOfLines amount of newlines", async function () {var expectedNumberOfLines = 4;var fakeThis = {draw: noop,@@ -125,7 +125,7 @@ describe("Nyan reporter", function () {};var runner = createMockRunner("end", EVENT_RUN_END);var options = {};- var stdout = runReporter(fakeThis, runner, options);+ var { stdout } = await runReporter(fakeThis, runner, options);var isBlankLine = function (value) {return value === "\n";@@ -138,7 +138,7 @@ describe("Nyan reporter", function () {);});- it("should call Base show", function () {+ it("should call Base show", async function () {var showCursorStub = sinon.stub(Base.cursor, "show");var fakeThis = {draw: noop,@@ -147,7 +147,7 @@ describe("Nyan reporter", function () {};var runner = createMockRunner("end", EVENT_RUN_END);var options = {};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);sinon.restore();expect(showCursorStub.called, "to be true");diff --git a/test/reporters/progress.spec.js b/test/reporters/progress.spec.jsindex b4ee7a57..3c953972 100644--- a/test/reporters/progress.spec.js+++ b/test/reporters/progress.spec.js@@ -24,12 +24,12 @@ describe("Progress reporter", function () {describe("event handlers", function () {describe("on 'start' event", function () {- it("should call cursor hide", function () {+ it("should call cursor hide", async function () {var hideCursorStub = sinon.stub(Base.cursor, "hide");var runner = createMockRunner("start", EVENT_RUN_BEGIN);var options = {};- runReporter({}, runner, options);+ await runReporter({}, runner, options);sinon.restore();expect(hideCursorStub.called, "to be true");@@ -38,7 +38,7 @@ describe("Progress reporter", function () {describe("on 'test end' event", function () {describe("when line has changed", function () {- it("should write expected progress of open and close options", function () {+ it("should write expected progress of open and close options", async function () {var crCursorStub = sinon.stub(Base.cursor, "CR").callsFake(noop);sinon.stub(Base, "useColors").value(false);sinon.stub(Base.window, "width").value(5);@@ -59,7 +59,7 @@ describe("Progress reporter", function () {var options = {reporterOptions: expectedOptions,};- var stdout = runReporter({}, runner, options);+ var { stdout } = await runReporter({}, runner, options);sinon.restore();var expectedArray = [@@ -76,7 +76,7 @@ describe("Progress reporter", function () {});describe("when line has not changed", function () {- it("should not write anything", function () {+ it("should not write anything", async function () {sinon.stub(Base, "useColors").value(false);sinon.stub(Base.cursor, "CR").callsFake(noop);sinon.stub(Base.window, "width").value(-3);@@ -85,7 +85,7 @@ describe("Progress reporter", function () {var runner = createMockRunner("test end", EVENT_TEST_END);runner.total = expectedTotal;var options = {};- var stdout = runReporter({}, runner, options);+ var { stdout } = await runReporter({}, runner, options);sinon.restore();expect(stdout, "to equal", []);@@ -94,14 +94,14 @@ describe("Progress reporter", function () {});describe("on 'end' event", function () {- it("should call cursor show and epilogue", function () {+ it("should call cursor show and epilogue", async function () {var showCursorStub = sinon.stub(Base.cursor, "show");var fakeThis = {epilogue: sinon.spy(),};var runner = createMockRunner("end", EVENT_RUN_END);var options = {};- runReporter(fakeThis, runner, options);+ await runReporter(fakeThis, runner, options);sinon.restore();expect(fakeThis.epilogue.calledOnce, "to be true");diff --git a/test/reporters/spec.spec.js b/test/reporters/spec.spec.jsindex 1a0dacdf..e77dd3af 100644--- a/test/reporters/spec.spec.js+++ b/test/reporters/spec.spec.js@@ -30,7 +30,7 @@ describe("Spec reporter", function () {describe("event handlers", function () {describe("on 'suite' event", function () {- it("should return title", function () {+ it("should return title", async function () {var suite = {title: expectedTitle,};@@ -42,7 +42,7 @@ describe("Spec reporter", function () {suite,);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter({ epilogue: noop }, runner, options);sinon.restore();var expectedArray = [expectedTitle + "\n"];@@ -51,7 +51,7 @@ describe("Spec reporter", function () {});describe("on 'pending' event", function () {- it("should return title", function () {+ it("should return title", async function () {var suite = {title: expectedTitle,};@@ -63,7 +63,7 @@ describe("Spec reporter", function () {suite,);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter({ epilogue: noop }, runner, options);sinon.restore();var expectedArray = [" - " + expectedTitle + "\n"];@@ -73,7 +73,7 @@ describe("Spec reporter", function () {describe("on 'pass' event", function () {describe("when test speed is slow", function () {- it("should return expected tick, title, and duration", function () {+ it("should return expected tick, title, and duration", async function () {var expectedDuration = 2;var test = {title: expectedTitle,@@ -90,7 +90,11 @@ describe("Spec reporter", function () {test,);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter(+ { epilogue: noop },+ runner,+ options,+ );sinon.restore();var expectedString =@@ -107,7 +111,7 @@ describe("Spec reporter", function () {});describe("when test speed is fast", function () {- it("should return expected tick, title without a duration", function () {+ it("should return expected tick, title without a duration", async function () {var expectedDuration = 1;var test = {title: expectedTitle,@@ -124,7 +128,11 @@ describe("Spec reporter", function () {test,);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter(+ { epilogue: noop },+ runner,+ options,+ );sinon.restore();var expectedString =@@ -135,7 +143,7 @@ describe("Spec reporter", function () {});describe("on 'fail' event", function () {- it("should return title and function count", function () {+ it("should return title and function count", async function () {var functionCount = 1;var test = {title: expectedTitle,@@ -148,7 +156,7 @@ describe("Spec reporter", function () {test,);var options = {};- var stdout = runReporter({ epilogue: noop }, runner, options);+ var { stdout } = await runReporter({ epilogue: noop }, runner, options);sinon.restore();var expectedArray = [diff --git a/test/reporters/tap.spec.js b/test/reporters/tap.spec.jsindex fdd2ced2..4fd4ccaa 100644--- a/test/reporters/tap.spec.js+++ b/test/reporters/tap.spec.js@@ -42,10 +42,10 @@ describe("TAP reporter", function () {var expectedSuite = "some suite";var stdout = [];- before(function () {+ before(async function () {var runner = createMockRunner("start", EVENT_RUN_BEGIN);runner.suite = expectedSuite;- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should not write a TAP specification version", function () {@@ -56,7 +56,7 @@ describe("TAP reporter", function () {describe("on 'pending' event", function () {var stdout = [];- before(function () {+ before(async function () {var test = createTest();var runner = createMockRunner("start test",@@ -66,7 +66,7 @@ describe("TAP reporter", function () {test,);runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message including count and title", function () {@@ -79,7 +79,7 @@ describe("TAP reporter", function () {describe("on 'pass' event", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var runner = createMockRunner("start test",@@ -89,7 +89,7 @@ describe("TAP reporter", function () {test,);runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message including count and title", function () {@@ -106,7 +106,7 @@ describe("TAP reporter", function () {describe("when 'error' has only message", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var error = {message: expectedErrorMessage,@@ -127,7 +127,7 @@ describe("TAP reporter", function () {}};runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message and error message", function () {@@ -142,7 +142,7 @@ describe("TAP reporter", function () {describe("when 'error' has only stack", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var error = {stack: expectedStack,@@ -156,7 +156,7 @@ describe("TAP reporter", function () {error,);runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message and stack", function () {@@ -171,7 +171,7 @@ describe("TAP reporter", function () {describe("when 'error' has both message and stack", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var error = {stack: expectedStack,@@ -193,7 +193,7 @@ describe("TAP reporter", function () {}};runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message, error message, and stack", function () {@@ -209,7 +209,7 @@ describe("TAP reporter", function () {describe("when 'error' has neither message nor stack", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var error = {};var runner = createMockRunner(@@ -228,7 +228,7 @@ describe("TAP reporter", function () {}};runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message only", function () {@@ -243,7 +243,7 @@ describe("TAP reporter", function () {describe("on 'end' event", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var runner = createMockRunner("fail end pass",@@ -253,7 +253,7 @@ describe("TAP reporter", function () {test,);runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write total tests, passes, failures, & plan", function () {@@ -286,10 +286,10 @@ describe("TAP reporter", function () {var expectedSuite = "some suite";var stdout;- before(function () {+ before(async function () {var runner = createMockRunner("start", EVENT_RUN_BEGIN);runner.suite = expectedSuite;- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write the TAP specification version", function () {@@ -302,7 +302,7 @@ describe("TAP reporter", function () {describe("on 'pending' event", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var runner = createMockRunner("start test",@@ -312,7 +312,7 @@ describe("TAP reporter", function () {test,);runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message including count and title", function () {@@ -325,7 +325,7 @@ describe("TAP reporter", function () {describe("on 'pass' event", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var runner = createMockRunner("start test",@@ -335,7 +335,7 @@ describe("TAP reporter", function () {test,);runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message including count and title", function () {@@ -352,7 +352,7 @@ describe("TAP reporter", function () {describe("when 'error' has only message", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var error = {message: expectedErrorMessage,@@ -373,7 +373,7 @@ describe("TAP reporter", function () {}};runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message and error message", function () {@@ -391,7 +391,7 @@ describe("TAP reporter", function () {describe("when 'error' has only stack", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var error = {stack: expectedStack,@@ -405,7 +405,7 @@ describe("TAP reporter", function () {error,);runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message and stack", function () {@@ -423,7 +423,7 @@ describe("TAP reporter", function () {describe("when 'error' has both message and stack", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var error = {stack: expectedStack,@@ -445,7 +445,7 @@ describe("TAP reporter", function () {}};runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message, error message, and stack", function () {@@ -465,7 +465,7 @@ describe("TAP reporter", function () {describe("when 'error' has neither message nor stack", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var error = {};var runner = createMockRunner(@@ -484,7 +484,7 @@ describe("TAP reporter", function () {}};runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write expected message only", function () {@@ -499,7 +499,7 @@ describe("TAP reporter", function () {describe("on 'end' event", function () {var stdout;- before(function () {+ before(async function () {var test = createTest();var runner = createMockRunner("fail end pass",@@ -509,7 +509,7 @@ describe("TAP reporter", function () {test,);runner.suite = "";- stdout = runReporter({}, runner, options);+ ({ stdout } = await runReporter({}, runner, options));});it("should write total tests, passes, failures & plan", function () {diff --git a/test/reporters/xunit.spec.js b/test/reporters/xunit.spec.jsindex 57eaa0a5..9301358d 100644--- a/test/reporters/xunit.spec.js+++ b/test/reporters/xunit.spec.js@@ -1,8 +1,8 @@"use strict";-var EventEmitter = require("node:events").EventEmitter;-var fs = require("node:fs");-var path = require("node:path");+var EventEmitter = require("events").EventEmitter;+var fs = require("fs");+var path = require("path");var sinon = require("sinon");var createStatsCollector = require("../../lib/stats-collector");var events = require("../../").Runner.constants;@@ -11,6 +11,10 @@ var states = require("../../").Runnable.constants;const { createTempDir, touchFile } = require("../integration/helpers");+var helpers = require("./helpers");+var createMockRunner = helpers.createMockRunner;+var makeRunReporter = helpers.createRunReporterFunction;+var Base = reporters.Base;var XUnit = reporters.XUnit;@@ -24,6 +28,7 @@ var STATE_FAILED = states.STATE_FAILED;var STATE_PASSED = states.STATE_PASSED;describe("XUnit reporter", function () {+ var runReporter = makeRunReporter(XUnit);var runner;var noop = function () {};@@ -58,11 +63,14 @@ describe("XUnit reporter", function () {fsCreateWriteStream = sinon.stub(fs, "createWriteStream");});- it("should open given file for writing, recursively creating directories in pathname", function () {- var fakeThis = {- fileStream: null,+ it("should open given file for writing, recursively creating directories in pathname", async function () {+ var runner = createMockRunner("start", events.EVENT_RUN_BEGIN);+ var options = {+ reporterOptions: {+ output: expectedOutput,+ },};- XUnit.call(fakeThis, runner, options);+ new XUnit(runner, options);var expectedDirectory = path.dirname(expectedOutput);expect(@@ -113,7 +121,7 @@ describe("XUnit reporter", function () {output: invalidPath,},};- var boundXUnit = XUnit.bind({}, runner, options);+ var boundXUnit = () => new XUnit(runner, options);expect(boundXUnit,"to throw",@@ -136,7 +144,7 @@ describe("XUnit reporter", function () {});it("should throw unsupported error", function () {- var boundXUnit = XUnit.bind({}, runner, options);+ var boundXUnit = () => new XUnit(runner, options);expect(boundXUnit,"to throw",@@ -152,20 +160,41 @@ describe("XUnit reporter", function () {});describe("event handlers", function () {+ var fsCreateWriteStream;++ beforeEach(function () {+ sinon.stub(fs, "mkdirSync");+ fsCreateWriteStream = sinon.stub(fs, "createWriteStream");+ });+describe("on 'pending', 'pass' and 'fail' events", function () {- it("should add test to tests called on 'end' event", function () {+ it("should add test to tests called on 'end' event", async function () {var pendingTest = {+ isPending: () => false,+ parent: {+ fullTitle: () => "pending parent",+ },name: "pending",slow: noop,};var failTest = {+ isPending: () => false,+ parent: {+ fullTitle: () => "fail parent",+ },name: "fail",slow: noop,};var passTest = {+ isPending: () => false,+ parent: {+ fullTitle: () => "pass parent",+ },name: "pass",slow: noop,};+ var write = sinon.spy();+ fsCreateWriteStream.returns({ write });runner.on = runner.once = function (event, callback) {if (event === EVENT_TEST_PENDING) {callback(pendingTest);@@ -178,17 +207,19 @@ describe("XUnit reporter", function () {}};- var calledTests = [];- var fakeThis = {- write: noop,- test: function (test) {- calledTests.push(test);+ var expectedOutput = path.join(path.sep, "path", "to", "some-output");+ var options = {+ reporterOptions: {+ output: expectedOutput,},};- XUnit.call(fakeThis, runner);+ const { reporter } = await runReporter({}, runner, options);- var expectedCalledTests = [pendingTest, passTest, failTest];- expect(calledTests, "to equal", expectedCalledTests);+ reporter.fileStream;+ expect(write.getCalls().length, "to equal", 5);+ expect(write.getCall(1).args[0], "to match", /pending parent/);+ expect(write.getCall(2).args[0], "to match", /pass parent/);+ expect(write.getCall(3).args[0], "to match", /fail parent/);});});});@@ -287,9 +318,8 @@ describe("XUnit reporter", 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()- /* eslint-disable no-global-assign */var realProcess = process;- process = false;+ process = false; // eslint-disable-line no-global-assignvar xunit = new XUnit(runner);var fakeThis = { fileStream: false };@@ -297,10 +327,9 @@ describe("XUnit reporter", function () {xunit.write.call(fakeThis, expectedLine);consoleLogStub.restore();- process = realProcess;+ process = realProcess; // eslint-disable-line no-global-assignexpect(consoleLogStub.calledWith(expectedLine), "to be true");- /* eslint-enable no-global-assign */});});});