Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

fix: watch existing dirs so first run starts armed (#6263)

Mostafa Nazarif5c8acac5f55
diff --git a/lib/cli/watch-run.cjs b/lib/cli/watch-run.cjs
index 3d5af674..9eb2dd98 100644
--- a/lib/cli/watch-run.cjs
+++ b/lib/cli/watch-run.cjs
@@ -1,6 +1,7 @@
"use strict";
const debug = require("debug")("mocha:cli:watch");
+const fs = require("node:fs");
const path = require("node:path");
const chokidar = require("chokidar");
const glob = require("glob");
@@ -10,6 +11,11 @@ const Context = require("../context.js").Context;
const collectFiles = require("./collect-files.cjs");
const { logSymbols } = require("../utils.cjs");
+// Save timer references to avoid Sinon interfering
+// https://github.com/mochajs/mocha/issues/237
+const Date = global.Date;
+const setTimeout = global.setTimeout;
+
/**
* @typedef {import('chokidar').FSWatcher} FSWatcher
* @typedef {import('glob').Glob['patterns'][number]} Pattern
@@ -391,6 +397,28 @@ function createPathMatcher(allowed, ignored, basePath) {
return matcher;
}
+async function validatePathsAreWatched(watcher, dirPaths) {
+ if (dirPaths.length === 0) {
+ return;
+ }
+ const expectedWatchedPaths = dirPaths.map((dirPath) => path.dirname(dirPath));
+ const maxAttempts = 400;
+ const msBeforeRetrying = 5;
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
+ debug(`before .getWatched(): ${Date.now()}`);
+ const watchedPaths = Object.keys(watcher.getWatched());
+ debug(`after .getWatched(): ${Date.now()}`);
+ if (
+ expectedWatchedPaths.every((dirPath) => watchedPaths.includes(dirPath))
+ ) {
+ debug("validated that expected paths are watched");
+ return;
+ }
+ await new Promise((resolve) => setTimeout(resolve, msBeforeRetrying));
+ }
+ debug("gave up waiting for watchers on %o", expectedWatchedPaths);
+}
+
/**
* Bootstraps a Chokidar watcher. Handles keyboard input & signals
* @param {Mocha} mocha - Mocha instance
@@ -436,7 +464,9 @@ const createWatcher = (
const matcher = createPathMatcher(allowed, ignored, basePath);
// Chokidar has to watch the directory paths in case new files are created
- const watcher = chokidar.watch(Array.from(allowed.dir.paths), {
+ const watchPaths = Array.from(allowed.dir.paths);
+ const missingPaths = watchPaths.filter((dirPath) => !fs.existsSync(dirPath));
+ const watcher = chokidar.watch(watchPaths, {
ignoreInitial: true,
ignored: matcher.ignore,
});
@@ -447,7 +477,9 @@ const createWatcher = (
});
watcher.on("ready", async () => {
- debug("watcher ready");
+ debug("watcher reports ready");
+ // chokidar sometimes reports "ready" prematurely
+ await validatePathsAreWatched(watcher, missingPaths);
if (!globalFixtureContext) {
debug("triggering global setup");
globalFixtureContext = await mocha.runGlobalSetup();