mocha 8.3.0 → 9.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/mocha.js CHANGED
@@ -30,7 +30,6 @@ const {
30
30
  EVENT_FILE_POST_REQUIRE,
31
31
  EVENT_FILE_REQUIRE
32
32
  } = Suite.constants;
33
- var sQuote = utils.sQuote;
34
33
  var debug = require('debug')('mocha:mocha');
35
34
 
36
35
  exports = module.exports = Mocha;
@@ -96,6 +95,61 @@ exports.Suite = Suite;
96
95
  exports.Hook = require('./hook');
97
96
  exports.Test = require('./test');
98
97
 
98
+ let currentContext;
99
+ exports.afterEach = function(...args) {
100
+ return (currentContext.afterEach || currentContext.teardown).apply(
101
+ this,
102
+ args
103
+ );
104
+ };
105
+ exports.after = function(...args) {
106
+ return (currentContext.after || currentContext.suiteTeardown).apply(
107
+ this,
108
+ args
109
+ );
110
+ };
111
+ exports.beforeEach = function(...args) {
112
+ return (currentContext.beforeEach || currentContext.setup).apply(this, args);
113
+ };
114
+ exports.before = function(...args) {
115
+ return (currentContext.before || currentContext.suiteSetup).apply(this, args);
116
+ };
117
+ exports.describe = function(...args) {
118
+ return (currentContext.describe || currentContext.suite).apply(this, args);
119
+ };
120
+ exports.describe.only = function(...args) {
121
+ return (currentContext.describe || currentContext.suite).only.apply(
122
+ this,
123
+ args
124
+ );
125
+ };
126
+ exports.describe.skip = function(...args) {
127
+ return (currentContext.describe || currentContext.suite).skip.apply(
128
+ this,
129
+ args
130
+ );
131
+ };
132
+ exports.it = function(...args) {
133
+ return (currentContext.it || currentContext.test).apply(this, args);
134
+ };
135
+ exports.it.only = function(...args) {
136
+ return (currentContext.it || currentContext.test).only.apply(this, args);
137
+ };
138
+ exports.it.skip = function(...args) {
139
+ return (currentContext.it || currentContext.test).skip.apply(this, args);
140
+ };
141
+ exports.xdescribe = exports.describe.skip;
142
+ exports.xit = exports.it.skip;
143
+ exports.setup = exports.beforeEach;
144
+ exports.suiteSetup = exports.before;
145
+ exports.suiteTeardown = exports.after;
146
+ exports.suite = exports.describe;
147
+ exports.teardown = exports.afterEach;
148
+ exports.test = exports.it;
149
+ exports.run = function(...args) {
150
+ return currentContext.run.apply(this, args);
151
+ };
152
+
99
153
  /**
100
154
  * Constructs a new Mocha instance with `options`.
101
155
  *
@@ -109,6 +163,7 @@ exports.Test = require('./test');
109
163
  * @param {boolean} [options.color] - Color TTY output from reporter?
110
164
  * @param {boolean} [options.delay] - Delay root suite execution?
111
165
  * @param {boolean} [options.diff] - Show diff on failure?
166
+ * @param {boolean} [options.dryRun] - Report tests without running them?
112
167
  * @param {string} [options.fgrep] - Test filter given string.
113
168
  * @param {boolean} [options.forbidOnly] - Tests marked `only` fail the suite?
114
169
  * @param {boolean} [options.forbidPending] - Pending tests fail the suite?
@@ -125,10 +180,10 @@ exports.Test = require('./test');
125
180
  * @param {number} [options.slow] - Slow threshold value.
126
181
  * @param {number|string} [options.timeout] - Timeout threshold value.
127
182
  * @param {string} [options.ui] - Interface name.
128
- * @param {boolean} [options.parallel] - Run jobs in parallel
129
- * @param {number} [options.jobs] - Max number of worker processes for parallel runs
130
- * @param {MochaRootHookObject} [options.rootHooks] - Hooks to bootstrap the root
131
- * suite with
183
+ * @param {boolean} [options.parallel] - Run jobs in parallel.
184
+ * @param {number} [options.jobs] - Max number of worker processes for parallel runs.
185
+ * @param {MochaRootHookObject} [options.rootHooks] - Hooks to bootstrap the root suite with.
186
+ * @param {string[]} [options.require] - Pathname of `rootHooks` plugin for parallel runs.
132
187
  * @param {boolean} [options.isWorker] - Should be `true` if `Mocha` process is running in a worker process.
133
188
  */
