mocha 8.0.1 → 8.1.3

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.
@@ -19,7 +19,7 @@ const collectFiles = require('./collect-files');
19
19
  * @param {Object} opts - Options
20
20
  * @param {string[]} [opts.watchFiles] - List of paths and patterns to
21
21
  * watch. If not provided all files with an extension included in
22
- * `fileColletionParams.extension` are watched. See first argument of
22
+ * `fileCollectionParams.extension` are watched. See first argument of
23
23
  * `chokidar.watch`.
24
24
  * @param {string[]} opts.watchIgnore - List of paths and patterns to
25
25
  * exclude from watching. See `ignored` option of `chokidar`.
@@ -59,6 +59,10 @@ exports.watchParallelRun = (
59
59
  // in `createRerunner`), we need to call `mocha.ui()` again to set up the context/globals.
60
60
  newMocha.ui(newMocha.options.ui);
61
61
 
62
+ // we need to call `newMocha.rootHooks` to set up rootHooks for the new
63
+ // suite
64
+ newMocha.rootHooks(newMocha.options.rootHooks);
65
+
62
66
  // in parallel mode, the main Mocha process doesn't actually load the
63
67
  // files. this flag prevents `mocha.run()` from autoloading.
64
68
  newMocha.lazyLoadFiles(true);
@@ -77,7 +81,7 @@ exports.watchParallelRun = (
77
81
  * @param {Object} opts - Options
78
82
  * @param {string[]} [opts.watchFiles] - List of paths and patterns to
79
83
  * watch. If not provided all files with an extension included in
80
- * `fileColletionParams.extension` are watched. See first argument of
84
+ * `fileCollectionParams.extension` are watched. See first argument of
81
85
  * `chokidar.watch`.
82
86
  * @param {string[]} opts.watchIgnore - List of paths and patterns to
83
87
  * exclude from watching. See `ignored` option of `chokidar`.
@@ -118,6 +122,10 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
118
122
  // in `createRerunner`), we need to call `mocha.ui()` again to set up the context/globals.
119
123
  newMocha.ui(newMocha.options.ui);
120
124
 
125
+ // we need to call `newMocha.rootHooks` to set up rootHooks for the new
126
+ // suite
127
+ newMocha.rootHooks(newMocha.options.rootHooks);
128
+
121
129
  return newMocha;
122
130
  },
123
131
  afterRun({watcher}) {
@@ -136,7 +144,7 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
136
144
  * @param {AfterWatchRun} [opts.afterRun] - Function to call after `mocha.run()`
137
145
  * @param {string[]} [opts.watchFiles] - List of paths and patterns to watch. If
138
146
  * not provided all files with an extension included in
139
- * `fileColletionParams.extension` are watched. See first argument of
147
+ * `fileCollectionParams.extension` are watched. See first argument of
140
148
  * `chokidar.watch`.
141
149
  * @param {string[]} [opts.watchIgnore] - List of paths and patterns to exclude
142
150
  * from watching. See `ignored` option of `chokidar`.
package/lib/errors.js CHANGED
@@ -59,12 +59,12 @@ var constants = {
59
59
  UNSUPPORTED: 'ERR_MOCHA_UNSUPPORTED',
60
60
 
61
61
  /**
62
- * Invalid state transition occuring in `Mocha` instance
62
+ * Invalid state transition occurring in `Mocha` instance
63
63
  */
64
64
  INSTANCE_ALREADY_RUNNING: 'ERR_MOCHA_INSTANCE_ALREADY_RUNNING',
65
65
 
66
66
  /**
67
- * Invalid state transition occuring in `Mocha` instance
67
+ * Invalid state transition occurring in `Mocha` instance
68
68
  */
69
69
  INSTANCE_ALREADY_DISPOSED: 'ERR_MOCHA_INSTANCE_ALREADY_DISPOSED',
70
70
 
@@ -1,5 +1,9 @@
1
1
  'use strict';
2
2
 
3
+ /**
4
+ @module interfaces/common
5
+ */
6
+
3
7
  var Suite = require('../suite');
4
8
  var errors = require('../errors');
5
9
  var createMissingArgumentError = errors.createMissingArgumentError;
@@ -9,6 +13,7 @@ var createForbiddenExclusivityError = errors.createForbiddenExclusivityError;
9
13
  /**
10
14
  * Functions common to more than one interface.
11
15
  *
16
+ * @private
12
17
  * @param {Suite[]} suites
13
18
  * @param {Context} context
14
19
  * @param {Mocha} mocha
package/lib/mocha.js CHANGED
@@ -12,18 +12,18 @@ var builtinReporters = require('./reporters');
12
12
  var growl = require('./nodejs/growl');
13
13
  var utils = require('./utils');
14
14
  var mocharc = require('./mocharc.json');
15
- var errors = require('./errors');
16
15
  var Suite = require('./suite');
17
16
  var esmUtils = utils.supportsEsModules(true)
18
17
  ? require('./esm-utils')
19
18
  : undefined;
20
19
  var createStatsCollector = require('./stats-collector');
21
- var createInvalidReporterError = errors.createInvalidReporterError;
22
- var createInvalidInterfaceError = errors.createInvalidInterfaceError;
23
- var createMochaInstanceAlreadyDisposedError =
24
- errors.createMochaInstanceAlreadyDisposedError;
25
- var createMochaInstanceAlreadyRunningError =
26
- errors.createMochaInstanceAlreadyRunningError;
20
+ const {
21
+ createUnsupportedError,
22
+ createInvalidInterfaceError,
23
+ createInvalidReporterError,
24
+ createMochaInstanceAlreadyDisposedError,
25
+ createMochaInstanceAlreadyRunningError
26
+ } = require('./errors');
27
27
  var EVENT_FILE_PRE_REQUIRE = Suite.constants.EVENT_FILE_PRE_REQUIRE;
28
28
  var EVENT_FILE_POST_REQUIRE = Suite.constants.EVENT_FILE_POST_REQUIRE;
29
29
  var EVENT_FILE_REQUIRE = Suite.constants.EVENT_FILE_REQUIRE;
@@ -35,23 +35,28 @@ exports = module.exports = Mocha;
35
35
  /**
36
36
  * A Mocha instance is a finite state machine.
37
37
  * These are the states it can be in.
38
+ * @private
38
39
  */
39
40
  var mochaStates = utils.defineConstants({
40
41
  /**
41
42
  * Initial state of the mocha instance
43
+ * @private
42
44
  */
43
45
  INIT: 'init',
44
46
  /**
45
47
  * Mocha instance is running tests
48
+ * @private
46
49
  */
47
50
  RUNNING: 'running',
48
51
  /**
49
52
  * Mocha instance is done running tests and references to test functions and hooks are cleaned.
50
53
  * You can reset this state by unloading the test files.
54
+ * @private
51
55
  */
52
56
  REFERENCES_CLEANED: 'referencesCleaned',
53
57
  /**
54
58
  * Mocha instance is disposed and can no longer be used.
59
+ * @private
55
60
  */
56
61
  DISPOSED: 'disposed'
57
62
  });
@@ -67,6 +72,7 @@ if (!utils.isBrowser() && typeof module.paths !== 'undefined') {
67
72
 
68
73
  /**
69
74
  * Expose internals.
75
+ * @private
70
76
  */
71
77
 
72
78
  exports.utils = utils;
@@ -246,7 +252,7 @@ Mocha.prototype.addFile = function(file) {
246
252
  * @public
247
253
  * @see [CLI option](../#-reporter-name-r-name)
248
254
  * @see [Reporters](../#reporters)
249
- * @param {String|Function} reporter - Reporter name or constructor.
255
+ * @param {String|Function} reporterName - Reporter name or constructor.
250
256
  * @param {Object} [reporterOptions] - Options used to configure the reporter.
251
257
  * @returns {Mocha} this
252
258
  * @chainable
@@ -439,7 +445,12 @@ Mocha.prototype.loadFilesAsync = function() {
439
445
  * @param {string} file - Pathname of file to be unloaded.
440
446
  */
441
447
  Mocha.unloadFile = function(file) {
442
- delete require.cache[require.resolve(file)];
448
+ if (utils.isBrowser()) {
449
+ throw createUnsupportedError(
450
+ 'unloadFile() is only suported in a Node.js environment'
451
+ );
452
+ }
453
+ return require('./nodejs/file-unloader').unloadFile(file);
443
454
  };
444
455
 
445
456
  /**
@@ -769,8 +780,8 @@ Mocha.prototype.timeout = function(msecs) {
769
780
  * // Allow any failed test to retry one more time
770
781
  * mocha.retries(1);
771
782
  */
772
- Mocha.prototype.retries = function(n) {
773
- this.suite.retries(n);
783
+ Mocha.prototype.retries = function(retry) {
784
+ this.suite.retries(retry);
774
785
  return this;
775
786
  };
776
787
 
@@ -801,7 +812,7 @@ Mocha.prototype.slow = function(msecs) {
801
812
  *
802
813
  * @public
803
814
  * @see [CLI option](../#-async-only-a)
804
- * @param {boolean} [asyncOnly=true] - Wether to force `done` callback or promise.
815
+ * @param {boolean} [asyncOnly=true] - Whether to force `done` callback or promise.
805
816
  * @return {Mocha} this
806
817
  * @chainable
807
818
  */
@@ -841,7 +852,7 @@ Mocha.prototype.allowUncaught = function(allowUncaught) {
841
852
  * Delays root suite execution.
842
853
  *
843
854
  * @description
844
- * Used to perform asynch operations before any suites are run.
855
+ * Used to perform async operations before any suites are run.
845
856
  *
846
857
  * @public
847
858
  * @see [delayed root suite](../#delayed-root-suite)
@@ -921,6 +932,7 @@ Object.defineProperty(Mocha.prototype, 'version', {
921
932
  /**
922
933
  * Callback to be invoked when test execution is complete.
923
934
  *
935
+ * @private
924
936
  * @callback DoneCB
925
937
  * @param {number} failures - Number of failures that occurred.
926
938
  */
@@ -1044,9 +1056,7 @@ Mocha.prototype.rootHooks = function rootHooks(hooks) {
1044
1056
  */
1045
1057
  Mocha.prototype.parallelMode = function parallelMode(enable) {
1046
1058
  if (utils.isBrowser()) {
1047
- throw errors.createUnsupportedError(
1048
- 'parallel mode is only supported in Node.js'
1049
- );
1059
+ throw createUnsupportedError('parallel mode is only supported in Node.js');
1050
1060
  }
1051
1061
  var parallel = enable === true;
1052
1062
  if (
@@ -1057,7 +1067,7 @@ Mocha.prototype.parallelMode = function parallelMode(enable) {
1057
1067
  return this;
1058
1068
  }
1059
1069
  if (this._state !== mochaStates.INIT) {
1060
- throw errors.createUnsupportedError(
1070
+ throw createUnsupportedError(
1061
1071
  'cannot change parallel mode after having called run()'
1062
1072
  );
1063
1073
  }
@@ -1091,6 +1101,7 @@ Mocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) {
1091
1101
 
1092
1102
  /**
1093
1103
  * An alternative way to define root hooks that works with parallel runs.
1104
+ * @private
1094
1105
  * @typedef {Object} MochaRootHookObject
1095
1106
  * @property {Function|Function[]} [beforeAll] - "Before all" hook(s)
1096
1107
  * @property {Function|Function[]} [beforeEach] - "Before each" hook(s)
@@ -1100,6 +1111,7 @@ Mocha.prototype.lazyLoadFiles = function lazyLoadFiles(enable) {
1100
1111
 
1101
1112
  /**
1102
1113
  * An function that returns a {@link MochaRootHookObject}, either sync or async.
1114
+ * @private
1103
1115
  * @callback MochaRootHookFunction
1104
1116
  * @returns {MochaRootHookObject|Promise<MochaRootHookObject>}
1105
1117
  */
@@ -0,0 +1,15 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * This module should not be in the browser bundle, so it's here.
5
+ * @private
6
+ * @module
7
+ */
8
+
9
+ /**
10
+ * Deletes a file from the `require` cache.
11
+ * @param {string} file - File
12
+ */
13
+ exports.unloadFile = file => {
14
+ delete require.cache[require.resolve(file)];
15
+ };
@@ -281,12 +281,14 @@ module.exports = ParallelBufferedRunner;
281
281
 
282
282
  /**
283
283
  * Listener function intended to be bound to `Process.SIGINT` event
284
+ * @private
284
285
  * @callback SigIntListener
285
286
  * @returns {Promise<void>}
286
287
  */
287
288
 
288
289
  /**
289
290
  * A function accepting a test file path and returning the results of a test run
291
+ * @private
290
292
  * @callback FileRunner
291
293
  * @param {string} filename - File to run
292
294
  * @returns {Promise<SerializedWorkerResult>}
@@ -56,7 +56,7 @@ class SerializableWorkerResult {
56
56
  /**
57
57
  * Instantiates a new {@link SerializableWorkerResult}.
58
58
  * @param {...any} args - Args to constructor
59
- * @returns {SerilizableWorkerResult}
59
+ * @returns {SerializableWorkerResult}
60
60
  */
61
61
  static create(...args) {
62
62
  return new SerializableWorkerResult(...args);
@@ -387,6 +387,7 @@ exports.SerializableWorkerResult = SerializableWorkerResult;
387
387
  /**
388
388
  * The result of calling `SerializableEvent.serialize`, as received
389
389
  * by the deserializer.
390
+ * @private
390
391
  * @typedef {Object} SerializedEvent
391
392
  * @property {object?} data - Optional serialized data
392
393
  * @property {object?} error - Optional serialized `Error`
@@ -395,6 +396,7 @@ exports.SerializableWorkerResult = SerializableWorkerResult;
395
396
  /**
396
397
  * The result of calling `SerializableWorkerResult.serialize` as received
397
398
  * by the deserializer.
399
+ * @private
398
400
  * @typedef {Object} SerializedWorkerResult
399
401
  * @property {number} failureCount - Number of failures
400
402
  * @property {SerializedEvent[]} events - Serialized events
package/lib/pending.js CHANGED
@@ -1,5 +1,9 @@
1
1
  'use strict';
2
2
 
3
+ /**
4
+ @module Pending
5
+ */
6
+
3
7
  module.exports = Pending;
4
8
 
5
9
  /**
@@ -6,15 +6,24 @@
6
6
  * Module dependencies.
7
7
  */
8
8
 
9
- var tty = require('tty');
10
9
  var diff = require('diff');
11
10
  var milliseconds = require('ms');
12
11
  var utils = require('../utils');
13
- var supportsColor = utils.isBrowser() ? null : require('supports-color');
12
+ var supportsColor = require('supports-color');
14
13
  var constants = require('../runner').constants;
15
14
  var EVENT_TEST_PASS = constants.EVENT_TEST_PASS;
16
15
  var EVENT_TEST_FAIL = constants.EVENT_TEST_FAIL;
17
16
 
17
+ const isBrowser = utils.isBrowser();
18
+
19
+ function getBrowserWindowSize() {
20
+ if ('innerHeight' in global) {
21
+ return [global.innerHeight, global.innerWidth];
22
+ }
23
+ // In a Web Worker, the DOM Window is not available.
24
+ return [640, 480];
25
+ }
26
+
18
27
  /**
19
28
  * Expose `Base`.
20
29
  */
@@ -25,7 +34,7 @@ exports = module.exports = Base;
25
34
  * Check if both stdio streams are associated with a tty.
26
35
  */
27
36
 
28
- var isatty = process.stdout.isTTY && process.stderr.isTTY;
37
+ var isatty = isBrowser || (process.stdout.isTTY && process.stderr.isTTY);
29
38
 
30
39
  /**
31
40
  * Save log references to avoid tests interfering (see GH-3604).
@@ -37,7 +46,7 @@ var consoleLog = console.log;
37
46
  */
38
47
 
39
48
  exports.useColors =
40
- !utils.isBrowser() &&
49
+ !isBrowser &&
41
50
  (supportsColor.stdout || process.env.MOCHA_COLORS !== undefined);
42
51
 
43
52
  /**
@@ -69,7 +78,9 @@ exports.colors = {
69
78
  light: 90,
70
79
  'diff gutter': 90,
71
80
  'diff added': 32,
72
- 'diff removed': 31
81
+ 'diff removed': 31,
82
+ 'diff added inline': '30;42',
83
+ 'diff removed inline': '30;41'
73
84
  };
74
85
 
75
86
  /**
@@ -118,9 +129,11 @@ exports.window = {
118
129
  };
119
130
 
120
131
  if (isatty) {
121
- exports.window.width = process.stdout.getWindowSize
122
- ? process.stdout.getWindowSize(1)[0]
123
- : tty.getWindowSize()[1];
132
+ if (isBrowser) {
133
+ exports.window.width = getBrowserWindowSize()[1];
134
+ } else {
135
+ exports.window.width = process.stdout.getWindowSize(1)[0];
136
+ }
124
137
  }
125
138
 
126
139
  /**
@@ -406,9 +419,9 @@ function inlineDiff(actual, expected) {
406
419
  // legend
407
420
  msg =
408
421
  '\n' +
409
- color('diff removed', 'actual') +
422
+ color('diff removed inline', 'actual') +
410
423
  ' ' +
411
- color('diff added', 'expected') +
424
+ color('diff added inline', 'expected') +
412
425
  '\n\n' +
413
426
  msg +
414
427
  '\n';
@@ -474,10 +487,10 @@ function errorDiff(actual, expected) {
474
487
  .diffWordsWithSpace(actual, expected)
475
488
  .map(function(str) {
476
489
  if (str.added) {
477
- return colorLines('diff added', str.value);
490
+ return colorLines('diff added inline', str.value);
478
491
  }
479
492
  if (str.removed) {
480
- return colorLines('diff removed', str.value);
493
+ return colorLines('diff removed inline', str.value);
481
494
  }
482
495
  return str.value;
483
496
  })
package/lib/runnable.js CHANGED
@@ -11,6 +11,7 @@ var createMultipleDoneError = errors.createMultipleDoneError;
11
11
 
12
12
  /**
13
13
  * Save timer references to avoid Sinon interfering (see GH-237).
14
+ * @private
14
15
  */
15
16
  var Date = global.Date;
16
17
  var setTimeout = global.setTimeout;
package/lib/runner.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  /**
4
4
  * Module dependencies.
5
+ * @private
5
6
  */
6
7
  var util = require('util');
7
8
  var EventEmitter = require('events').EventEmitter;
@@ -31,6 +32,7 @@ var createFatalError = errors.createFatalError;
31
32
 
32
33
  /**
33
34
  * Non-enumerable globals.
35
+ * @private
34
36
  * @readonly
35
37
  */
36
38
  var globals = [
@@ -204,7 +206,7 @@ Runner.prototype._addEventListener = function(target, eventName, listener) {
204
206
  /**
205
207
  * Replacement for `target.removeListener(eventName, listener)` that also updates the bookkeeping.
206
208
  * @param {EventEmitter} target - The `EventEmitter`
207
- * @param {string} eventName - The event anme
209
+ * @param {string} eventName - The event name
208
210
  * @param {function} listener - Listener function
209
211
  * @private
210
212
  */
@@ -358,6 +360,19 @@ Runner.prototype.checkGlobals = function(test) {
358
360
  /**
359
361
  * Fail the given `test`.
360
362
  *
363
+ * If `test` is a hook, failures work in the following pattern:
364
+ * - If bail, run corresponding `after each` and `after` hooks,
365
+ * then exit
366
+ * - Failed `before` hook skips all tests in a suite and subsuites,
367
+ * but jumps to corresponding `after` hook
368
+ * - Failed `before each` hook skips remaining tests in a
369
+ * suite and jumps to corresponding `after each` hook,
370
+ * which is run only once
371
+ * - Failed `after` hook does not alter execution order
372
+ * - Failed `after each` hook skips remaining tests in a
373
+ * suite and subsuites, but executes other `after each`
374
+ * hooks
375
+ *
361
376
  * @private
362
377
  * @param {Runnable} test
363
378
  * @param {Error} err
@@ -396,44 +411,6 @@ Runner.prototype.fail = function(test, err, force) {
396
411
  this.emit(constants.EVENT_TEST_FAIL, test, err);
397
412
  };
398
413
 
399
- /**
400
- * Fail the given `hook` with `err`.
401
- *
402
- * Hook failures work in the following pattern:
403
- * - If bail, run corresponding `after each` and `after` hooks,
404
- * then exit
405
- * - Failed `before` hook skips all tests in a suite and subsuites,
406
- * but jumps to corresponding `after` hook
407
- * - Failed `before each` hook skips remaining tests in a
408
- * suite and jumps to corresponding `after each` hook,
409
- * which is run only once
410
- * - Failed `after` hook does not alter execution order
411
- * - Failed `after each` hook skips remaining tests in a
412
- * suite and subsuites, but executes other `after each`
413
- * hooks
414
- *
415
- * @private
416
- * @param {Hook} hook
417
- * @param {Error} err
418
- */
419
- Runner.prototype.failHook = function(hook, err) {
420
- hook.originalTitle = hook.originalTitle || hook.title;
421
- if (hook.ctx && hook.ctx.currentTest) {
422
- hook.title =
423
- hook.originalTitle + ' for ' + dQuote(hook.ctx.currentTest.title);
424
- } else {
425
- var parentTitle;
426
- if (hook.parent.title) {
427
- parentTitle = hook.parent.title;
428
- } else {
429
- parentTitle = hook.parent.root ? '{root}' : '';
430
- }
431
- hook.title = hook.originalTitle + ' in ' + dQuote(parentTitle);
432
- }
433
-
434
- this.fail(hook, err);
435
- };
436
-
437
414
  /**
438
415
  * Run hook `name` callbacks and then invoke `fn()`.
439
416
  *
@@ -462,13 +439,15 @@ Runner.prototype.hook = function(name, fn) {
462
439
  hook.ctx.currentTest = self.test;
463
440
  }
464
441
 
442
+ setHookTitle(hook);
443
+
465
444
  hook.allowUncaught = self.allowUncaught;
466
445
 
467
446
  self.emit(constants.EVENT_HOOK_BEGIN, hook);
468
447
 
469
448
  if (!hook.listeners('error').length) {
470
449
  self._addEventListener(hook, 'error', function(err) {
471
- self.failHook(hook, err);
450
+ self.fail(hook, err);
472
451
  });
473
452
  }
474
453
 
@@ -502,18 +481,35 @@ Runner.prototype.hook = function(name, fn) {
502
481
  } else {
503
482
  hook.pending = false;
504
483
  var errForbid = createUnsupportedError('`this.skip` forbidden');
505
- self.failHook(hook, errForbid);
484
+ self.fail(hook, errForbid);
506
485
  return fn(errForbid);
507
486
  }
508
487
  } else if (err) {
509
- self.failHook(hook, err);
488
+ self.fail(hook, err);
510
489
  // stop executing hooks, notify callee of hook err
511
490
  return fn(err);
512
491
  }
513
492
  self.emit(constants.EVENT_HOOK_END, hook);
514
493
  delete hook.ctx.currentTest;
494
+ setHookTitle(hook);
515
495
  next(++i);
516
496
  });
497
+
498
+ function setHookTitle(hook) {
499
+ hook.originalTitle = hook.originalTitle || hook.title;
500
+ if (hook.ctx && hook.ctx.currentTest) {
501
+ hook.title =
502
+ hook.originalTitle + ' for ' + dQuote(hook.ctx.currentTest.title);
503
+ } else {
504
+ var parentTitle;
505
+ if (hook.parent.title) {
506
+ parentTitle = hook.parent.title;
507
+ } else {
508
+ parentTitle = hook.parent.root ? '{root}' : '';
509
+ }
510
+ hook.title = hook.originalTitle + ' in ' + dQuote(parentTitle);
511
+ }
512
+ }
517
513
  }
518
514
 
519
515
  Runner.immediately(function() {
package/lib/suite.js CHANGED
@@ -2,6 +2,7 @@
2
2
 
3
3
  /**
4
4
  * Module dependencies.
5
+ * @private
5
6
  */
6
7
  var EventEmitter = require('events').EventEmitter;
7
8
  var Hook = require('./hook');