☕️ Classic, reliable, trusted test framework for Node.js and the browser
fix: detect global leaks on every watch rerun (#6368)
Mostafa Nazari79db2ee53b86
diff --git a/.knip.jsonc b/.knip.jsoncindex 5e328ad3..b60ff86e 100644--- a/.knip.jsonc+++ b/.knip.jsonc@@ -5,6 +5,7 @@"ignore": ["test/integration/fixtures/esm/type-module/test-that-imports-non-existing-module.fixture.js","test/integration/fixtures/options/watch/test-with-dependency.fixture.cjs",+ "test/integration/fixtures/options/watch/test-with-global-install.fixture.cjs",],"ignoreDependencies": ["@test/esm-only-loader",diff --git a/docs/src/content/docs/running/cli.mdx b/docs/src/content/docs/running/cli.mdxindex 5b4af7ab..5ad6484f 100644--- a/docs/src/content/docs/running/cli.mdx+++ b/docs/src/content/docs/running/cli.mdx@@ -95,6 +95,9 @@ Corresponding "after each" and "after all" hooks are executed for potential cleaUse this option to have Mocha check for global variables that are leaked while running tests.Specify globals that are acceptable via the `--global` option (for example: `--check-leaks --global jQuery --global MyLib`).+With [`--watch`](#--watch--w), every run is checked against the global variables that existed before the first run.+Mocha never removes a leaked variable, so a leak keeps being reported until you restart Mocha even after you fix the test that caused it.+### `--compilers`:::notediff --git a/lib/cli/watch-run.cjs b/lib/cli/watch-run.cjsindex 9eb2dd98..ea16bb5c 100644--- a/lib/cli/watch-run.cjs+++ b/lib/cli/watch-run.cjs@@ -563,6 +563,7 @@ const createRerunner = (mocha, watcher, { beforeRun, clearScreen } = {}) => {// true if a file has changed during a test runlet rerunScheduled = false;+ let initialGlobals;const run = () => {try {@@ -570,6 +571,7 @@ const createRerunner = (mocha, watcher, { beforeRun, clearScreen } = {}) => {clearTerminal();}mocha = beforeRun ? beforeRun({ mocha, watcher }) || mocha : mocha;+ mocha._initialGlobals = initialGlobals;runner = mocha.run(() => {debug("finished watch run");runner = null;@@ -580,6 +582,7 @@ const createRerunner = (mocha, watcher, { beforeRun, clearScreen } = {}) => {console.error(`${logSymbols.info} [mocha] waiting for changes...`);}});+ initialGlobals = runner._initialGlobals;} catch (err) {console.error(err.stack);}diff --git a/lib/mocha.cjs b/lib/mocha.cjsindex 095c35a0..d1f22841 100644--- a/lib/mocha.cjs+++ b/lib/mocha.cjs@@ -997,6 +997,7 @@ Mocha.prototype.run = function (fn) {dryRun: options.dryRun,failHookAffectedTests: options.failHookAffectedTests,failZero: options.failZero,+ initialGlobals: this._initialGlobals,});createStatsCollector(runner);var reporter = new this._reporter(runner, options);diff --git a/lib/runner.js b/lib/runner.jsindex 1eb4152d..154068a1 100644--- a/lib/runner.js+++ b/lib/runner.js@@ -183,6 +183,7 @@ class Runner extends EventEmitter {* @param {boolean} [opts.dryRun] - Whether to report tests without running them.* @param {boolean} [opts.failZero] - Whether to fail test run if zero tests encountered.* @param {boolean} [opts.failHookAffectedTests] - Whether to fail all tests affected by hook failures.+ * @param {string[]} [opts.initialGlobals] - Global properties to treat as pre-existing when checking for leaks; defaults to those present when the `Runner` is created.*/constructor(suite, opts = {}) {super();@@ -212,7 +213,8 @@ class Runner extends EventEmitter {});this._defaultGrep = /.*/;this.grep(this._defaultGrep);- this.globals(this.globalProps());+ this._initialGlobals = opts.initialGlobals || this.globalProps();+ this.globals(this._initialGlobals);this.uncaught = this._uncaught.bind(this);this.unhandled = (reason, promise) => {diff --git a/test/integration/fixtures/options/watch/global-install.fixture.cjs b/test/integration/fixtures/options/watch/global-install.fixture.cjsnew file mode 100644index 00000000..6dfaf103--- /dev/null+++ b/test/integration/fixtures/options/watch/global-install.fixture.cjs@@ -0,0 +1 @@+globalThis.installedOnce = (globalThis.installedOnce || 0) + 1;diff --git a/test/integration/fixtures/options/watch/global-leak.fixture.cjs b/test/integration/fixtures/options/watch/global-leak.fixture.cjsnew file mode 100644index 00000000..35de785a--- /dev/null+++ b/test/integration/fixtures/options/watch/global-leak.fixture.cjs@@ -0,0 +1,3 @@+it("leaks a global", function () {+ globalThis.leakedVar = 123;+});diff --git a/test/integration/fixtures/options/watch/test-with-global-install.fixture.cjs b/test/integration/fixtures/options/watch/test-with-global-install.fixture.cjsnew file mode 100644index 00000000..2a1abae2--- /dev/null+++ b/test/integration/fixtures/options/watch/test-with-global-install.fixture.cjs@@ -0,0 +1,7 @@+const assert = require("node:assert");++require("./lib/global-install");++it("still sees the global from the first run", function () {+ assert.strictEqual(globalThis.installedOnce, 1);+});diff --git a/test/integration/options/watch.spec.cjs b/test/integration/options/watch.spec.cjsindex 8d9e53f6..685d18c0 100644--- a/test/integration/options/watch.spec.cjs+++ b/test/integration/options/watch.spec.cjs@@ -515,6 +515,49 @@ describe("--watch", function () {});});+ // Regression test for https://github.com/mochajs/mocha/issues/1948+ it("reports a global leak on every run", function () {+ const testFile = path.join(tempDir, "test.js");+ copyFixture("options/watch/global-leak.fixture.cjs", testFile);++ return runMochaWatchJSONAsync(+ [testFile, "--check-leaks"],+ tempDir,+ () => {+ touchFile(testFile);+ },+ ).then((results) => {+ expect(results, "to have length", 2);+ expect(results[0].failures, "to have length", 1);+ expect(results[1].failures, "to have length", 1);+ });+ });++ it("keeps globals introduced by the first run", function () {+ const testFile = path.join(tempDir, "test.js");+ copyFixture(+ "options/watch/test-with-global-install.fixture.cjs",+ testFile,+ );+ copyFixture(+ "options/watch/global-install.fixture.cjs",+ path.join(tempDir, "lib", "global-install.js"),+ );++ return runMochaWatchJSONAsync(+ [testFile, "--check-leaks", "--watch-files", "test.js"],+ tempDir,+ () => {+ touchFile(testFile);+ },+ ).then((results) => {+ expect(results, "to have length", 2);+ expect(results[0].failures, "to have length", 0);+ expect(results[1].failures, "to have length", 0);+ expect(results[1].passes, "to have length", 1);+ });+ });+// Regression test for https://github.com/mochajs/mocha/issues/2027it("respects --fgrep on re-runs", async function () {const testFile = path.join(tempDir, "test.js");