134
189
  function Mocha(options = {}) {
@@ -145,7 +200,7 @@ function Mocha(options = {}) {
145
200
  .ui(options.ui)
146
201
  .reporter(
147
202
  options.reporter,
148
- options.reporterOption || options.reporterOptions // reporterOptions was previously the only way to specify options to reporter
203
+ options.reporterOption || options.reporterOptions // for backwards compability
149
204
  )
150
205
  .slow(options.slow)
151
206
  .global(options.global);
@@ -167,6 +222,7 @@ function Mocha(options = {}) {
167
222
  'color',
168
223
  'delay',
169
224
  'diff',
225
+ 'dryRun',
170
226
  'forbidOnly',
171
227
  'forbidPending',
172
228
  'fullTrace',
@@ -291,23 +347,19 @@ Mocha.prototype.reporter = function(reporterName, reporterOptions) {
291
347
  reporter = require(path.resolve(utils.cwd(), reporterName));
292
348
  } catch (_err) {
293
349
  _err.code === 'MODULE_NOT_FOUND'
294
- ? warn(sQuote(reporterName) + ' reporter not found')
350
+ ? warn(`'${reporterName}' reporter not found`)
295
351
  : warn(
296
- sQuote(reporterName) +
297
- ' reporter blew up with error:\n' +
298
- err.stack
352
+ `'${reporterName}' reporter blew up with error:\n ${err.stack}`
299
353
  );
300
354
  }
301
355
  } else {
302
- warn(
303
- sQuote(reporterName) + ' reporter blew up with error:\n' + err.stack
304
- );
356
+ warn(`'${reporterName}' reporter blew up with error:\n ${err.stack}`);
305
357
  }
306
358
  }
307
359
  }
308
360
  if (!reporter) {
309
361
  throw createInvalidReporterError(
310
- 'invalid reporter ' + sQuote(reporterName),
362
+ `invalid reporter '${reporterName}'`,
311
363
  reporterName
312
364
  );
313
365
  }
@@ -341,30 +393,14 @@ Mocha.prototype.ui = function(ui) {
341
393
  try {
342
394
  bindInterface = require(ui);
343
395
  } catch (err) {
344
- throw createInvalidInterfaceError(
345
- 'invalid interface ' + sQuote(ui),
346
- ui
347
- );
396
+ throw createInvalidInterfaceError(`invalid interface '${ui}'`, ui);
348
397
  }
349
398
  }
350
399
  }
351
400
  bindInterface(this.suite);
352
401
 
353
402
  this.suite.on(EVENT_FILE_PRE_REQUIRE, function(context) {
354
- exports.afterEach = context.afterEach || context.teardown;
355
- exports.after = context.after || context.suiteTeardown;
356
- exports.beforeEach = context.beforeEach || context.setup;
357
- exports.before = context.before || context.suiteSetup;
358
- exports.describe = context.describe || context.suite;
359
- exports.it = context.it || context.test;
360
- exports.xit = context.xit || (context.test && context.test.skip);
361
- exports.setup = context.setup || context.beforeEach;
362
- exports.suiteSetup = context.suiteSetup || context.before;
363
- exports.suiteTeardown = context.suiteTeardown || context.after;
364
- exports.suite = context.suite || context.describe;
365
- exports.teardown = context.teardown || context.afterEach;
366
- exports.test = context.test || context.it;
367
- exports.run = context.run;
403
+ currentContext = context;
368
404
  });
369
405
 
370
406
  return this;
@@ -742,6 +778,20 @@ Mocha.prototype.diff = function(diff) {
742
778
  return this;
743
779
  };
744
780
 
