mocha 8.1.3 → 8.2.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/CHANGELOG.md CHANGED
@@ -1,3 +1,59 @@
1
+ # 8.2.0 / 2020-10-15
2
+
3
+ The major feature added in v8.2.0 is addition of support for [_global fixtures_](https://mochajs.org/#global-fixtures).
4
+
5
+ While Mocha has always had the ability to run setup and teardown via a hook (e.g., a `before()` at the top level of a test file) when running tests in serial, Mocha v8.0.0 added support for parallel runs. Parallel runs are _incompatible_ with this strategy; e.g., a top-level `before()` would only run for the file in which it was defined.
6
+
7
+ With [global fixtures](https://mochajs.org/#global-fixtures), Mocha can now perform user-defined setup and teardown _regardless_ of mode, and these fixtures are guaranteed to run _once and only once_. This holds for parallel mode, serial mode, and even "watch" mode (the teardown will run once you hit Ctrl-C, just before Mocha finally exits). Tasks such as starting and stopping servers are well-suited to global fixtures, but not sharing resources--global fixtures do _not_ share context with your test files (but they do share context with each other).
8
+
9
+ Here's a short example of usage:
10
+
11
+ ```js
12
+ // fixtures.js
13
+
14
+ // can be async or not
15
+ exports.mochaGlobalSetup = async function() {
16
+ this.server = await startSomeServer({port: process.env.TEST_PORT});
17
+ console.log(`server running on port ${this.server.port}`);
18
+ };
19
+
20
+ exports.mochaGlobalTeardown = async function() {
21
+ // the context (`this`) is shared, but not with the test files
22
+ await this.server.stop();
23
+ console.log(`server on port ${this.server.port} stopped`);
24
+ };
25
+
26
+ // this file can contain root hook plugins as well!
27
+ // exports.mochaHooks = { ... }
28
+ ```
29
+
30
+ Fixtures are loaded with `--require`, e.g., `mocha --require fixtures.js`.
31
+
32
+ For detailed information, please see the [documentation](https://mochajs.org/#global-fixtures) and this handy-dandy [flowchart](https://mochajs.org/#test-fixture-decision-tree-wizard-thing) to help understand the differences between hooks, root hook plugins, and global fixtures (and when you should use each).
33
+
34
+ ## :tada: Enhancements
35
+
36
+ - [#4308](https://github.com/mochajs/mocha/issues/4308): Support run-once [global setup & teardown fixtures](https://mochajs.org/#global-fixtures) ([**@boneskull**](https://github.com/boneskull))
37
+ - [#4442](https://github.com/mochajs/mocha/issues/4442): Multi-part extensions (e.g., `test.js`) now usable with `--extension` option ([**@jordanstephens**](https://github.com/jordanstephens))
38
+ - [#4472](https://github.com/mochajs/mocha/issues/4472): Leading dots (e.g., `.js`, `.test.js`) now usable with `--extension` option ([**@boneskull**](https://github.com/boneskull))
39
+ - [#4434](https://github.com/mochajs/mocha/issues/4434): Output of `json` reporter now contains `speed` ("fast"/"medium"/"slow") property ([**@wwhurin**](https://github.com/wwhurin))
40
+ - [#4464](https://github.com/mochajs/mocha/issues/4464): Errors thrown by serializer in parallel mode now have error codes ([**@evaline-ju**](https://github.com/evaline-ju))
41
+
42
+ _For implementors of custom reporters:_
43
+
44
+ - [#4409](https://github.com/mochajs/mocha/issues/4409): Parallel mode and custom reporter improvements ([**@boneskull**](https://github.com/boneskull)):
45
+ - Support custom worker-process-only reporters (`Runner.prototype.workerReporter()`); reporters should subclass `ParallelBufferedReporter` in `mocha/lib/nodejs/reporters/parallel-buffered`
46
+ - Allow opt-in of object reference matching for "sufficiently advanced" custom reporters (`Runner.prototype.linkPartialObjects()`); use if strict object equality is needed when consuming `Runner` event data
47
+ - Enable detection of parallel mode (`Runner.prototype.isParallelMode()`)
48
+
49
+ ## :bug: Fixes
50
+
51
+ - [#4476](https://github.com/mochajs/mocha/issues/4476): Workaround for profoundly bizarre issue affecting `npm` v6.x causing some of Mocha's deps to be installed when `mocha` is present in a package's `devDependencies` and `npm install --production` is run the package's working copy ([**@boneskull**](https://github.com/boneskull))
52
+ - [#4465](https://github.com/mochajs/mocha/issues/4465): Worker processes guaranteed (as opposed to "very likely") to exit before Mocha does; fixes a problem when using `nyc` with Mocha in parallel mode ([**@boneskull**](https://github.com/boneskull))
53
+ - [#4419](https://github.com/mochajs/mocha/issues/4419): Restore `lookupFiles()` in `mocha/lib/utils`, which was broken/missing in Mocha v8.1.0; it now prints a deprecation warning (use `const {lookupFiles} = require('mocha/lib/cli')` instead) ([**@boneskull**](https://github.com/boneskull))
54
+
55
+ Thanks to [**@AviVahl**](https://github.com/AviVahl), [**@donghoon-song**](https://github.com/donghoon-song), [**@ValeriaVG**](https://github.com/ValeriaVG), [**@znarf**](https://github.com/znarf), [**@sujin-park**](https://github.com/sujin-park), and [**@majecty**](https://github.com/majecty) for other helpful contributions!
56
+
1
57
  # 8.1.3 / 2020-08-28
2
58
 
3
59
  ## :bug: Fixes
@@ -9,7 +65,7 @@
9
65
  ## :bug: Fixes
10
66
 
11
67
  - [#4418](https://github.com/mochajs/mocha/issues/4418): Fix command-line flag incompatibility in forthcoming Node.js v14.9.0 ([**@boneskull**](https://github.com/boneskull))
12
- - [#4401](https://github.com/mochajs/mocha/issues/4401): Fix missing global variable in browser ([**@irrationelle**](https://github.com/irrationelle))
68
+ - [#4401](https://github.com/mochajs/mocha/issues/4401): Fix missing global variable in browser ([**@irrationnelle**](https://github.com/irrationnelle))
13
69
 
14
70
  ## :lock: Security Fixes
15
71
 
package/README.md CHANGED
@@ -7,6 +7,8 @@
7
7
  <p align="center"><a href="http://travis-ci.org/mochajs/mocha"><img src="https://api.travis-ci.org/mochajs/mocha.svg?branch=master" alt="Build Status"></a> <a href="https://coveralls.io/github/mochajs/mocha"><img src="https://coveralls.io/repos/github/mochajs/mocha/badge.svg" alt="Coverage Status"></a> <a href="https://app.fossa.io/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmochajs%2Fmocha?ref=badge_shield"><img src="https://app.fossa.io/api/projects/git%2Bhttps%3A%2F%2Fgithub.com%2Fmochajs%2Fmocha.svg?type=shield" alt="FOSSA Status"></a> <a href="https://gitter.im/mochajs/mocha?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge"><img src="https://badges.gitter.im/Join%20Chat.svg" alt="Gitter"></a> <a href="https://github.com/mochajs/mocha#backers"><img src="https://opencollective.com/mochajs/backers/badge.svg" alt="OpenCollective"></a> <a href="https://github.com/mochajs/mocha#sponsors"><img src="https://opencollective.com/mochajs/sponsors/badge.svg" alt="OpenCollective"></a>
8
8
  </p>
9
9
 
10
+ <p align="center"><a href="https://www.npmjs.com/package/mocha"><img src="https://img.shields.io/npm/v/mocha.svg" alt="NPM Version"></a> <a href="https://github.com/mochajs/mocha"><img src="https://img.shields.io/node/v/mocha.svg" alt="Node Version"></a></p>
11
+
10
12
  <p align="center"><br><img alt="Mocha Browser Support h/t SauceLabs" src="https://saucelabs.com/browser-matrix/mochajs.svg" width="354"></p>
11
13
 
12
14
  ## Links
@@ -1,5 +1,4 @@
1
1
  'use strict';
2
-
3
2
  /**
4
3
  * Contains `lookupFiles`, which takes some globs/dirs/options and returns a list of files.
5
4
  * @module
@@ -14,6 +13,7 @@ var errors = require('../errors');
14
13
  var createNoFilesMatchPatternError = errors.createNoFilesMatchPatternError;
15
14
  var createMissingArgumentError = errors.createMissingArgumentError;
16
15
  var {sQuote, dQuote} = require('../utils');
16
+ const debug = require('debug')('mocha:cli:lookup-files');
17
17
 
18
18
  /**
19
19
  * Determines if pathname would be a "hidden" file (or directory) on UN*X.
@@ -30,26 +30,26 @@ var {sQuote, dQuote} = require('../utils');
30
30
  * @example
31
31
  * isHiddenOnUnix('.profile'); // => true
32
32
  */
33
- function isHiddenOnUnix(pathname) {
34
- return path.basename(pathname)[0] === '.';
35
- }
33
+ const isHiddenOnUnix = pathname => path.basename(pathname).startsWith('.');
36
34
 
37
35
  /**
38
36
  * Determines if pathname has a matching file extension.
39
37
  *
38
+ * Supports multi-part extensions.
39
+ *
40
40
  * @private
41
41
  * @param {string} pathname - Pathname to check for match.
42
- * @param {string[]} exts - List of file extensions (sans period).
43
- * @return {boolean} whether file extension matches.
42
+ * @param {string[]} exts - List of file extensions, w/-or-w/o leading period
43
+ * @return {boolean} `true` if file extension matches.
44
44
  * @example
45
- * hasMatchingExtname('foo.html', ['js', 'css']); // => false
45
+ * hasMatchingExtname('foo.html', ['js', 'css']); // false
46
+ * hasMatchingExtname('foo.js', ['.js']); // true
47
+ * hasMatchingExtname('foo.js', ['js']); // ture
46
48
  */
47
- function hasMatchingExtname(pathname, exts) {
48
- var suffix = path.extname(pathname).slice(1);
49
- return exts.some(function(element) {
50
- return suffix === element;
51
- });
52
- }
49
+ const hasMatchingExtname = (pathname, exts = []) =>
50
+ exts
51
+ .map(ext => (ext.startsWith('.') ? ext : `.${ext}`))
52
+ .some(ext => pathname.endsWith(ext));
53
53
 
54
54
  /**
55
55
  * Lookup file names at the given `path`.
@@ -67,27 +67,28 @@ function hasMatchingExtname(pathname, exts) {
67
67
  * @throws {Error} if no files match pattern.
68
68
  * @throws {TypeError} if `filepath` is directory and `extensions` not provided.
69
69
  */
70
- module.exports = function lookupFiles(filepath, extensions, recursive) {
71
- extensions = extensions || [];
72
- recursive = recursive || false;
73
- var files = [];
74
- var stat;
70
+ module.exports = function lookupFiles(
71
+ filepath,
72
+ extensions = [],
73
+ recursive = false
74
+ ) {
75
+ const files = [];
76
+ let stat;
75
77
 
76
78
  if (!fs.existsSync(filepath)) {
77
- var pattern;
79
+ let pattern;
78
80
  if (glob.hasMagic(filepath)) {
79
81
  // Handle glob as is without extensions
80
82
  pattern = filepath;
81
83
  } else {
82
84
  // glob pattern e.g. 'filepath+(.js|.ts)'
83
- var strExtensions = extensions
84
- .map(function(v) {
85
- return '.' + v;
86
- })
85
+ const strExtensions = extensions
86
+ .map(ext => (ext.startsWith('.') ? ext : `.${ext}`))
87
87
  .join('|');
88
- pattern = filepath + '+(' + strExtensions + ')';
88
+ pattern = `${filepath}+(${strExtensions})`;
89
+ debug('looking for files using glob pattern: %s', pattern);
89
90
  }
90
- files = glob.sync(pattern, {nodir: true});
91
+ files.push(...glob.sync(pattern, {nodir: true}));
91
92
  if (!files.length) {
92
93
  throw createNoFilesMatchPatternError(
93
94
  'Cannot find any files matching pattern ' + dQuote(filepath),
@@ -109,20 +110,19 @@ module.exports = function lookupFiles(filepath, extensions, recursive) {
109
110
  }
110
111
 
111
112
  // Handle directory
112
- fs.readdirSync(filepath).forEach(function(dirent) {
113
- var pathname = path.join(filepath, dirent);
114
- var stat;
113
+ fs.readdirSync(filepath).forEach(dirent => {
114
+ const pathname = path.join(filepath, dirent);
115
+ let stat;
115
116
 
116
117
  try {
117
118
  stat = fs.statSync(pathname);
118
119
  if (stat.isDirectory()) {
119
120
  if (recursive) {
120
- files = files.concat(lookupFiles(pathname, extensions, recursive));
121
+ files.push(...lookupFiles(pathname, extensions, recursive));
121
122
  }
122
123
  return;
123
124
  }
124
- } catch (err) {
125
- // ignore error
125
+ } catch (ignored) {
126
126
  return;
127
127
  }
128
128
  if (!extensions.length) {
@@ -12,10 +12,10 @@ const path = require('path');
12
12
  const debug = require('debug')('mocha:cli:run:helpers');
13
13
  const {watchRun, watchParallelRun} = require('./watch-run');
14
14
  const collectFiles = require('./collect-files');
15
- const {type} = require('../utils');
16
15
  const {format} = require('util');
17
- const {createInvalidPluginError, createUnsupportedError} = require('../errors');
16
+ const {createInvalidLegacyPluginError} = require('../errors');
18
17
  const {requireOrImport} = require('../esm-utils');
18
+ const PluginLoader = require('../plugin-loader');
19
19
 
20
20
  /**
21
21
  * Exits Mocha when tests + code under test has finished execution (default)
@@ -79,12 +79,12 @@ exports.list = str =>
79
79
  *
80
80
  * Returns array of `mochaHooks` exports, if any.
81
81
  * @param {string[]} requires - Modules to require
82
- * @returns {Promise<MochaRootHookObject|MochaRootHookFunction>} Any root hooks
82
+ * @returns {Promise<object>} Plugin implementations
83
83
  * @private
84
84
  */
85
- exports.handleRequires = async (requires = []) => {
86
- const acc = [];
87
- for (const mod of requires) {
85
+ exports.handleRequires = async (requires = [], {ignoredPlugins = []} = {}) => {
86
+ const pluginLoader = PluginLoader.create({ignore: ignoredPlugins});
87
+ for await (const mod of requires) {
88
88
  let modpath = mod;
89
89
  // this is relative to cwd
90
90
  if (fs.existsSync(mod) || fs.existsSync(`${mod}.js`)) {
@@ -92,49 +92,18 @@ exports.handleRequires = async (requires = []) => {
92
92
  debug('resolved required file %s to %s', mod, modpath);
93
93
  }
94
94
  const requiredModule = await requireOrImport(modpath);
95
- if (
96
- requiredModule &&
97
- typeof requiredModule === 'object' &&
98
- requiredModule.mochaHooks
99
- ) {
100
- const mochaHooksType = type(requiredModule.mochaHooks);
101
- if (/function$/.test(mochaHooksType) || mochaHooksType === 'object') {
102
- debug('found root hooks in required file %s', mod);
103
- acc.push(requiredModule.mochaHooks);
104
- } else {
105
- throw createUnsupportedError(
106
- 'mochaHooks must be an object or a function returning (or fulfilling with) an object'
107
- );
95
+ if (requiredModule && typeof requiredModule === 'object') {
96
+ if (pluginLoader.load(requiredModule)) {
97
+ debug('found one or more plugin implementations in %s', modpath);
108
98
  }
109
99
  }
110
100
  debug('loaded required module "%s"', mod);
111
101
  }
112
- return acc;
113
- };
114
-
115
- /**
116
- * Loads root hooks as exported via `mochaHooks` from required files.
117
- * These can be sync/async functions returning objects, or just objects.
118
- * Flattens to a single object.
119
- * @param {Array<MochaRootHookObject|MochaRootHookFunction>} rootHooks - Array of root hooks
120
- * @private
121
- * @returns {MochaRootHookObject}
122
- */
123
- exports.loadRootHooks = async rootHooks => {
124
- const rootHookObjects = await Promise.all(
125
- rootHooks.map(async hook => (/function$/.test(type(hook)) ? hook() : hook))
126
- );
127
-
128
- return rootHookObjects.reduce(
129
- (acc, hook) => {
130
- acc.beforeAll = acc.beforeAll.concat(hook.beforeAll || []);
131
- acc.beforeEach = acc.beforeEach.concat(hook.beforeEach || []);
132
- acc.afterAll = acc.afterAll.concat(hook.afterAll || []);
133
- acc.afterEach = acc.afterEach.concat(hook.afterEach || []);
134
- return acc;
135
- },
136
- {beforeAll: [], beforeEach: [], afterAll: [], afterEach: []}
137
- );
102
+ const plugins = await pluginLoader.finalize();
103
+ if (Object.keys(plugins).length) {
104
+ debug('finalized plugin implementations: %O', plugins);
105
+ }
106
+ return plugins;
138
107
  };
139
108
 
140
109
  /**
@@ -172,11 +141,7 @@ const singleRun = async (mocha, {exit}, fileCollectParams) => {
172
141
  */
173
142
  const parallelRun = async (mocha, options, fileCollectParams) => {
174
143
  const files = collectFiles(fileCollectParams);
175
- debug(
176
- 'executing %d test file(s) across %d concurrent jobs',
177
- files.length,
178
- options.jobs
179
- );
144
+ debug('executing %d test file(s) in parallel mode', files.length);
180
145
  mocha.files = files;
181
146
 
182
147
  // note that we DO NOT load any files here; this is handled by the worker
@@ -236,7 +201,7 @@ exports.runMocha = async (mocha, options) => {
236
201
  * name
237
202
  * @private
238
203
  */
239
- exports.validatePlugin = (opts, pluginType, map = {}) => {
204
+ exports.validateLegacyPlugin = (opts, pluginType, map = {}) => {
240
205
  /**
241
206
  * This should be a unique identifier; either a string (present in `map`),
242
207
  * or a resolvable (via `require.resolve`) module ID/path.
@@ -245,14 +210,14 @@ exports.validatePlugin = (opts, pluginType, map = {}) => {
245
210
  const pluginId = opts[pluginType];
246
211
 
247
212
  if (Array.isArray(pluginId)) {
248
- throw createInvalidPluginError(
213
+ throw createInvalidLegacyPluginError(
249
214
  `"--${pluginType}" can only be specified once`,
250
215
  pluginType
251
216
  );
252
217
  }
253
218
 
254
- const unknownError = err =>
255
- createInvalidPluginError(
219
+ const createUnknownError = err =>
220
+ createInvalidLegacyPluginError(
256
221
  format('Could not load %s "%s":\n\n %O', pluginType, pluginId, err),
257
222
  pluginType,
258
223
  pluginId
@@ -268,10 +233,10 @@ exports.validatePlugin = (opts, pluginType, map = {}) => {
268
233
  try {
269
234
  opts[pluginType] = require(path.resolve(pluginId));
270
235
  } catch (err) {
271
- throw unknownError(err);
236
+ throw createUnknownError(err);
272
237
  }
273
238
  } else {
274
- throw unknownError(err);
239
+ throw createUnknownError(err);
275
240
  }
276
241
  }
277
242
  }
package/lib/cli/run.js CHANGED
@@ -19,8 +19,7 @@ const {
19
19
  const {
20
20
  list,
21
21
  handleRequires,
22
- validatePlugin,
23
- loadRootHooks,
22
+ validateLegacyPlugin,
24
23
  runMocha
25
24
  } = require('./run-helpers');
26
25
  const {ONE_AND_DONES, ONE_AND_DONE_ARGS} = require('./one-and-dones');
@@ -339,13 +338,10 @@ exports.builder = yargs =>
339
338
  // currently a failing middleware does not work nicely with yargs' `fail()`.
340
339
  try {
341
340
  // load requires first, because it can impact "plugin" validation
342
- const rawRootHooks = await handleRequires(argv.require);
343
- validatePlugin(argv, 'reporter', Mocha.reporters);
344
- validatePlugin(argv, 'ui', Mocha.interfaces);
345
-
346
- if (rawRootHooks && rawRootHooks.length) {
347
- argv.rootHooks = await loadRootHooks(rawRootHooks);
348
- }
341
+ const plugins = await handleRequires(argv.require);
342
+ validateLegacyPlugin(argv, 'reporter', Mocha.reporters);
343
+ validateLegacyPlugin(argv, 'ui', Mocha.interfaces);
344
+ Object.assign(argv, plugins);
349
345
  } catch (err) {
350
346
  // this could be a bad --require, bad reporter, ui, etc.
351
347
  console.error(`\n${symbols.error} ${ansi.red('ERROR:')}`, err);
@@ -1,5 +1,6 @@
1
1
  'use strict';
2
2
 
3
+ const logSymbols = require('log-symbols');
3
4
  const debug = require('debug')('mocha:cli:watch');
4
5
  const path = require('path');
5
6
  const chokidar = require('chokidar');
@@ -32,6 +33,7 @@ exports.watchParallelRun = (
32
33
  fileCollectParams
33
34
  ) => {
34
35
  debug('creating parallel watcher');
36
+
35
37
  return createWatcher(mocha, {
36
38
  watchFiles,
37
39
  watchIgnore,
@@ -68,9 +70,6 @@ exports.watchParallelRun = (
68
70
  newMocha.lazyLoadFiles(true);
69
71
  return newMocha;
70
72
  },
71
- afterRun({watcher}) {
72
- blastCache(watcher);
73
- },
74
73
  fileCollectParams
75
74
  });
76
75
  };
@@ -91,7 +90,6 @@ exports.watchParallelRun = (
91
90
  */
92
91
  exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
93
92
  debug('creating serial watcher');
94
- // list of all test files
95
93
 
96
94
  return createWatcher(mocha, {
97
95
  watchFiles,
@@ -128,9 +126,6 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
128
126
 
129
127
  return newMocha;
130
128
  },
131
- afterRun({watcher}) {
132
- blastCache(watcher);
133
- },
134
129
  fileCollectParams
135
130
  });
136
131
  };
@@ -141,7 +136,6 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
141
136
  * @param {Object} opts
142
137
  * @param {BeforeWatchRun} [opts.beforeRun] - Function to call before
143
138
  * `mocha.run()`
144
- * @param {AfterWatchRun} [opts.afterRun] - Function to call after `mocha.run()`
145
139
  * @param {string[]} [opts.watchFiles] - List of paths and patterns to watch. If
146
140
  * not provided all files with an extension included in
147
141
  * `fileCollectionParams.extension` are watched. See first argument of
@@ -155,13 +149,17 @@ exports.watchRun = (mocha, {watchFiles, watchIgnore}, fileCollectParams) => {
155
149
  */
156
150
  const createWatcher = (
157
151
  mocha,
158
- {watchFiles, watchIgnore, beforeRun, afterRun, fileCollectParams}
152
+ {watchFiles, watchIgnore, beforeRun, fileCollectParams}
159
153
  ) => {
160
154
  if (!watchFiles) {
161
155
  watchFiles = fileCollectParams.extension.map(ext => `**/*.${ext}`);
162
156
  }
163
157
 
164
158
  debug('ignoring files matching: %s', watchIgnore);
159
+ let globalFixtureContext;
160
+
161
+ // we handle global fixtures manually
162
+ mocha.enableGlobalSetup(false).enableGlobalTeardown(false);
165
163
 
166
164
  const watcher = chokidar.watch(watchFiles, {
167
165
  ignored: watchIgnore,
@@ -169,11 +167,14 @@ const createWatcher = (
169
167
  });
170
168
 
171
169
  const rerunner = createRerunner(mocha, watcher, {
172
- beforeRun,
173
- afterRun
170
+ beforeRun
174
171
  });
175
172
 
176
- watcher.on('ready', () => {
173
+ watcher.on('ready', async () => {
174
+ if (!globalFixtureContext) {
175
+ debug('triggering global setup');
176
+ globalFixtureContext = await mocha.runGlobalSetup();
177
+ }
177
178
  rerunner.run();
178
179
  });
179
180
 
@@ -185,10 +186,39 @@ const createWatcher = (
185
186
  process.on('exit', () => {
186
187
  showCursor();
187
188
  });
188
- process.on('SIGINT', () => {
189
+
190
+ // this is for testing.
191
+ // win32 cannot gracefully shutdown via a signal from a parent
192
+ // process; a `SIGINT` from a parent will cause the process
193
+ // to immediately exit. during normal course of operation, a user
194
+ // will type Ctrl-C and the listener will be invoked, but this
195
+ // is not possible in automated testing.
196
+ // there may be another way to solve this, but it too will be a hack.
197
+ // for our watch tests on win32 we must _fork_ mocha with an IPC channel
198
+ if (process.connected) {
199
+ process.on('message', msg => {
200
+ if (msg === 'SIGINT') {
201
+ process.emit('SIGINT');
202
+ }
203
+ });
204
+ }
205
+
206
+ let exiting = false;
207
+ process.on('SIGINT', async () => {
189
208
  showCursor();
190
- console.log('\n');
191
- process.exit(128 + 2);
209
+ console.error(`${logSymbols.warning} [mocha] cleaning up, please wait...`);
210
+ if (!exiting) {
211
+ exiting = true;
212
+ if (mocha.hasGlobalTeardownFixtures()) {
213
+ debug('running global teardown');
214
+ try {
215
+ await mocha.runGlobalTeardown(globalFixtureContext);
216
+ } catch (err) {
217
+ console.error(err);
218
+ }
219
+ }
220
+ process.exit(130);
221
+ }
192
222
  });
193
223
 
194
224
  // Keyboard shortcut for restarting when "rs\n" is typed (ala Nodemon)
@@ -212,12 +242,11 @@ const createWatcher = (
212
242
  * @param {FSWatcher} watcher - chokidar `FSWatcher` instance
213
243
  * @param {Object} [opts] - Options!
214
244
  * @param {BeforeWatchRun} [opts.beforeRun] - Function to call before `mocha.run()`
215
- * @param {AfterWatchRun} [opts.afterRun] - Function to call after `mocha.run()`
216
245
  * @returns {Rerunner}
217
246
  * @ignore
218
247
  * @private
219
248
  */
220
- const createRerunner = (mocha, watcher, {beforeRun, afterRun} = {}) => {
249
+ const createRerunner = (mocha, watcher, {beforeRun} = {}) => {
221
250
  // Set to a `Runner` when mocha is running. Set to `null` when mocha is not
222
251
  // running.
223
252
  let runner = null;
@@ -226,16 +255,15 @@ const createRerunner = (mocha, watcher, {beforeRun, afterRun} = {}) => {
226
255
  let rerunScheduled = false;
227
256
 
228
257
  const run = () => {
229
- mocha = beforeRun ? beforeRun({mocha, watcher}) : mocha;
230
-
258
+ mocha = beforeRun ? beforeRun({mocha, watcher}) || mocha : mocha;
231
259
  runner = mocha.run(() => {
232
260
  debug('finished watch run');
233
261
  runner = null;
234
- afterRun && afterRun({mocha, watcher});
262
+ blastCache(watcher);
235
263
  if (rerunScheduled) {
236
264
  rerun();
237
265
  } else {
238
- debug('waiting for changes...');
266
+ console.error(`${logSymbols.info} [mocha] waiting for changes...`);
239
267
  }
240
268
  });
241
269
  };
@@ -333,15 +361,6 @@ const blastCache = watcher => {
333
361
  * @returns {Mocha}
334
362
  */
335
363
 
336
- /**
337
- * Callback to be run after `mocha.run()` completes. Typically used to clear
338
- * require cache.
339
- * @callback AfterWatchRun
340
- * @private
341
- * @param {{mocha: Mocha, watcher: FSWatcher}} options
342
- * @returns {void}
343
- */
344
-
345
364
  /**
346
365
  * Object containing run control methods
347
366
  * @typedef {Object} Rerunner