☕️ Classic, reliable, trusted test framework for Node.js and the browser
Revert "fix: begin running tests immediately instead of waiting for w… (#5881)
Mark Wiemer46cd926c2768
diff --git a/.knip.jsonc b/.knip.jsoncindex a087dbc7..4929d751 100644--- a/.knip.jsonc+++ b/.knip.jsonc@@ -11,9 +11,7 @@"project": ["{bin,lib,scripts,test}/**/*.{js,ts,mjs,cjs}"],"ignore": ["test/integration/fixtures/esm/type-module/test-that-imports-non-existing-module.fixture.js",- "test/integration/fixtures/options/watch/mock-global-setup-with-dependency.fixture.js","test/integration/fixtures/options/watch/test-with-dependency.fixture.js",- "test/integration/fixtures/options/watch/test-with-dependency-and-barrier.fixture.js",],"ignoreDependencies": ["@test/esm-only-loader",diff --git a/lib/cli/run-helpers.js b/lib/cli/run-helpers.jsindex 9f91e6e5..d83b76f1 100644--- a/lib/cli/run-helpers.js+++ b/lib/cli/run-helpers.js@@ -87,22 +87,16 @@ exports.list = (str) =>Array.isArray(str) ? exports.list(str.join(",")) : str.split(/ *, */);/**- * `import()` or `require()` the modules as required by `--require <require>`.+ * `require()` the modules as required by `--require <require>`.** Returns array of `mochaHooks` exports, if any.* @param {string[]} requires - Modules to require- * @param {Object} [opts] - additional options- * @param {string[]} [opts.ignoredPlugins] - ignored plugins by export name- * @param {boolean} [opts.forceRequire] - if true, don't try to `import()`- * the modules. Watch serial mode uses this to ensure root hook modules- * get `require()`d, because if `import()`ed there's no way to reload them- * after they've changed.* @returns {Promise<object>} Plugin implementations* @private*/exports.handleRequires = async (requires = [],- { ignoredPlugins = [], forceRequire } = {},+ { ignoredPlugins = [] } = {},) => {const pluginLoader = PluginLoader.create({ ignore: ignoredPlugins });for await (const mod of requires) {@@ -112,9 +106,7 @@ exports.handleRequires = async (modpath = path.resolve(mod);debug("resolved required file %s to %s", mod, modpath);}- const requiredModule = forceRequire- ? require(modpath)- : await requireOrImport(modpath);+ const requiredModule = await requireOrImport(modpath);if (requiredModule && typeof requiredModule === "object") {if (pluginLoader.load(requiredModule)) {debug("found one or more plugin implementations in %s", modpath);diff --git a/lib/cli/watch-run.js b/lib/cli/watch-run.jsindex f8887209..495d1e28 100644--- a/lib/cli/watch-run.js+++ b/lib/cli/watch-run.js@@ -1,7 +1,5 @@"use strict";-const { clearTimeout, setTimeout } = global;-const debug = require("debug")("mocha:cli:watch");const path = require("node:path");const chokidar = require("chokidar");@@ -10,7 +8,6 @@ const isPathInside = require("is-path-inside");const { minimatch } = require("minimatch");const Context = require("../context.mjs").Context;const collectFiles = require("./collect-files");-const runHelpers = require("./run-helpers");const { logSymbols } = require("../utils");/**@@ -57,7 +54,7 @@ exports.watchParallelRun = (return createWatcher(mocha, {watchFiles,watchIgnore,- async beforeRun({ mocha }) {+ beforeRun({ mocha }) {// I don't know why we're cloning the root suite.const rootSuite = mocha.suite.clone();@@ -69,12 +66,9 @@ exports.watchParallelRun = (// test depends on this module.const Mocha = require("../mocha");- // reload rootHooks and other plugins, in case those files have changed- const plugins = await runHelpers.handleRequires(mocha.options.require);-// ... and now that we've gotten a new module, we need to use it again due// to `mocha.ui()` call- const newMocha = new Mocha(Object.assign({}, mocha.options, plugins));+ const newMocha = new Mocha(mocha.options);// don't know why this is needednewMocha.suite = rootSuite;// nor this@@ -120,7 +114,9 @@ exports.watchRun = (mocha, { watchFiles, watchIgnore }, fileCollectParams) => {return createWatcher(mocha, {watchFiles,watchIgnore,- async beforeRun({ mocha }) {+ beforeRun({ mocha }) {+ mocha.unloadFiles();+// I don't know why we're cloning the root suite.const rootSuite = mocha.suite.clone();@@ -132,17 +128,9 @@ exports.watchRun = (mocha, { watchFiles, watchIgnore }, fileCollectParams) => {// test depends on this module.const Mocha = require("../mocha");- // reload rootHooks and other plugins, in case those files have changed- const plugins = await runHelpers.handleRequires(mocha.options.require, {- // disable requireOrImport, since if the module gets loaded via ESM- // the cache won't get busted between runs.- // watch serial mode doesn't currently support ESM anyway.- forceRequire: true,- });-// ... and now that we've gotten a new module, we need to use it again due// to `mocha.ui()` call- const newMocha = new Mocha({ ...mocha.options, ...plugins });+ const newMocha = new Mocha(mocha.options);// don't know why this is needednewMocha.suite = rootSuite;// nor this@@ -397,19 +385,6 @@ function createPathMatcher(allowed, ignored, basePath) {return matcher;}-const TEST_MODE = Boolean(process.env.__MOCHA_WATCH_MOCK_CHOKIDAR);--// grab Date.now before anything like sinon.createFakeTimers can monkeypatch it-// eslint-disable-next-line no-restricted-globals-const dateNow = Date.now;-if (TEST_MODE) debug("in test mode");--const sendMessage = (msg) => {- if (!TEST_MODE) return;- process.send(msg);- debug("sent message", msg);-};-/*** Bootstraps a Chokidar watcher. Handles keyboard input & signals* @param {Mocha} mocha - Mocha instance@@ -454,70 +429,29 @@ const createWatcher = (const matcher = createPathMatcher(allowed, ignored, basePath);// Chokidar has to watch the directory paths in case new files are created- let watcher;- /* istanbul ignore next */- if (TEST_MODE) {- const EventEmitter = require("node:events");- watcher = new EventEmitter();- process.on("message", (msg) => {- debug("got message", msg);- if (msg.watcher) watcher.emit(...msg.watcher);- });- } else {- watcher = chokidar.watch(Array.from(allowed.dir.paths), {- ignoreInitial: true,- ignored: matcher.ignore,- alwaysStat: true,- });- }-- // if files change during global setup, we need to blast the cache before the first- // run in case any tests depend on changed modules that were loaded by global setup- let blastCacheBeforeNextRun = false;- const rerunner = createRerunner(mocha, watcher, matcher, {- beforeRun: async (opts) => {- if (blastCacheBeforeNextRun) {- blastCacheBeforeNextRun = false;- blastCache(matcher);- }- return await beforeRun(opts);- },+ const watcher = chokidar.watch(Array.from(allowed.dir.paths), {+ ignoreInitial: true,+ ignored: matcher.ignore,});- const startTime = dateNow();- debug("start time: %d", startTime);+ const rerunner = createRerunner(mocha, watcher, {+ beforeRun,+ });- watcher.on("all", function handleEvent(...args) {- const [event, filePath, stat] = args;- /* istanbul ignore next */- if (TEST_MODE) sendMessage({ received: ["all", ...args] });- if (exiting) return;- if (!matcher.allow(filePath)) {- debug("event doesn't match filter: %s, %s", event, filePath);- return;- }- if (- event === "unlink" ||- // birthtime can be > mtime on some filesystems; also check ctime just in case- (stat && Math.max(stat.mtime, stat.ctime, stat.birthtime) > startTime)- ) {- // we don't want to accidentally trigger a run before globalFixtureContext- // has been created. If it hasn't then it's okay to do nothing here because- // the code that creates globalFixtureContext will run the tests afterward- if (globalFixtureContext) rerunner.scheduleRun();- // if files change during global setup, we need to blast the cache before the first- // run in case any tests depend on changed modules that were loaded by global setup- else blastCacheBeforeNextRun = true;+ watcher.on("ready", async () => {+ debug("watcher ready");+ if (!globalFixtureContext) {+ debug("triggering global setup");+ globalFixtureContext = await mocha.runGlobalSetup();}+ rerunner.run();});- /* istanbul ignore next */- if (TEST_MODE) sendMessage({ listening: true, startTime });-- debug("triggering global setup");- mocha.runGlobalSetup().then((context) => {- globalFixtureContext = context;- return rerunner.run();+ watcher.on("all", (_event, filePath) => {+ // only allow file paths that match the allowed patterns+ if (matcher.allow(filePath)) {+ rerunner.scheduleRun();+ }});hideCursor();@@ -575,71 +509,51 @@ const createWatcher = (** @param {Mocha} mocha - Mocha instance* @param {FSWatcher} watcher - Chokidar `FSWatcher` instance- * @param {PathMatcher} matcher - `PathMatcher` instance- * @param {Object} opts - Options!- * @param {BeforeWatchRun} opts.beforeRun - Function to call before `mocha.run()`. Must be provided.+ * @param {Object} [opts] - Options!+ * @param {BeforeWatchRun} [opts.beforeRun] - Function to call before `mocha.run()`* @returns {Rerunner}* @ignore* @private*/-const createRerunner = (mocha, watcher, matcher, { beforeRun }) => {- // Set to `Runner.abort` when mocha is running. Set to another abort function- // during `beforeRun()`. Set to `null` otherwise.- let abortRun = null;+const createRerunner = (mocha, watcher, { beforeRun } = {}) => {+ // Set to a `Runner` when mocha is running. Set to `null` when mocha is not+ // running.+ let runner = null;// true if a file has changed during a test runlet rerunScheduled = false;- const run = async () => {+ const run = () => {try {- if (TEST_MODE) sendMessage({ run: true });- let aborted = false;- abortRun = () => (aborted = true);- mocha = (await beforeRun({ mocha, watcher })) || mocha;- if (aborted) {- abortRun = null;- blastCache(matcher);- rerun();- }- const runner = mocha.run(() => {+ mocha = beforeRun ? beforeRun({ mocha, watcher }) || mocha : mocha;+ runner = mocha.run(() => {debug("finished watch run");- if (TEST_MODE) sendMessage({ runFinished: true });- abortRun = null;- blastCache(matcher);+ runner = null;+ blastCache(watcher);if (rerunScheduled) {rerun();} else {console.error(`${logSymbols.info} [mocha] waiting for changes...`);}});- abortRun = () => runner.abort();} catch (err) {- abortRun = null;console.error(err.stack);}};const scheduleRun = () => {- if (TEST_MODE) sendMessage({ scheduleRun: true });if (rerunScheduled) {return;}rerunScheduled = true;- if (abortRun) {- abortRun();+ if (runner) {+ runner.abort();} else {- debounceRerun();+ rerun();}};- let rerunTimeout;-- const debounceRerun = () => {- clearTimeout(rerunTimeout);- rerunTimeout = setTimeout(rerun, 10);- };-const rerun = () => {rerunScheduled = false;eraseLine();@@ -652,6 +566,25 @@ const createRerunner = (mocha, watcher, matcher, { beforeRun }) => {};};+/**+ * Return the list of absolute paths watched by a Chokidar watcher.+ *+ * @param watcher - Instance of a Chokidar watcher+ * @return {string[]} - List of absolute paths+ * @ignore+ * @private+ */+const getWatchedFiles = (watcher) => {+ const watchedDirs = watcher.getWatched();+ return Object.keys(watchedDirs).reduce(+ (acc, dir) => [+ ...acc,+ ...watchedDirs[dir].map((file) => path.join(dir, file)),+ ],+ [],+ );+};+/*** Hide the cursor.* @ignore@@ -680,17 +613,14 @@ const eraseLine = () => {/*** Blast all of the watched files out of `require.cache`- * @param {PathMatcher} matcher - only delete keys allowed by this matcher+ * @param {FSWatcher} watcher - Chokidar FSWatcher* @ignore* @private*/-const blastCache = (matcher) => {- let deletedCount = 0;- for (const key in require.cache) {- if (matcher.allow(key)) {- deletedCount++;- delete require.cache[key];- }- }- debug("deleted %d file(s) from the require cache", deletedCount);+const blastCache = (watcher) => {+ const files = getWatchedFiles(watcher);+ files.forEach((file) => {+ delete require.cache[file];+ });+ debug("deleted %d file(s) from the require cache", files.length);};diff --git a/lib/mocha.js b/lib/mocha.jsindex a6bec3b4..d84784b5 100644--- a/lib/mocha.js+++ b/lib/mocha.js@@ -975,88 +975,79 @@ Object.defineProperty(Mocha.prototype, "version", {Mocha.prototype.run = function (fn) {this._guardRunningStateTransition();this._state = mochaStates.RUNNING;- try {- if (this._previousRunner) {- this._previousRunner.dispose();- this.suite.reset();- }- if (this.files.length && !this._lazyLoadFiles) {- this.loadFiles();+ if (this._previousRunner) {+ this._previousRunner.dispose();+ this.suite.reset();+ }+ if (this.files.length && !this._lazyLoadFiles) {+ this.loadFiles();+ }+ var suite = this.suite;+ var options = this.options;+ options.files = this.files;+ const runner = new this._runnerClass(suite, {+ cleanReferencesAfterRun: this._cleanReferencesAfterRun,+ delay: options.delay,+ dryRun: options.dryRun,+ failHookAffectedTests: options.failHookAffectedTests,+ failZero: options.failZero,+ });+ createStatsCollector(runner);+ var reporter = new this._reporter(runner, options);+ runner.checkLeaks = options.checkLeaks === true;+ runner.fullStackTrace = options.fullTrace;+ runner.asyncOnly = options.asyncOnly;+ runner.allowUncaught = options.allowUncaught;+ runner.forbidOnly = options.forbidOnly;+ runner.forbidPending = options.forbidPending;+ if (options.grep) {+ runner.grep(options.grep, options.invert);+ }+ if (options.global) {+ runner.globals(options.global);+ }+ if (options.color !== undefined) {+ exports.reporters.Base.useColors = options.color;+ }+ exports.reporters.Base.inlineDiffs = options.inlineDiffs;+ exports.reporters.Base.hideDiff = !options.diff;++ const done = (failures) => {+ this._previousRunner = runner;+ this._state = this._cleanReferencesAfterRun+ ? mochaStates.REFERENCES_CLEANED+ : mochaStates.INIT;+ fn = fn || utils.noop;+ if (typeof reporter.done === "function") {+ reporter.done(failures, fn);+ } else {+ fn(failures);}+ };- var suite = this.suite;- var options = this.options;- options.files = this.files;- const runner = new this._runnerClass(suite, {- cleanReferencesAfterRun: this._cleanReferencesAfterRun,- delay: options.delay,- dryRun: options.dryRun,- failHookAffectedTests: options.failHookAffectedTests,- failZero: options.failZero,+ const runAsync = async (runner) => {+ const context =+ this.options.enableGlobalSetup && this.hasGlobalSetupFixtures()+ ? await this.runGlobalSetup(runner)+ : {};+ const failureCount = await runner.runAsync({+ files: this.files,+ options,});- createStatsCollector(runner);- var reporter = new this._reporter(runner, options);- runner.checkLeaks = options.checkLeaks === true;- runner.fullStackTrace = options.fullTrace;- runner.asyncOnly = options.asyncOnly;- runner.allowUncaught = options.allowUncaught;- runner.forbidOnly = options.forbidOnly;- runner.forbidPending = options.forbidPending;- if (options.grep) {- runner.grep(options.grep, options.invert);+ if (this.options.enableGlobalTeardown && this.hasGlobalTeardownFixtures()) {+ await this.runGlobalTeardown(runner, { context });}- if (options.global) {- runner.globals(options.global);- }- if (options.color !== undefined) {- exports.reporters.Base.useColors = options.color;- }- exports.reporters.Base.inlineDiffs = options.inlineDiffs;- exports.reporters.Base.hideDiff = !options.diff;-- const done = (failures) => {- this._previousRunner = runner;- this._state = this._cleanReferencesAfterRun- ? mochaStates.REFERENCES_CLEANED- : mochaStates.INIT;- fn = fn || utils.noop;- if (typeof reporter.done === "function") {- reporter.done(failures, fn);- } else {- fn(failures);- }- };-- const runAsync = async (runner) => {- const context =- this.options.enableGlobalSetup && this.hasGlobalSetupFixtures()- ? await this.runGlobalSetup(runner)- : {};- const failureCount = await runner.runAsync({- files: this.files,- options,- });- if (- this.options.enableGlobalTeardown &&- this.hasGlobalTeardownFixtures()- ) {- await this.runGlobalTeardown(runner, { context });- }- return failureCount;- };-- // no "catch" here is intentional. errors coming out of- // Runner#run are considered uncaught/unhandled and caught- // by the `process` event listeners.- // also: returning anything other than `runner` would be a breaking- // change- runAsync(runner).then(done);-- return runner;- } catch (error) {- this._state = mochaStates.INIT;- throw error;- }+ return failureCount;+ };++ // no "catch" here is intentional. errors coming out of+ // Runner#run are considered uncaught/unhandled and caught+ // by the `process` event listeners.+ // also: returning anything other than `runner` would be a breaking+ // change+ runAsync(runner).then(done);++ return runner;};/**diff --git a/lib/types.d.ts b/lib/types.d.tsindex 78f3ad65..7b5e9858 100644--- a/lib/types.d.ts+++ b/lib/types.d.ts@@ -241,7 +241,7 @@ export interface BeforeWatchRunOptions {* Optionally, it can return a new `Mocha` instance.* @private*/-export type BeforeWatchRun = (options: BeforeWatchRunOptions) => Promise<Mocha>;+export type BeforeWatchRun = (options: BeforeWatchRunOptions) => Mocha;/*** Object containing run control methodsdiff --git a/test/integration/fixtures/options/watch/mock-global-setup-with-dependency.fixture.js b/test/integration/fixtures/options/watch/mock-global-setup-with-dependency.fixture.jsdeleted file mode 100644index 6eb115c0..00000000--- a/test/integration/fixtures/options/watch/mock-global-setup-with-dependency.fixture.js+++ /dev/null@@ -1,9 +0,0 @@-const { once } = require('node:events')-require('./lib/dependency');--exports.mochaGlobalSetup = async function () {- let message;- do {- [message] = await once(process, 'message');- } while (!message?.resolveGlobalSetup);-}diff --git a/test/integration/fixtures/options/watch/mock-global-setup.fixture.js b/test/integration/fixtures/options/watch/mock-global-setup.fixture.jsdeleted file mode 100644index 6020f6c9..00000000--- a/test/integration/fixtures/options/watch/mock-global-setup.fixture.js+++ /dev/null@@ -1,8 +0,0 @@-const { once } = require('node:events')--exports.mochaGlobalSetup = async function () {- let message;- do {- [message] = await once(process, 'message');- } while (!message?.resolveGlobalSetup);-}diff --git a/test/integration/fixtures/options/watch/test-with-dependency-and-barrier.fixture.js b/test/integration/fixtures/options/watch/test-with-dependency-and-barrier.fixture.jsdeleted file mode 100644index e643b1e8..00000000--- a/test/integration/fixtures/options/watch/test-with-dependency-and-barrier.fixture.js+++ /dev/null@@ -1,14 +0,0 @@-const dependency = require('./lib/dependency');-const { once } = require('node:events');--// wait for resolveTest message and then check for existing depencency.fixture.js-it('checks dependency', async () => {- process.send({ testStarted: true });- let message;- do {- [message] = await once(process, 'message');- } while (!message?.resolveTest);- if (dependency.testShouldFail === true) {- throw new Error('test failed');- }-});diff --git a/test/integration/helpers.js b/test/integration/helpers.jsindex 94ad261d..cbbea0e4 100644--- a/test/integration/helpers.js+++ b/test/integration/helpers.js@@ -493,6 +493,8 @@ async function runMochaWatchJSONAsync(args, opts, change) {);}+const touchRef = new Date();+/*** Synchronously touch a file. Creates* the file and all its parent directories if necessary.@@ -502,7 +504,6 @@ async function runMochaWatchJSONAsync(args, opts, change) {function touchFile(filepath) {fs.mkdirSync(path.dirname(filepath), { recursive: true });try {- const touchRef = new Date();fs.utimesSync(filepath, touchRef, touchRef);} catch {const fd = fs.openSync(filepath, "a");@@ -542,14 +543,7 @@ function copyFixture(fixtureName, dest) {* @returns {Promise<CreateTempDirResult>} Temp dir path and cleanup function*/const createTempDir = async () => {- // os.tmpdir() can be a symlink on some OSes, or contain 8.3 filename on Windows- // (https://en.wikipedia.org/wiki/8.3_filename)- // realpathing this prevents cases where some watch tests fail because the mock- // file watcher events they send to the mocha process don't match the watch patterns- // or require.cache entries.- const dirpath = await fsP.realpath(- await fsP.mkdtemp(path.join(os.tmpdir(), "mocha-")),- );+ const dirpath = await fsP.mkdtemp(path.join(os.tmpdir(), "mocha-"));return {dirpath,removeTempDir: async () => {diff --git a/test/integration/options/watch.spec.js b/test/integration/options/watch.spec.jsindex b9f4e7cc..8729171a 100644--- a/test/integration/options/watch.spec.js+++ b/test/integration/options/watch.spec.js@@ -1,9 +1,7 @@"use strict";const fs = require("node:fs");-const fsPromises = require("node:fs/promises");const path = require("node:path");-const { isDeepStrictEqual } = require("node:util");const {copyFixture,runMochaWatchJSONAsync,@@ -12,7 +10,6 @@ const {touchFile,replaceFileContents,createTempDir,- resolveFixturePath,DEFAULT_FIXTURE,} = require("../helpers");@@ -478,535 +475,6 @@ describe("--watch", function () {});});- const fakeWatchStat = (time) => ({- mtime: time,- ctime: time,- birthtime: time,- });-- /**- * @callback ChokidarMockChangeCallback- * @param {ChildProcess} mocha - the `mocha` CLI child process- * @param {Object} api - test api for interacting with the `mocha` prcoess- * @param {Function} api.gotMessage - function that accepts a message predicate and returns a Promise that resolves with the first- * message received from the `mocha` process matching the predicate- * @param {SendWatcherEvent} api.sendWatcherEvent - function for sending a mock chokidar event to the `mocha` process- * @param {SendFileEvent} api.sendWatcherEvent.add - function for sending a mock chokidar file add event to the `mocha` process- * @param {SendFileEvent} api.sendWatcherEvent.change - function for sending a mock chokidar file change event to the `mocha` process- * @param {SendFileEvent} api.sendWatcherEvent.unlink - function for sending a mock chokidar file unlink event to the `mocha` process- */-- /**- * Helper for running watch tests with mock chokidar events to precisely- * test behavior in different concurrent timing scenarios.- *- * @param {string[]} args - the `mocha` CLI arguments- * @param {Object} opts - additional `spawn` options for the `mocha` child process- * @param {ChokidarMockChangeCallback} change - function to perform test-specific actions- * once the `mocha` process has started.- */- async function runMochaWatchWithChokidarMock(args, opts, change) {- let runScheduled = false;- let running = false;- if (- opts?.stdio &&- (!Array.isArray(opts.stdio) || !opts.stdio.includes("ipc"))- ) {- throw new Error(- `if overriding stdio, you must include an 'ipc' channel`,- );- }- const result = await runMochaWatchJSONAsync(- args,- {- // stdin: pipe, stdout: pipe, stderr: inherit, ipc: create IPC channel for messages- stdio: ["pipe", "pipe", "inherit", "ipc"],- env: {- ...process.env,- __MOCHA_WATCH_MOCK_CHOKIDAR: "1",- ...opts?.env,- },- sleepMs: 0,- ...opts,- },- async (mochaProcess) => {- mochaProcess.on("message", (msg) => {- if (!msg) return;- if (msg.run) {- running = true;- runScheduled = false;- }- if (msg.runFinished) running = false;- if (msg.scheduleRun) runScheduled = true;- });- const gotMessage = (filter) =>- new Promise((resolve, reject) => {- function onMessage(message) {- if (filter(message)) {- cleanup();- resolve(message);- }- }- function onError(error) {- cleanup();- reject(error);- }- function cleanup() {- mochaProcess.removeListener("message", onMessage);- mochaProcess.removeListener("error", onError);- }- mochaProcess.on("message", onMessage);- mochaProcess.on("error", onError);- });- const sendWatcherEvent = (...args) =>- Promise.all([- gotMessage(- (msg) =>- Array.isArray(msg.received) &&- msg.received.every((value, i) =>- isDeepStrictEqual(value, args[i]),- ),- ),- mochaProcess.send({ watcher: args }),- ]);-- const { startTime } = await gotMessage((msg) => msg.listening);-- sendWatcherEvent.add = (file, delta) =>- sendWatcherEvent(- "all",- "add",- file,- fakeWatchStat(startTime + delta),- );- sendWatcherEvent.change = (file, delta) =>- sendWatcherEvent(- "all",- "change",- file,- fakeWatchStat(startTime + delta),- );- sendWatcherEvent.unlink = (file) =>- sendWatcherEvent("all", "unlink", file);-- await change(mochaProcess, {- gotMessage,- sendWatcherEvent,- startTime,- });- },- );- result.runPending = runScheduled || running;- return result;- }- it("doesn't rerun when file events occur before tests", async function () {- const testFile = path.join(tempDir, "test.js");- copyFixture("options/watch/test-with-dependency-and-barrier", testFile);-- const dependency = path.join(tempDir, "lib", "dependency.js");- copyFixture("options/watch/dependency", dependency);-- const results = await runMochaWatchWithChokidarMock(- [- testFile,- "--watch-files",- "lib/**/*.js",- "--require",- resolveFixturePath("options/watch/mock-global-setup"),- ],- { cwd: tempDir },- async (mochaProcess, { gotMessage, sendWatcherEvent }) => {- await sendWatcherEvent.add(testFile, -1000);- await sendWatcherEvent.add(dependency, -1000);- await sendWatcherEvent.change(dependency, -1000);-- mochaProcess.send({ resolveGlobalSetup: true });- await gotMessage((msg) => msg.testStarted);-- mochaProcess.send({ resolveTest: true });- await gotMessage((msg) => msg.runFinished);- },- );- expect(results, "to have length", 1);- expect(results[0].passes, "to have length", 1);- expect(results[0].failures, "to have length", 0);- expect(results.runPending, "to be", false);- });-- it("doesn't rerun when file events timestamped before tests are received late, while test is running", async function () {- const testFile = path.join(tempDir, "test.js");- copyFixture("options/watch/test-with-dependency-and-barrier", testFile);-- const dependency = path.join(tempDir, "lib", "dependency.js");- copyFixture("options/watch/dependency", dependency);-- const dependency2 = path.join(tempDir, "lib", "dependency2.js");-- const results = await runMochaWatchWithChokidarMock(- [- testFile,- "--watch-files",- "lib/**/*.js",- "--require",- resolveFixturePath("options/watch/mock-global-setup"),- ],- { cwd: tempDir },- async (mochaProcess, { gotMessage, sendWatcherEvent }) => {- await sendWatcherEvent.add(testFile, -1000);- await sendWatcherEvent.add(dependency, -1000);- await sendWatcherEvent.change(dependency, -1000);-- mochaProcess.send({ resolveGlobalSetup: true });- await gotMessage((msg) => msg.testStarted);-- copyFixture("options/watch/dependency", dependency2);- await sendWatcherEvent.change(dependency, -800);- await sendWatcherEvent.add(dependency2, -800);-- mochaProcess.send({ resolveTest: true });- await gotMessage((msg) => msg.runFinished);- },- );- expect(results, "to have length", 1);- expect(results[0].passes, "to have length", 1);- expect(results[0].failures, "to have length", 0);- expect(results.runPending, "to be", false);- });-- it("doesn't rerun when file events timestamped before tests are received late, after test run", async function () {- const testFile = path.join(tempDir, "test.js");- copyFixture("options/watch/test-with-dependency-and-barrier", testFile);-- const dependency = path.join(tempDir, "lib", "dependency.js");- copyFixture("options/watch/dependency", dependency);-- const dependency2 = path.join(tempDir, "lib", "dependency2.js");-- const results = await runMochaWatchWithChokidarMock(- [- testFile,- "--watch-files",- "lib/**/*.js",- "--require",- resolveFixturePath("options/watch/mock-global-setup"),- ],- { cwd: tempDir },- async (mochaProcess, { gotMessage, sendWatcherEvent }) => {- await sendWatcherEvent.add(testFile, -1000);- await sendWatcherEvent.add(dependency, -1000);-- mochaProcess.send({ resolveGlobalSetup: true });- await gotMessage((msg) => msg.testStarted);-- mochaProcess.send({ resolveTest: true });- await gotMessage((msg) => msg.runFinished);-- copyFixture("options/watch/dependency", dependency2);- await sendWatcherEvent.change(dependency, -600);- await sendWatcherEvent.add(dependency2, -600);- },- );- expect(results, "to have length", 1);- expect(results[0].passes, "to have length", 1);- expect(results[0].failures, "to have length", 0);- expect(results.runPending, "to be", false);- });-- it("doesn't blast cache before run if file events occur before global setup", async function () {- const globalSetupFile = path.join(tempDir, "globalSetup.js");- copyFixture(- "options/watch/mock-global-setup-with-dependency",- globalSetupFile,- );-- const testFile = path.join(tempDir, "test.js");- copyFixture("options/watch/test-with-dependency", testFile);-- const dependency = path.join(tempDir, "lib", "dependency.js");- copyFixture("options/watch/dependency", dependency);-- const results = await runMochaWatchWithChokidarMock(- [- testFile,- "--watch-files",- "lib/**/*.js",- "--require",- globalSetupFile,- ],- { cwd: tempDir },- async (mochaProcess, { gotMessage, sendWatcherEvent }) => {- await sendWatcherEvent.add(testFile, -1000);- await sendWatcherEvent.add(dependency, -1000);- await sendWatcherEvent.change(dependency, -500);- // this should not get picked up by the test file- // it should already have the old version in memory- replaceFileContents(- dependency,- "module.exports.testShouldFail = false",- "module.exports.testShouldFail = true",- );- mochaProcess.send({ resolveGlobalSetup: true });- await gotMessage((msg) => msg.runFinished);- },- );- expect(results, "to have length", 1);- expect(results[0].passes, "to have length", 1);- expect(results[0].failures, "to have length", 0);- expect(results.runPending, "to be", false);- });-- describe("blasts cache before run if file events occur during global setup", function () {- for (const event of ["add", "change", "unlink"]) {- it(`${event} events`, async function () {- const globalSetupFile = path.join(tempDir, "globalSetup.js");- copyFixture(- "options/watch/mock-global-setup-with-dependency",- globalSetupFile,- );-- const testFile = path.join(tempDir, "test.js");- copyFixture(- "options/watch/test-with-dependency-and-barrier",- testFile,- );-- const dependency = path.join(tempDir, "lib", "dependency.js");- copyFixture("options/watch/dependency", dependency);- // this version of the module gets loaded by global setup,- // but it should get replaced before the test is run- replaceFileContents(- dependency,- "module.exports.testShouldFail = false",- "module.exports.testShouldFail = true",- );-- const dependency2 = path.join(tempDir, "lib", "dependency2.js");- if (event !== "add")- copyFixture("options/watch/dependency", dependency2);-- const results = await runMochaWatchWithChokidarMock(- [- testFile,- "--watch-files",- "lib/**/*.js",- "--require",- globalSetupFile,- ],- { cwd: tempDir },- async (mochaProcess, { gotMessage, sendWatcherEvent }) => {- await sendWatcherEvent.add(testFile, -1000);- await sendWatcherEvent.add(dependency, -1000);- if (event !== "add")- await sendWatcherEvent.add(dependency2, -1000);-- replaceFileContents(- dependency,- "module.exports.testShouldFail = true",- "module.exports.testShouldFail = false",- );- if (event === "unlink") await fsPromises.unlink(dependency2);- await sendWatcherEvent[event](dependency2, 1000);-- mochaProcess.send({ resolveGlobalSetup: true });- await gotMessage((msg) => msg.testStarted);-- mochaProcess.send({ resolveTest: true });- await gotMessage((msg) => msg.runFinished);- },- );- expect(results, "to have length", 1);- expect(results[0].passes, "to have length", 1);- expect(results[0].failures, "to have length", 0);- expect(results.runPending, "to be", false);- });- }- });-- describe("reruns once if file events occur during test run", function () {- for (const event of ["add", "change", "unlink"]) {- it(`${event} events`, async function () {- const testFile = path.join(tempDir, "test.js");- copyFixture(- "options/watch/test-with-dependency-and-barrier",- testFile,- );-- const dependency = path.join(tempDir, "lib", "dependency.js");- copyFixture("options/watch/dependency", dependency);- const dependency2 = path.join(tempDir, "lib", "dependency2.js");- const dependency3 = path.join(tempDir, "lib", "dependency3.js");- if (event !== "add") {- copyFixture("options/watch/dependency", dependency2);- copyFixture("options/watch/dependency", dependency3);- }-- const results = await runMochaWatchWithChokidarMock(- [- testFile,- "--watch-files",- "lib/**/*.js",- "--require",- resolveFixturePath("options/watch/mock-global-setup"),- ],- { cwd: tempDir },- async (mochaProcess, { gotMessage, sendWatcherEvent }) => {- await sendWatcherEvent.add(testFile, -3000);- await sendWatcherEvent.add(dependency, -3000);- if (event !== "add") {- await sendWatcherEvent.add(dependency2, -3000);- await sendWatcherEvent.add(dependency3, -3000);- }-- mochaProcess.send({ resolveGlobalSetup: true });- await gotMessage((msg) => msg.testStarted);-- if (event === "add") {- copyFixture("options/watch/dependency", dependency2);- copyFixture("options/watch/dependency", dependency3);- } else if (event === "unlink") {- await Promise.all([- fsPromises.unlink(dependency2),- fsPromises.unlink(dependency3),- ]);- }- await Promise.all([- sendWatcherEvent[event](dependency2, 1000),- sendWatcherEvent[event](dependency3, 2000),- ]);-- await Promise.all([- mochaProcess.send({ resolveTest: true }),- gotMessage((msg) => msg.runFinished),- // also wait for rerun to start- gotMessage((msg) => msg.testStarted),- ]);- await Promise.all([- mochaProcess.send({ resolveTest: true }),- gotMessage((msg) => msg.runFinished),- ]);- },- );- expect(results, "to have length", 2);- expect(results[0].passes, "to have length", 1);- expect(results[0].failures, "to have length", 0);- expect(results[1].passes, "to have length", 1);- expect(results[1].failures, "to have length", 0);- expect(results.runPending, "to be", false);- });- }- });-- describe("reruns once if file events occur after test run", function () {- for (const event of ["add", "change", "unlink"]) {- it(`${event} events`, async function () {- console.error(- `\n***** reruns once if file events occur after test run (${event}) *****\n`,- );- const testFile = path.join(tempDir, "test.js");- copyFixture("options/watch/test-with-dependency", testFile);-- const dependency = path.join(tempDir, "lib", "dependency.js");- copyFixture("options/watch/dependency", dependency);-- const dependency2 = path.join(tempDir, "lib", "dependency2.js");- const dependency3 = path.join(tempDir, "lib", "dependency3.js");- if (event !== "add") {- copyFixture("options/watch/dependency", dependency2);- copyFixture("options/watch/dependency", dependency3);- }-- const results = await runMochaWatchWithChokidarMock(- [- testFile,- "--watch-files",- "lib/**/*.js",- "--require",- resolveFixturePath("options/watch/mock-global-setup"),- ],- { cwd: tempDir },- async (mochaProcess, { gotMessage, sendWatcherEvent }) => {- await sendWatcherEvent.add(testFile, 0);- await sendWatcherEvent.add(dependency, 0);- if (event !== "add") {- await sendWatcherEvent.add(dependency2, 0);- await sendWatcherEvent.add(dependency3, 0);- }-- mochaProcess.send({ resolveGlobalSetup: true });- await gotMessage((msg) => msg.runFinished);-- if (event === "add") {- copyFixture("options/watch/dependency", dependency2);- copyFixture("options/watch/dependency", dependency3);- } else if (event === "unlink") {- await Promise.all([- fsPromises.unlink(dependency2),- fsPromises.unlink(dependency3),- ]);- }- await Promise.all([- sendWatcherEvent[event](dependency2, 1000).then(() =>- console.error(4),- ),- sendWatcherEvent[event](dependency3, 1000).then(() =>- console.error(5),- ),- gotMessage((msg) => msg.runFinished).then(() =>- console.error(6),- ),- ]);- },- );-- const filtered = results.filter((r) => r.tests.length > 0);-- expect(filtered, "to have length", 2);- expect(filtered[0].passes, "to have length", 1);- expect(filtered[0].failures, "to have length", 0);- expect(filtered[1].passes, "to have length", 1);- expect(filtered[1].failures, "to have length", 0);- expect(results.runPending, "to be", false);- });- }- });-- describe("reloads root hooks", function () {- /**- * Helper for setting up hook tests- *- * @param {string} hookName name of hook to test- * @return {function}- */- function setupHookTest(hookName) {- return function () {- const testFile = path.join(tempDir, "test.js");- const hookFile = path.join(tempDir, "hook.js");-- copyFixture("__default__", testFile);- copyFixture("options/watch/hook", hookFile);-- replaceFileContents(hookFile, "<hook>", hookName);-- return runMochaWatchJSONAsync(- [testFile, "--require", hookFile],- tempDir,- () => {- replaceFileContents(hookFile, /throw new Error\([^)]+\)/gm, "");- },- ).then((results) => {- expect(results.length, "to equal", 2);- expect(results[0].failures, "to have length", 1);- expect(results[1].failures, "to have length", 0);- });- };- }-- it("mochaHooks.beforeAll runs as expected", setupHookTest("beforeAll"));- it("mochaHooks.beforeEach runs as expected", setupHookTest("beforeEach"));- it("mochaHooks.afterAll runs as expected", setupHookTest("afterAll"));- it("mochaHooks.afterEach runs as expected", setupHookTest("afterEach"));- });-// Regression test for https://github.com/mochajs/mocha/issues/2027it("respects --fgrep on re-runs", async function () {const testFile = path.join(tempDir, "test.js");