781
+ /**
782
+ * Enables or disables running tests in dry-run mode.
783
+ *
784
+ * @public
785
+ * @see [CLI option](../#-dry-run)
786
+ * @param {boolean} [dryRun=true] - Whether to activate dry-run mode.
787
+ * @return {Mocha} this
788
+ * @chainable
789
+ */
790
+ Mocha.prototype.dryRun = function(dryRun) {
791
+ this.options.dryRun = dryRun !== false;
792
+ return this;
793
+ };
794
+
745
795
  /**
746
796
  * @summary
747
797
  * Sets timeout threshold value.
@@ -974,6 +1024,7 @@ Mocha.prototype.run = function(fn) {
974
1024
  options.files = this.files;
975
1025
  const runner = new this._runnerClass(suite, {
976
1026
  delay: options.delay,
1027
+ dryRun: options.dryRun,
977
1028
  cleanReferencesAfterRun: this._cleanReferencesAfterRun
978
1029
  });
979
1030
  createStatsCollector(runner);
@@ -1299,7 +1350,7 @@ Mocha.prototype.hasGlobalTeardownFixtures = function hasGlobalTeardownFixtures()
1299
1350
  * A (sync) function to assert a user-supplied plugin implementation is valid.
1300
1351
  *
1301
1352
  * Defined in a {@link PluginDefinition}.
1302
-
1353
+
1303
1354
  * @callback PluginValidator
1304
1355
  * @param {*} value - Value to check
1305
1356
  * @this {PluginDefinition}
@@ -10,6 +10,7 @@ var diff = require('diff');
10
10
  var milliseconds = require('ms');
11
11
  var utils = require('../utils');
12
12
  var supportsColor = require('supports-color');
13
+ var symbols = require('log-symbols');
13
14
  var constants = require('../runner').constants;
14
15
  var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
15
16
  var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
@@ -88,20 +89,13 @@ exports.colors = {
88
89
  */
89
90
 
90
91
  exports.symbols = {
91
- ok: '✓',
92
- err: '✖',
93
- dot: '',
92
+ ok: symbols.success,
93
+ err: symbols.err,
94
+ dot: '.',
94
95
  comma: ',',
95
96
  bang: '!'
96
97
  };
97
98
 
98
- // With node.js on Windows: use symbols available in terminal default fonts
99
- if (process.platform === 'win32') {
100
- exports.symbols.ok = '\u221A';
101
- exports.symbols.err = '\u00D7';
102
- exports.symbols.dot = '.';
103
- }
104
-
105
99
  /**
106
100
  * Color `str` with the given `type`,
107
101
  * allowing colors to be disabled,
@@ -196,6 +190,13 @@ function stringifyDiffObjs(err) {
196
190
  */
