From 3d111520435590c236086a8826378b0f93f51a98 Mon Sep 17 00:00:00 2001 From: Jimmynycu Date: Sun, 25 Jan 2026 02:31:20 +0800 Subject: [PATCH] test: make transformProjectRoot CWD-agnostic Fix issue where tests fail when run from directories like /node because the project root path appears as a substring in URLs (nodejs.org) or other paths (/node_modules). Use a regex that only matches the project root when followed by a path separator, colon, whitespace, or end of string. Fixes: https://github.com/nodejs/node/issues/61303 --- test/common/assertSnapshot.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/test/common/assertSnapshot.js b/test/common/assertSnapshot.js index af4345f5111f24..795e658f9c5179 100644 --- a/test/common/assertSnapshot.js +++ b/test/common/assertSnapshot.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict'; const common = require('.'); const path = require('node:path'); const test = require('node:test'); @@ -33,8 +33,15 @@ function replaceWindowsPaths(str) { function transformProjectRoot(replacement = '') { const projectRoot = path.resolve(__dirname, '../..'); + // Fix for issue #61303: Use a regex to only match projectRoot when it appears + // as an actual path prefix, not as a substring within URLs (like nodejs.org) + // or other paths (like /node_modules) when CWD happens to be /node. + // Match projectRoot followed by: path separator, colon (for line numbers), + // whitespace, or end of string. + const escapedRoot = projectRoot.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + const projectRootRegex = new RegExp(escapedRoot + '(?=[/\\\\:\\s]|$)', 'g'); return (str) => { - return str.replaceAll('\\\'', "'").replaceAll(projectRoot, replacement); + return str.replaceAll('\\\'', "'").replace(projectRootRegex, replacement); }; }