From ad3f2f9cb22c517e68a1f9588b1f907a12fc2b0b Mon Sep 17 00:00:00 2001 From: Joe Hanley Date: Fri, 25 Sep 2026 22:56:02 +0000 Subject: [PATCH] test: replace per-test require.cache scan with O(1) custom-nock lookup (b/566321038) --- src/test/helpers/mocha-bootstrap.js | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/test/helpers/mocha-bootstrap.js b/src/test/helpers/mocha-bootstrap.js index 0dc5b8efd84..2a73b76fac8 100644 --- a/src/test/helpers/mocha-bootstrap.js +++ b/src/test/helpers/mocha-bootstrap.js @@ -1,3 +1,4 @@ +const path = require("path"); const chai = require("chai"); const chaiAsPromised = require("chai-as-promised"); const sinon = require("sinon"); @@ -27,6 +28,11 @@ process.on("unhandledRejection", (error) => { throw error; }); +// Absolute require.cache keys of the custom undici nock helper (src/test/helpers/nock.ts), +// which sits next to this file. Looking them up directly avoids scanning ~3800 cache keys +// after every test. +const CUSTOM_NOCK_PATHS = [path.join(__dirname, "nock.ts"), path.join(__dirname, "nock.js")]; + let suiteFakes = new Set(); /** @@ -50,19 +56,17 @@ function cleanup() { nock.cleanAll(); // Safely clean up custom nock (src/test/helpers/nock.ts) if required by tests - for (const key of Object.keys(require.cache)) { - if (key.endsWith("test/helpers/nock.ts") || key.endsWith("test/helpers/nock.js")) { - try { - const mod = require.cache[key]; - if (mod && mod.exports) { - const customNock = mod.exports.default || mod.exports; - if (typeof customNock.cleanAll === "function") { - customNock.cleanAll(); - } + for (const key of CUSTOM_NOCK_PATHS) { + try { + const mod = require.cache[key]; + if (mod && mod.exports) { + const customNock = mod.exports.default || mod.exports; + if (typeof customNock.cleanAll === "function") { + customNock.cleanAll(); } - } catch { - // Ignore cleanup errors from custom nock } + } catch { + // Ignore cleanup errors from custom nock } } }