197
191
  var generateDiff = (exports.generateDiff = function(actual, expected) {
198
192
  try {
193
+ const diffSize = 2048;
194
+ if (actual.length > diffSize) {
195
+ actual = actual.substring(0, diffSize) + ' ... Lines skipped';
196
+ }
197
+ if (expected.length > diffSize) {
198
+ expected = expected.substring(0, diffSize) + ' ... Lines skipped';
199
+ }
199
200
  return exports.inlineDiffs
200
201
  ? inlineDiff(actual, expected)
201
202
  : unifiedDiff(actual, expected);
@@ -242,10 +243,10 @@ exports.list = function(failures) {
242
243
  err = test.err;
243
244
  }
244
245
  var message;
245
- if (err.message && typeof err.message.toString === 'function') {
246
- message = err.message + '';
247
- } else if (typeof err.inspect === 'function') {
246
+ if (typeof err.inspect === 'function') {
248
247
  message = err.inspect() + '';
248
+ } else if (err.message && typeof err.message.toString === 'function') {
249
+ message = err.message + '';
249
250
  } else {
250
251
  message = '';
251
252
  }
package/lib/runner.js CHANGED
@@ -4,7 +4,6 @@
4
4
  * Module dependencies.
5
5
  * @private
6
6
  */
7
- var util = require('util');
8
7
  var EventEmitter = require('events').EventEmitter;
9
8
  var Pending = require('./pending');
10
9
  var utils = require('./utils');
@@ -19,8 +18,6 @@ var EVENT_ROOT_SUITE_RUN = Suite.constants.EVENT_ROOT_SUITE_RUN;
19
18
  var STATE_FAILED = Runnable.constants.STATE_FAILED;
20
19
  var STATE_PASSED = Runnable.constants.STATE_PASSED;
21
20
  var STATE_PENDING = Runnable.constants.STATE_PENDING;
22
- var dQuote = utils.dQuote;
23
- var sQuote = utils.sQuote;
24
21
  var stackFilter = utils.stackTraceFilter();
25
22
  var stringify = utils.stringify;
26
23
 
@@ -138,8 +135,9 @@ class Runner extends EventEmitter {
138
135
  * @public
139
136
  * @class
140
137
  * @param {Suite} suite - Root suite
141
- * @param {Object|boolean} [opts] - Options. If `boolean`, whether or not to delay execution of root suite until ready (for backwards compatibility).
138
+ * @param {Object|boolean} [opts] - Options. If `boolean` (deprecated), whether or not to delay execution of root suite until ready.
142
139
  * @param {boolean} [opts.delay] - Whether to delay execution of root suite until ready.
140
+ * @param {boolean} [opts.dryRun] - Whether to report tests without running them.
143
141
  * @param {boolean} [opts.cleanReferencesAfterRun] - Whether to clean references to test fns and hooks when a suite is done.
144
142
  */
145
143
  constructor(suite, opts) {
@@ -148,7 +146,10 @@ class Runner extends EventEmitter {
148
146
  opts = {};
149
147
  }
150
148
  if (typeof opts === 'boolean') {
151
- // TODO: deprecate this
149
+ // TODO: remove this
150
+ require('./errors').deprecate(
151
+ '"Runner(suite: Suite, delay: boolean)" is deprecated. Use "Runner(suite: Suite, {delay: boolean})" instead.'
152
+ );
152
153
  this._delay = opts;
153
154
  opts = {};
154
155
  } else {
@@ -407,9 +408,8 @@ Runner.prototype.checkGlobals = function(test) {
407
408
  this._globals = this._globals.concat(leaks);
408
409
 
409
410
  if (leaks.length) {
410
- var msg = 'global leak(s) detected: %s';
411
- var error = new Error(util.format(msg, leaks.map(sQuote).join(', ')));
412
- this.fail(test, error);
411
+ var msg = `global leak(s) detected: ${leaks.map(e => `'${e}'`).join(', ')}`;
412
+ this.fail(test, new Error(msg));
413
413
  }
414
414
  };
415
415
 
@@ -476,6 +476,8 @@ Runner.prototype.fail = function(test, err, force) {
476
476
  */
477
477
 
478
478
  Runner.prototype.hook = function(name, fn) {
479
+ if (this._opts.dryRun) return fn();
480
+
479
481
  var suite = this.suite;
480
482
  var hooks = suite.getHooks(name);
481
483
  var self = this;
@@ -554,8 +556,7 @@ Runner.prototype.hook = function(name, fn) {
554
556
  function setHookTitle(hook) {
555
557
  hook.originalTitle = hook.originalTitle || hook.title;
556
558
  if (hook.ctx && hook.ctx.currentTest) {
557
- hook.title =
558
- hook.originalTitle + ' for ' + dQuote(hook.ctx.currentTest.title);
559
+ hook.title = `${hook.originalTitle} for "${hook.ctx.currentTest.title}"`;
559
560
  } else {
560
561
  var parentTitle;
561
562
  if (hook.parent.title) {
@@ -563,7 +564,7 @@ Runner.prototype.hook = function(name, fn) {
563
564
  } else {
564
565
  parentTitle = hook.parent.root ? '{root}' : '';
565
566
  }
566
- hook.title = hook.originalTitle + ' in ' + dQuote(parentTitle);
567
+ hook.title = `${hook.originalTitle} in "${parentTitle}"`;
567
568
  }
568
569
  }
569
570
  }
@@ -609,7 +610,7 @@ Runner.prototype.hooks = function(name, suites, fn) {
609
610
  };
610
611
 
611
612
  /**
612
- * Run hooks from the top level down.
613
+ * Run 'afterEach' hooks from bottom up.
613
614
  *
614
615
  * @param {String} name
615
616
  * @param {Function} fn
@@ -621,7 +622,7 @@ Runner.prototype.hookUp = function(name, fn) {
621
622
  };
622
623
 
623
624
  /**
624
- * Run hooks from the bottom up.
625
+ * Run 'beforeEach' hooks from top level down.
625
626
  *
626
627
  * @param {String} name
627
628
  * @param {Function} fn
@@ -656,6 +657,8 @@ Runner.prototype.parents = function() {
656
657
  * @private
657
658
  */
658
659
  Runner.prototype.runTest = function(fn) {
660
+ if (this._opts.dryRun) return fn();
661
+
659
662
  var self = this;
660
663
  var test = this.test;
661
664
 
@@ -701,7 +704,6 @@ Runner.prototype.runTests = function(suite, fn) {
701
704
  self.suite = after ? errSuite.parent : errSuite;
702
705
 
703
706
  if (self.suite) {
704
- // call hookUp afterEach
705
707
  self.hookUp(HOOK_TYPE_AFTER_EACH, function(err2, errSuite2) {
706
708
  self.suite = orig;
707
709
  // some hooks may fail even now
package/lib/utils.js CHANGED
@@ -13,7 +13,6 @@ const {nanoid} = require('nanoid/non-secure');
13
13
  var path = require('path');
14
14
  var util = require('util');
15
15
  var he = require('he');
16
- const errors = require('./errors');
17
16
 
18
17
  const MOCHA_ID_PROP_NAME = '__mocha_id__';
19
18
 
@@ -519,44 +518,6 @@ exports.clamp = function clamp(value, range) {
519
518
  return Math.min(Math.max(value, range[0]), range[1]);
520
519
  };
521
520
 
522
- /**
523
- * Single quote text by combining with undirectional ASCII quotation marks.
524
- *
525
- * @description
526
- * Provides a simple means of markup for quoting text to be used in output.
527
- * Use this to quote names of variables, methods, and packages.
528
- *
529
- * <samp>package 'foo' cannot be found</samp>
530
- *
531
- * @private
532
- * @param {string} str - Value to be quoted.
533
- * @returns {string} quoted value
534
- * @example
535
- * sQuote('n') // => 'n'
536
- */
537
- exports.sQuote = function(str) {
538
- return "'" + str + "'";
539
- };
540
-
541
- /**
542
- * Double quote text by combining with undirectional ASCII quotation marks.
543
- *
544
- * @description
545
- * Provides a simple means of markup for quoting text to be used in output.
546
- * Use this to quote names of datatypes, classes, pathnames, and strings.
547
- *
548
- * <samp>argument 'value' must be "string" or "number"</samp>
549
- *
550
- * @private
551
- * @param {string} str - Value to be quoted.
552
- * @returns {string} quoted value
553
- * @example
554
- * dQuote('number') // => "number"
555
- */
556
- exports.dQuote = function(str) {
557
- return '"' + str + '"';
558
- };
559
-
560
521
  /**
561
522
  * It's a noop.
562
523
  * @public
@@ -650,35 +611,6 @@ exports.isBrowser = function isBrowser() {
650
611
  return Boolean(process.browser);
651
612
  };
652
613
 
653
- /**
654
- * Lookup file names at the given `path`.
655
- *
656
- * @description
657
- * Filenames are returned in _traversal_ order by the OS/filesystem.
658
- * **Make no assumption that the names will be sorted in any fashion.**
659
- *
660
- * @public
661
- * @alias module:lib/cli.lookupFiles
662
- * @param {string} filepath - Base path to start searching from.
663
- * @param {string[]} [extensions=[]] - File extensions to look for.
664
- * @param {boolean} [recursive=false] - Whether to recurse into subdirectories.
665
- * @return {string[]} An array of paths.
666
- * @throws {Error} if no files match pattern.
667
- * @throws {TypeError} if `filepath` is directory and `extensions` not provided.
668
- * @deprecated Moved to {@link module:lib/cli.lookupFiles}
669
- */
670
- exports.lookupFiles = (...args) => {
671
- if (exports.isBrowser()) {
672
- throw errors.createUnsupportedError(
673
- 'lookupFiles() is only supported in Node.js!'
674
- );
675
- }
676
- errors.deprecate(
677
- '`lookupFiles()` in module `mocha/lib/utils` has moved to module `mocha/lib/cli` and will be removed in the next major revision of Mocha'
678
- );
679
- return require('./cli').lookupFiles(...args);
680
- };
681
-
682
614
  /*
683
615
  * Casts `value` to an array; useful for optionally accepting array parameters
684
616
  *