Commit 797ef40

Browse files
maruthangaduh95
authored andcommitted
test_runner: mock dual-package with conditional exports
When `mock.module()` targets a package whose `exports` field maps `import` and `require` to different files, the ESM resolver and the CJS resolver disagree on the resolved path. Only the ESM path was registered in `mockMap`, so `require()` of the mocked specifier bypassed the mock and loaded the real CJS module. Resolve the specifier through `Module._resolveFilename` from the caller's directory in addition to the existing ESM resolution. When the two paths differ, register the CJS path as a second key in `mockMap` and invalidate `Module._cache[cjsPath]`, restoring it on `restore()`. Single-resolution packages keep their existing behavior. Fixes: #58231 Signed-off-by: Maruthan G <maruthang4@gmail.com> PR-URL: #62943 Reviewed-By: Aviv Keller <me@aviv.sh> Reviewed-By: Moshe Atlow <moshe@atlow.co.il> Reviewed-By: Jacob Smith <jacob@frende.me>
1 parent 1ad7ca3 commit 797ef40

6 files changed

Lines changed: 173 additions & 0 deletions

File tree

β€Žlib/internal/test_runner/mock/mock.jsβ€Ž

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const {
2020
ReflectConstruct,
2121
ReflectGet,
2222
SafeMap,
23+
StringPrototypeIncludes,
2324
StringPrototypeSlice,
2425
StringPrototypeStartsWith,
2526
}=primordials;
@@ -207,6 +208,7 @@ class MockModuleContext {
207208
baseURL,
208209
cache,
209210
caller,
211+
cjsPath,
210212
format,
211213
fullPath,
212214
moduleExports,
@@ -222,12 +224,25 @@ class MockModuleContext {
222224

223225
sharedState.mockMap.set(baseURL,config);
224226
sharedState.mockMap.set(fullPath,config);
227+
// For dual packages (e.g., a package with a "exports" field that exposes
228+
// both ESM and CJS entry points), the file selected by the ESM resolver
229+
// (used to compute fullPath) may differ from the one selected by CJS
230+
// require(). Register the CJS-resolved path so that require() also picks
231+
// up the mock. See https://github.com/nodejs/node/issues/58231.
232+
if(cjsPath!==null&&cjsPath!==fullPath){
233+
sharedState.mockMap.set(cjsPath,config);
234+
}
225235

226236
this.#sharedState =sharedState;
227237
this.#restore ={
228238
__proto__: null,
229239
baseURL,
230240
cached: fullPathinModule._cache,
241+
cjsPath,
242+
cjsCached: cjsPath!==null&&cjsPath!==fullPath&&
243+
cjsPathinModule._cache,
244+
cjsValue: cjsPath!==null&&cjsPath!==fullPath ?
245+
Module._cache[cjsPath] : undefined,
231246
format,
232247
fullPath,
233248
value: Module._cache[fullPath],
@@ -257,6 +272,9 @@ class MockModuleContext {
257272
}
258273

259274
deleteModule._cache[fullPath];
275+
if(cjsPath!==null&&cjsPath!==fullPath){
276+
deleteModule._cache[cjsPath];
277+
}
260278
sharedState.mockExports.set(baseURL,{
261279
__proto__: null,
262280
moduleExports,
@@ -276,6 +294,14 @@ class MockModuleContext {
276294
Module._cache[this.#restore.fullPath]=this.#restore.value;
277295
}
278296

297+
if(this.#restore.cjsPath!==null&&
298+
this.#restore.cjsPath!==this.#restore.fullPath){
299+
deleteModule._cache[this.#restore.cjsPath];
300+
if(this.#restore.cjsCached){
301+
Module._cache[this.#restore.cjsPath]=this.#restore.cjsValue;
302+
}
303+
}
304+
279305
constmock=mocks.get(this.#restore.baseURL);
280306

281307
if(mock!==undefined){
@@ -285,6 +311,10 @@ class MockModuleContext {
285311

286312
this.#sharedState.mockMap.delete(this.#restore.baseURL);
287313
this.#sharedState.mockMap.delete(this.#restore.fullPath);
314+
if(this.#restore.cjsPath!==null&&
315+
this.#restore.cjsPath!==this.#restore.fullPath){
316+
this.#sharedState.mockMap.delete(this.#restore.cjsPath);
317+
}
288318
this.#restore =undefined;
289319
}
290320
}
@@ -680,11 +710,19 @@ class MockTracker {
680710

681711
constfullPath=StringPrototypeStartsWith(url,'file://') ?
682712
fileURLToPath(url) : null;
713+
// For dual packages, the ESM resolver may return a different file than
714+
// CJS require() would for the same specifier (e.g., when a package's
715+
// "exports" field points to different files for the "import" and
716+
// "require" conditions). Compute the CJS-resolved path so that
717+
// require() of a mocked module also picks up the mock.
718+
// See https://github.com/nodejs/node/issues/58231.
719+
constcjsPath=resolveAsCJS(mockSpecifier,caller,fullPath);
683720
constctx=newMockModuleContext({
684721
__proto__: null,
685722
baseURL: baseURL.href,
686723
cache,
687724
caller,
725+
cjsPath,
688726
format,
689727
fullPath,
690728
moduleExports,
@@ -987,6 +1025,54 @@ function cjsMockModuleLoad(request, parent, isMain) {
9871025
returnmodExports;
9881026
}
9891027

1028+
// Resolve `specifier` using CJS resolution rules so that mocks for dual
1029+
// packages (e.g., a package whose "exports" field points to different files
1030+
// for the "import" and "require" conditions) also intercept require().
1031+
// Returns an absolute file path on success, or null when the specifier cannot
1032+
// be resolved as CJS (for example, when the package is ESM-only or when it is
1033+
// a non-file URL such as data: or node:).
1034+
functionresolveAsCJS(specifier,callerURL,esmFullPath){
1035+
if(isBuiltin(specifier)||
1036+
StringPrototypeStartsWith(specifier,'node:')||
1037+
StringPrototypeStartsWith(specifier,'data:')){
1038+
returnnull;
1039+
}
1040+
1041+
letparentPath;
1042+
if(StringPrototypeStartsWith(callerURL,'file://')){
1043+
try{
1044+
parentPath=fileURLToPath(callerURL);
1045+
}catch{
1046+
returnnull;
1047+
}
1048+
}else{
1049+
returnnull;
1050+
}
1051+
1052+
try{
1053+
consttmpModule=newModule(parentPath,null);
1054+
tmpModule.paths=_nodeModulePaths(parentPath);
1055+
constresolved=_resolveFilename(specifier,tmpModule,false);
1056+
if(typeofresolved!=='string'){
1057+
returnnull;
1058+
}
1059+
// If the resolution matches what the ESM resolver picked, there is
1060+
// nothing additional to register.
1061+
if(resolved===esmFullPath){
1062+
returnesmFullPath;
1063+
}
1064+
// If the resolution returned something that is not a filesystem path
1065+
// (e.g., a builtin id without a slash or backslash), ignore it.
1066+
if(!StringPrototypeIncludes(resolved,'/')&&
1067+
!StringPrototypeIncludes(resolved,'\\')){
1068+
returnnull;
1069+
}
1070+
returnresolved;
1071+
}catch{
1072+
returnnull;
1073+
}
1074+
}
1075+
9901076
functionvalidateStringOrSymbol(value,name){
9911077
if(typeofvalue!=='string'&&typeofvalue!=='symbol'){
9921078
thrownewERR_INVALID_ARG_TYPE(name,['string','symbol'],value);
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict';
2+
constassert=require('node:assert');
3+
const{ test }=require('node:test');
4+
constfixture='dual-pkg-with-exports';
5+
6+
test('mock node_modules dual package with conditional exports',async(t)=>{
7+
constmock=t.mock.module(fixture,{
8+
namedExports: {add(x,y){return1+x+y;},flavor: 'mocked'},
9+
});
10+
11+
// CJS require should pick up the mock even though the package's "exports"
12+
// field maps the "require" condition to a different file than "import".
13+
constcjsImpl=require(fixture);
14+
assert.strictEqual(cjsImpl.add(4,5),10);
15+
assert.strictEqual(cjsImpl.flavor,'mocked');
16+
17+
// ESM dynamic import should also pick up the mock.
18+
constesmImpl=awaitimport(fixture);
19+
assert.strictEqual(esmImpl.add(4,5),10);
20+
assert.strictEqual(esmImpl.flavor,'mocked');
21+
22+
mock.restore();
23+
24+
// After restore, both module systems should see the original exports.
25+
constrestoredCjs=require(fixture);
26+
assert.strictEqual(restoredCjs.add(4,5),9);
27+
assert.strictEqual(restoredCjs.flavor,'cjs');
28+
29+
constrestoredEsm=awaitimport(fixture);
30+
assert.strictEqual(restoredEsm.add(4,5),9);
31+
assert.strictEqual(restoredEsm.flavor,'esm');
32+
});

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.cjsβ€Ž

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.jsβ€Ž

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/package.jsonβ€Ž

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
constcommon=require('../common');
3+
const{ isMainThread }=require('worker_threads');
4+
5+
if(!isMainThread){
6+
common.skip('registering customization hooks in Workers does not work');
7+
}
8+
9+
constfixtures=require('../common/fixtures');
10+
constassert=require('node:assert');
11+
const{ test }=require('node:test');
12+
13+
// Regression test for https://github.com/nodejs/node/issues/58231
14+
// When a dual package exposes both ESM and CJS entry points via the
15+
// "exports" field with "import"/"require" conditions, the ESM resolver
16+
// picks one file (e.g. index.js) and CJS require() picks another
17+
// (e.g. index.cjs). mock.module() must intercept both so that require()
18+
// of the mocked module does not return the original CJS file.
19+
test('mock.module intercepts dual package require with conditional exports',
20+
async()=>{
21+
constcwd=fixtures.path('test-runner');
22+
constfixture=fixtures.path('test-runner','mock-nm-dual-pkg.js');
23+
constargs=['--experimental-test-module-mocks',fixture];
24+
const{
25+
code,
26+
stdout,
27+
signal,
28+
}=awaitcommon.spawnPromisified(process.execPath,args,{ cwd });
29+
30+
assert.strictEqual(signal,null);
31+
assert.strictEqual(code,0,
32+
'child process exited with non-zero status\n'+
33+
`stdout:\n${stdout}`);
34+
assert.match(stdout,/pass1/);
35+
assert.match(stdout,/fail0/);
36+
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Commit 797ef40

Browse files
maruthangaduh95
authored andcommitted
test_runner: mock dual-package with conditional exports
When `mock.module()` targets a package whose `exports` field maps `import` and `require` to different files, the ESM resolver and the CJS resolver disagree on the resolved path. Only the ESM path was registered in `mockMap`, so `require()` of the mocked specifier bypassed the mock and loaded the real CJS module. Resolve the specifier through `Module._resolveFilename` from the caller's directory in addition to the existing ESM resolution. When the two paths differ, register the CJS path as a second key in `mockMap` and invalidate `Module._cache[cjsPath]`, restoring it on `restore()`. Single-resolution packages keep their existing behavior. Fixes: #58231 Signed-off-by: Maruthan G <maruthang4@gmail.com> PR-URL: #62943 Reviewed-By: Aviv Keller <me@aviv.sh> Reviewed-By: Moshe Atlow <moshe@atlow.co.il> Reviewed-By: Jacob Smith <jacob@frende.me>
1 parent 1ad7ca3 commit 797ef40

6 files changed

Lines changed: 173 additions & 0 deletions

File tree

β€Žlib/internal/test_runner/mock/mock.jsβ€Ž

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const {
2020
ReflectConstruct,
2121
ReflectGet,
2222
SafeMap,
23+
StringPrototypeIncludes,
2324
StringPrototypeSlice,
2425
StringPrototypeStartsWith,
2526
}=primordials;
@@ -207,6 +208,7 @@ class MockModuleContext {
207208
baseURL,
208209
cache,
209210
caller,
211+
cjsPath,
210212
format,
211213
fullPath,
212214
moduleExports,
@@ -222,12 +224,25 @@ class MockModuleContext {
222224

223225
sharedState.mockMap.set(baseURL,config);
224226
sharedState.mockMap.set(fullPath,config);
227+
// For dual packages (e.g., a package with a "exports" field that exposes
228+
// both ESM and CJS entry points), the file selected by the ESM resolver
229+
// (used to compute fullPath) may differ from the one selected by CJS
230+
// require(). Register the CJS-resolved path so that require() also picks
231+
// up the mock. See https://github.com/nodejs/node/issues/58231.
232+
if(cjsPath!==null&&cjsPath!==fullPath){
233+
sharedState.mockMap.set(cjsPath,config);
234+
}
225235

226236
this.#sharedState =sharedState;
227237
this.#restore ={
228238
__proto__: null,
229239
baseURL,
230240
cached: fullPathinModule._cache,
241+
cjsPath,
242+
cjsCached: cjsPath!==null&&cjsPath!==fullPath&&
243+
cjsPathinModule._cache,
244+
cjsValue: cjsPath!==null&&cjsPath!==fullPath ?
245+
Module._cache[cjsPath] : undefined,
231246
format,
232247
fullPath,
233248
value: Module._cache[fullPath],
@@ -257,6 +272,9 @@ class MockModuleContext {
257272
}
258273

259274
deleteModule._cache[fullPath];
275+
if(cjsPath!==null&&cjsPath!==fullPath){
276+
deleteModule._cache[cjsPath];
277+
}
260278
sharedState.mockExports.set(baseURL,{
261279
__proto__: null,
262280
moduleExports,
@@ -276,6 +294,14 @@ class MockModuleContext {
276294
Module._cache[this.#restore.fullPath]=this.#restore.value;
277295
}
278296

297+
if(this.#restore.cjsPath!==null&&
298+
this.#restore.cjsPath!==this.#restore.fullPath){
299+
deleteModule._cache[this.#restore.cjsPath];
300+
if(this.#restore.cjsCached){
301+
Module._cache[this.#restore.cjsPath]=this.#restore.cjsValue;
302+
}
303+
}
304+
279305
constmock=mocks.get(this.#restore.baseURL);
280306

281307
if(mock!==undefined){
@@ -285,6 +311,10 @@ class MockModuleContext {
285311

286312
this.#sharedState.mockMap.delete(this.#restore.baseURL);
287313
this.#sharedState.mockMap.delete(this.#restore.fullPath);
314+
if(this.#restore.cjsPath!==null&&
315+
this.#restore.cjsPath!==this.#restore.fullPath){
316+
this.#sharedState.mockMap.delete(this.#restore.cjsPath);
317+
}
288318
this.#restore =undefined;
289319
}
290320
}
@@ -680,11 +710,19 @@ class MockTracker {
680710

681711
constfullPath=StringPrototypeStartsWith(url,'file://') ?
682712
fileURLToPath(url) : null;
713+
// For dual packages, the ESM resolver may return a different file than
714+
// CJS require() would for the same specifier (e.g., when a package's
715+
// "exports" field points to different files for the "import" and
716+
// "require" conditions). Compute the CJS-resolved path so that
717+
// require() of a mocked module also picks up the mock.
718+
// See https://github.com/nodejs/node/issues/58231.
719+
constcjsPath=resolveAsCJS(mockSpecifier,caller,fullPath);
683720
constctx=newMockModuleContext({
684721
__proto__: null,
685722
baseURL: baseURL.href,
686723
cache,
687724
caller,
725+
cjsPath,
688726
format,
689727
fullPath,
690728
moduleExports,
@@ -987,6 +1025,54 @@ function cjsMockModuleLoad(request, parent, isMain) {
9871025
returnmodExports;
9881026
}
9891027

1028+
// Resolve `specifier` using CJS resolution rules so that mocks for dual
1029+
// packages (e.g., a package whose "exports" field points to different files
1030+
// for the "import" and "require" conditions) also intercept require().
1031+
// Returns an absolute file path on success, or null when the specifier cannot
1032+
// be resolved as CJS (for example, when the package is ESM-only or when it is
1033+
// a non-file URL such as data: or node:).
1034+
functionresolveAsCJS(specifier,callerURL,esmFullPath){
1035+
if(isBuiltin(specifier)||
1036+
StringPrototypeStartsWith(specifier,'node:')||
1037+
StringPrototypeStartsWith(specifier,'data:')){
1038+
returnnull;
1039+
}
1040+
1041+
letparentPath;
1042+
if(StringPrototypeStartsWith(callerURL,'file://')){
1043+
try{
1044+
parentPath=fileURLToPath(callerURL);
1045+
}catch{
1046+
returnnull;
1047+
}
1048+
}else{
1049+
returnnull;
1050+
}
1051+
1052+
try{
1053+
consttmpModule=newModule(parentPath,null);
1054+
tmpModule.paths=_nodeModulePaths(parentPath);
1055+
constresolved=_resolveFilename(specifier,tmpModule,false);
1056+
if(typeofresolved!=='string'){
1057+
returnnull;
1058+
}
1059+
// If the resolution matches what the ESM resolver picked, there is
1060+
// nothing additional to register.
1061+
if(resolved===esmFullPath){
1062+
returnesmFullPath;
1063+
}
1064+
// If the resolution returned something that is not a filesystem path
1065+
// (e.g., a builtin id without a slash or backslash), ignore it.
1066+
if(!StringPrototypeIncludes(resolved,'/')&&
1067+
!StringPrototypeIncludes(resolved,'\\')){
1068+
returnnull;
1069+
}
1070+
returnresolved;
1071+
}catch{
1072+
returnnull;
1073+
}
1074+
}
1075+
9901076
functionvalidateStringOrSymbol(value,name){
9911077
if(typeofvalue!=='string'&&typeofvalue!=='symbol'){
9921078
thrownewERR_INVALID_ARG_TYPE(name,['string','symbol'],value);
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict';
2+
constassert=require('node:assert');
3+
const{ test }=require('node:test');
4+
constfixture='dual-pkg-with-exports';
5+
6+
test('mock node_modules dual package with conditional exports',async(t)=>{
7+
constmock=t.mock.module(fixture,{
8+
namedExports: {add(x,y){return1+x+y;},flavor: 'mocked'},
9+
});
10+
11+
// CJS require should pick up the mock even though the package's "exports"
12+
// field maps the "require" condition to a different file than "import".
13+
constcjsImpl=require(fixture);
14+
assert.strictEqual(cjsImpl.add(4,5),10);
15+
assert.strictEqual(cjsImpl.flavor,'mocked');
16+
17+
// ESM dynamic import should also pick up the mock.
18+
constesmImpl=awaitimport(fixture);
19+
assert.strictEqual(esmImpl.add(4,5),10);
20+
assert.strictEqual(esmImpl.flavor,'mocked');
21+
22+
mock.restore();
23+
24+
// After restore, both module systems should see the original exports.
25+
constrestoredCjs=require(fixture);
26+
assert.strictEqual(restoredCjs.add(4,5),9);
27+
assert.strictEqual(restoredCjs.flavor,'cjs');
28+
29+
constrestoredEsm=awaitimport(fixture);
30+
assert.strictEqual(restoredEsm.add(4,5),9);
31+
assert.strictEqual(restoredEsm.flavor,'esm');
32+
});

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.cjsβ€Ž

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.jsβ€Ž

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/package.jsonβ€Ž

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
constcommon=require('../common');
3+
const{ isMainThread }=require('worker_threads');
4+
5+
if(!isMainThread){
6+
common.skip('registering customization hooks in Workers does not work');
7+
}
8+
9+
constfixtures=require('../common/fixtures');
10+
constassert=require('node:assert');
11+
const{ test }=require('node:test');
12+
13+
// Regression test for https://github.com/nodejs/node/issues/58231
14+
// When a dual package exposes both ESM and CJS entry points via the
15+
// "exports" field with "import"/"require" conditions, the ESM resolver
16+
// picks one file (e.g. index.js) and CJS require() picks another
17+
// (e.g. index.cjs). mock.module() must intercept both so that require()
18+
// of the mocked module does not return the original CJS file.
19+
test('mock.module intercepts dual package require with conditional exports',
20+
async()=>{
21+
constcwd=fixtures.path('test-runner');
22+
constfixture=fixtures.path('test-runner','mock-nm-dual-pkg.js');
23+
constargs=['--experimental-test-module-mocks',fixture];
24+
const{
25+
code,
26+
stdout,
27+
signal,
28+
}=awaitcommon.spawnPromisified(process.execPath,args,{ cwd });
29+
30+
assert.strictEqual(signal,null);
31+
assert.strictEqual(code,0,
32+
'child process exited with non-zero status\n'+
33+
`stdout:\n${stdout}`);
34+
assert.match(stdout,/pass1/);
35+
assert.match(stdout,/fail0/);
36+
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 797ef40

Browse files
maruthangaduh95
authored andcommitted
test_runner: mock dual-package with conditional exports
When `mock.module()` targets a package whose `exports` field maps `import` and `require` to different files, the ESM resolver and the CJS resolver disagree on the resolved path. Only the ESM path was registered in `mockMap`, so `require()` of the mocked specifier bypassed the mock and loaded the real CJS module. Resolve the specifier through `Module._resolveFilename` from the caller's directory in addition to the existing ESM resolution. When the two paths differ, register the CJS path as a second key in `mockMap` and invalidate `Module._cache[cjsPath]`, restoring it on `restore()`. Single-resolution packages keep their existing behavior. Fixes: #58231 Signed-off-by: Maruthan G <maruthang4@gmail.com> PR-URL: #62943 Reviewed-By: Aviv Keller <me@aviv.sh> Reviewed-By: Moshe Atlow <moshe@atlow.co.il> Reviewed-By: Jacob Smith <jacob@frende.me>
1 parent 1ad7ca3 commit 797ef40

6 files changed

Lines changed: 173 additions & 0 deletions

File tree

β€Žlib/internal/test_runner/mock/mock.jsβ€Ž

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const {
2020
ReflectConstruct,
2121
ReflectGet,
2222
SafeMap,
23+
StringPrototypeIncludes,
2324
StringPrototypeSlice,
2425
StringPrototypeStartsWith,
2526
}=primordials;
@@ -207,6 +208,7 @@ class MockModuleContext {
207208
baseURL,
208209
cache,
209210
caller,
211+
cjsPath,
210212
format,
211213
fullPath,
212214
moduleExports,
@@ -222,12 +224,25 @@ class MockModuleContext {
222224

223225
sharedState.mockMap.set(baseURL,config);
224226
sharedState.mockMap.set(fullPath,config);
227+
// For dual packages (e.g., a package with a "exports" field that exposes
228+
// both ESM and CJS entry points), the file selected by the ESM resolver
229+
// (used to compute fullPath) may differ from the one selected by CJS
230+
// require(). Register the CJS-resolved path so that require() also picks
231+
// up the mock. See https://github.com/nodejs/node/issues/58231.
232+
if(cjsPath!==null&&cjsPath!==fullPath){
233+
sharedState.mockMap.set(cjsPath,config);
234+
}
225235

226236
this.#sharedState =sharedState;
227237
this.#restore ={
228238
__proto__: null,
229239
baseURL,
230240
cached: fullPathinModule._cache,
241+
cjsPath,
242+
cjsCached: cjsPath!==null&&cjsPath!==fullPath&&
243+
cjsPathinModule._cache,
244+
cjsValue: cjsPath!==null&&cjsPath!==fullPath ?
245+
Module._cache[cjsPath] : undefined,
231246
format,
232247
fullPath,
233248
value: Module._cache[fullPath],
@@ -257,6 +272,9 @@ class MockModuleContext {
257272
}
258273

259274
deleteModule._cache[fullPath];
275+
if(cjsPath!==null&&cjsPath!==fullPath){
276+
deleteModule._cache[cjsPath];
277+
}
260278
sharedState.mockExports.set(baseURL,{
261279
__proto__: null,
262280
moduleExports,
@@ -276,6 +294,14 @@ class MockModuleContext {
276294
Module._cache[this.#restore.fullPath]=this.#restore.value;
277295
}
278296

297+
if(this.#restore.cjsPath!==null&&
298+
this.#restore.cjsPath!==this.#restore.fullPath){
299+
deleteModule._cache[this.#restore.cjsPath];
300+
if(this.#restore.cjsCached){
301+
Module._cache[this.#restore.cjsPath]=this.#restore.cjsValue;
302+
}
303+
}
304+
279305
constmock=mocks.get(this.#restore.baseURL);
280306

281307
if(mock!==undefined){
@@ -285,6 +311,10 @@ class MockModuleContext {
285311

286312
this.#sharedState.mockMap.delete(this.#restore.baseURL);
287313
this.#sharedState.mockMap.delete(this.#restore.fullPath);
314+
if(this.#restore.cjsPath!==null&&
315+
this.#restore.cjsPath!==this.#restore.fullPath){
316+
this.#sharedState.mockMap.delete(this.#restore.cjsPath);
317+
}
288318
this.#restore =undefined;
289319
}
290320
}
@@ -680,11 +710,19 @@ class MockTracker {
680710

681711
constfullPath=StringPrototypeStartsWith(url,'file://') ?
682712
fileURLToPath(url) : null;
713+
// For dual packages, the ESM resolver may return a different file than
714+
// CJS require() would for the same specifier (e.g., when a package's
715+
// "exports" field points to different files for the "import" and
716+
// "require" conditions). Compute the CJS-resolved path so that
717+
// require() of a mocked module also picks up the mock.
718+
// See https://github.com/nodejs/node/issues/58231.
719+
constcjsPath=resolveAsCJS(mockSpecifier,caller,fullPath);
683720
constctx=newMockModuleContext({
684721
__proto__: null,
685722
baseURL: baseURL.href,
686723
cache,
687724
caller,
725+
cjsPath,
688726
format,
689727
fullPath,
690728
moduleExports,
@@ -987,6 +1025,54 @@ function cjsMockModuleLoad(request, parent, isMain) {
9871025
returnmodExports;
9881026
}
9891027

1028+
// Resolve `specifier` using CJS resolution rules so that mocks for dual
1029+
// packages (e.g., a package whose "exports" field points to different files
1030+
// for the "import" and "require" conditions) also intercept require().
1031+
// Returns an absolute file path on success, or null when the specifier cannot
1032+
// be resolved as CJS (for example, when the package is ESM-only or when it is
1033+
// a non-file URL such as data: or node:).
1034+
functionresolveAsCJS(specifier,callerURL,esmFullPath){
1035+
if(isBuiltin(specifier)||
1036+
StringPrototypeStartsWith(specifier,'node:')||
1037+
StringPrototypeStartsWith(specifier,'data:')){
1038+
returnnull;
1039+
}
1040+
1041+
letparentPath;
1042+
if(StringPrototypeStartsWith(callerURL,'file://')){
1043+
try{
1044+
parentPath=fileURLToPath(callerURL);
1045+
}catch{
1046+
returnnull;
1047+
}
1048+
}else{
1049+
returnnull;
1050+
}
1051+
1052+
try{
1053+
consttmpModule=newModule(parentPath,null);
1054+
tmpModule.paths=_nodeModulePaths(parentPath);
1055+
constresolved=_resolveFilename(specifier,tmpModule,false);
1056+
if(typeofresolved!=='string'){
1057+
returnnull;
1058+
}
1059+
// If the resolution matches what the ESM resolver picked, there is
1060+
// nothing additional to register.
1061+
if(resolved===esmFullPath){
1062+
returnesmFullPath;
1063+
}
1064+
// If the resolution returned something that is not a filesystem path
1065+
// (e.g., a builtin id without a slash or backslash), ignore it.
1066+
if(!StringPrototypeIncludes(resolved,'/')&&
1067+
!StringPrototypeIncludes(resolved,'\\')){
1068+
returnnull;
1069+
}
1070+
returnresolved;
1071+
}catch{
1072+
returnnull;
1073+
}
1074+
}
1075+
9901076
functionvalidateStringOrSymbol(value,name){
9911077
if(typeofvalue!=='string'&&typeofvalue!=='symbol'){
9921078
thrownewERR_INVALID_ARG_TYPE(name,['string','symbol'],value);
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict';
2+
constassert=require('node:assert');
3+
const{ test }=require('node:test');
4+
constfixture='dual-pkg-with-exports';
5+
6+
test('mock node_modules dual package with conditional exports',async(t)=>{
7+
constmock=t.mock.module(fixture,{
8+
namedExports: {add(x,y){return1+x+y;},flavor: 'mocked'},
9+
});
10+
11+
// CJS require should pick up the mock even though the package's "exports"
12+
// field maps the "require" condition to a different file than "import".
13+
constcjsImpl=require(fixture);
14+
assert.strictEqual(cjsImpl.add(4,5),10);
15+
assert.strictEqual(cjsImpl.flavor,'mocked');
16+
17+
// ESM dynamic import should also pick up the mock.
18+
constesmImpl=awaitimport(fixture);
19+
assert.strictEqual(esmImpl.add(4,5),10);
20+
assert.strictEqual(esmImpl.flavor,'mocked');
21+
22+
mock.restore();
23+
24+
// After restore, both module systems should see the original exports.
25+
constrestoredCjs=require(fixture);
26+
assert.strictEqual(restoredCjs.add(4,5),9);
27+
assert.strictEqual(restoredCjs.flavor,'cjs');
28+
29+
constrestoredEsm=awaitimport(fixture);
30+
assert.strictEqual(restoredEsm.add(4,5),9);
31+
assert.strictEqual(restoredEsm.flavor,'esm');
32+
});

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.cjsβ€Ž

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.jsβ€Ž

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/package.jsonβ€Ž

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
constcommon=require('../common');
3+
const{ isMainThread }=require('worker_threads');
4+
5+
if(!isMainThread){
6+
common.skip('registering customization hooks in Workers does not work');
7+
}
8+
9+
constfixtures=require('../common/fixtures');
10+
constassert=require('node:assert');
11+
const{ test }=require('node:test');
12+
13+
// Regression test for https://github.com/nodejs/node/issues/58231
14+
// When a dual package exposes both ESM and CJS entry points via the
15+
// "exports" field with "import"/"require" conditions, the ESM resolver
16+
// picks one file (e.g. index.js) and CJS require() picks another
17+
// (e.g. index.cjs). mock.module() must intercept both so that require()
18+
// of the mocked module does not return the original CJS file.
19+
test('mock.module intercepts dual package require with conditional exports',
20+
async()=>{
21+
constcwd=fixtures.path('test-runner');
22+
constfixture=fixtures.path('test-runner','mock-nm-dual-pkg.js');
23+
constargs=['--experimental-test-module-mocks',fixture];
24+
const{
25+
code,
26+
stdout,
27+
signal,
28+
}=awaitcommon.spawnPromisified(process.execPath,args,{ cwd });
29+
30+
assert.strictEqual(signal,null);
31+
assert.strictEqual(code,0,
32+
'child process exited with non-zero status\n'+
33+
`stdout:\n${stdout}`);
34+
assert.match(stdout,/pass1/);
35+
assert.match(stdout,/fail0/);
36+
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 797ef40

Browse files
maruthangaduh95
authored andcommitted
test_runner: mock dual-package with conditional exports
When `mock.module()` targets a package whose `exports` field maps `import` and `require` to different files, the ESM resolver and the CJS resolver disagree on the resolved path. Only the ESM path was registered in `mockMap`, so `require()` of the mocked specifier bypassed the mock and loaded the real CJS module. Resolve the specifier through `Module._resolveFilename` from the caller's directory in addition to the existing ESM resolution. When the two paths differ, register the CJS path as a second key in `mockMap` and invalidate `Module._cache[cjsPath]`, restoring it on `restore()`. Single-resolution packages keep their existing behavior. Fixes: #58231 Signed-off-by: Maruthan G <maruthang4@gmail.com> PR-URL: #62943 Reviewed-By: Aviv Keller <me@aviv.sh> Reviewed-By: Moshe Atlow <moshe@atlow.co.il> Reviewed-By: Jacob Smith <jacob@frende.me>
1 parent 1ad7ca3 commit 797ef40

6 files changed

Lines changed: 173 additions & 0 deletions

File tree

β€Žlib/internal/test_runner/mock/mock.jsβ€Ž

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const {
2020
ReflectConstruct,
2121
ReflectGet,
2222
SafeMap,
23+
StringPrototypeIncludes,
2324
StringPrototypeSlice,
2425
StringPrototypeStartsWith,
2526
}=primordials;
@@ -207,6 +208,7 @@ class MockModuleContext {
207208
baseURL,
208209
cache,
209210
caller,
211+
cjsPath,
210212
format,
211213
fullPath,
212214
moduleExports,
@@ -222,12 +224,25 @@ class MockModuleContext {
222224

223225
sharedState.mockMap.set(baseURL,config);
224226
sharedState.mockMap.set(fullPath,config);
227+
// For dual packages (e.g., a package with a "exports" field that exposes
228+
// both ESM and CJS entry points), the file selected by the ESM resolver
229+
// (used to compute fullPath) may differ from the one selected by CJS
230+
// require(). Register the CJS-resolved path so that require() also picks
231+
// up the mock. See https://github.com/nodejs/node/issues/58231.
232+
if(cjsPath!==null&&cjsPath!==fullPath){
233+
sharedState.mockMap.set(cjsPath,config);
234+
}
225235

226236
this.#sharedState =sharedState;
227237
this.#restore ={
228238
__proto__: null,
229239
baseURL,
230240
cached: fullPathinModule._cache,
241+
cjsPath,
242+
cjsCached: cjsPath!==null&&cjsPath!==fullPath&&
243+
cjsPathinModule._cache,
244+
cjsValue: cjsPath!==null&&cjsPath!==fullPath ?
245+
Module._cache[cjsPath] : undefined,
231246
format,
232247
fullPath,
233248
value: Module._cache[fullPath],
@@ -257,6 +272,9 @@ class MockModuleContext {
257272
}
258273

259274
deleteModule._cache[fullPath];
275+
if(cjsPath!==null&&cjsPath!==fullPath){
276+
deleteModule._cache[cjsPath];
277+
}
260278
sharedState.mockExports.set(baseURL,{
261279
__proto__: null,
262280
moduleExports,
@@ -276,6 +294,14 @@ class MockModuleContext {
276294
Module._cache[this.#restore.fullPath]=this.#restore.value;
277295
}
278296

297+
if(this.#restore.cjsPath!==null&&
298+
this.#restore.cjsPath!==this.#restore.fullPath){
299+
deleteModule._cache[this.#restore.cjsPath];
300+
if(this.#restore.cjsCached){
301+
Module._cache[this.#restore.cjsPath]=this.#restore.cjsValue;
302+
}
303+
}
304+
279305
constmock=mocks.get(this.#restore.baseURL);
280306

281307
if(mock!==undefined){
@@ -285,6 +311,10 @@ class MockModuleContext {
285311

286312
this.#sharedState.mockMap.delete(this.#restore.baseURL);
287313
this.#sharedState.mockMap.delete(this.#restore.fullPath);
314+
if(this.#restore.cjsPath!==null&&
315+
this.#restore.cjsPath!==this.#restore.fullPath){
316+
this.#sharedState.mockMap.delete(this.#restore.cjsPath);
317+
}
288318
this.#restore =undefined;
289319
}
290320
}
@@ -680,11 +710,19 @@ class MockTracker {
680710

681711
constfullPath=StringPrototypeStartsWith(url,'file://') ?
682712
fileURLToPath(url) : null;
713+
// For dual packages, the ESM resolver may return a different file than
714+
// CJS require() would for the same specifier (e.g., when a package's
715+
// "exports" field points to different files for the "import" and
716+
// "require" conditions). Compute the CJS-resolved path so that
717+
// require() of a mocked module also picks up the mock.
718+
// See https://github.com/nodejs/node/issues/58231.
719+
constcjsPath=resolveAsCJS(mockSpecifier,caller,fullPath);
683720
constctx=newMockModuleContext({
684721
__proto__: null,
685722
baseURL: baseURL.href,
686723
cache,
687724
caller,
725+
cjsPath,
688726
format,
689727
fullPath,
690728
moduleExports,
@@ -987,6 +1025,54 @@ function cjsMockModuleLoad(request, parent, isMain) {
9871025
returnmodExports;
9881026
}
9891027

1028+
// Resolve `specifier` using CJS resolution rules so that mocks for dual
1029+
// packages (e.g., a package whose "exports" field points to different files
1030+
// for the "import" and "require" conditions) also intercept require().
1031+
// Returns an absolute file path on success, or null when the specifier cannot
1032+
// be resolved as CJS (for example, when the package is ESM-only or when it is
1033+
// a non-file URL such as data: or node:).
1034+
functionresolveAsCJS(specifier,callerURL,esmFullPath){
1035+
if(isBuiltin(specifier)||
1036+
StringPrototypeStartsWith(specifier,'node:')||
1037+
StringPrototypeStartsWith(specifier,'data:')){
1038+
returnnull;
1039+
}
1040+
1041+
letparentPath;
1042+
if(StringPrototypeStartsWith(callerURL,'file://')){
1043+
try{
1044+
parentPath=fileURLToPath(callerURL);
1045+
}catch{
1046+
returnnull;
1047+
}
1048+
}else{
1049+
returnnull;
1050+
}
1051+
1052+
try{
1053+
consttmpModule=newModule(parentPath,null);
1054+
tmpModule.paths=_nodeModulePaths(parentPath);
1055+
constresolved=_resolveFilename(specifier,tmpModule,false);
1056+
if(typeofresolved!=='string'){
1057+
returnnull;
1058+
}
1059+
// If the resolution matches what the ESM resolver picked, there is
1060+
// nothing additional to register.
1061+
if(resolved===esmFullPath){
1062+
returnesmFullPath;
1063+
}
1064+
// If the resolution returned something that is not a filesystem path
1065+
// (e.g., a builtin id without a slash or backslash), ignore it.
1066+
if(!StringPrototypeIncludes(resolved,'/')&&
1067+
!StringPrototypeIncludes(resolved,'\\')){
1068+
returnnull;
1069+
}
1070+
returnresolved;
1071+
}catch{
1072+
returnnull;
1073+
}
1074+
}
1075+
9901076
functionvalidateStringOrSymbol(value,name){
9911077
if(typeofvalue!=='string'&&typeofvalue!=='symbol'){
9921078
thrownewERR_INVALID_ARG_TYPE(name,['string','symbol'],value);
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict';
2+
constassert=require('node:assert');
3+
const{ test }=require('node:test');
4+
constfixture='dual-pkg-with-exports';
5+
6+
test('mock node_modules dual package with conditional exports',async(t)=>{
7+
constmock=t.mock.module(fixture,{
8+
namedExports: {add(x,y){return1+x+y;},flavor: 'mocked'},
9+
});
10+
11+
// CJS require should pick up the mock even though the package's "exports"
12+
// field maps the "require" condition to a different file than "import".
13+
constcjsImpl=require(fixture);
14+
assert.strictEqual(cjsImpl.add(4,5),10);
15+
assert.strictEqual(cjsImpl.flavor,'mocked');
16+
17+
// ESM dynamic import should also pick up the mock.
18+
constesmImpl=awaitimport(fixture);
19+
assert.strictEqual(esmImpl.add(4,5),10);
20+
assert.strictEqual(esmImpl.flavor,'mocked');
21+
22+
mock.restore();
23+
24+
// After restore, both module systems should see the original exports.
25+
constrestoredCjs=require(fixture);
26+
assert.strictEqual(restoredCjs.add(4,5),9);
27+
assert.strictEqual(restoredCjs.flavor,'cjs');
28+
29+
constrestoredEsm=awaitimport(fixture);
30+
assert.strictEqual(restoredEsm.add(4,5),9);
31+
assert.strictEqual(restoredEsm.flavor,'esm');
32+
});

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.cjsβ€Ž

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.jsβ€Ž

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/package.jsonβ€Ž

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
constcommon=require('../common');
3+
const{ isMainThread }=require('worker_threads');
4+
5+
if(!isMainThread){
6+
common.skip('registering customization hooks in Workers does not work');
7+
}
8+
9+
constfixtures=require('../common/fixtures');
10+
constassert=require('node:assert');
11+
const{ test }=require('node:test');
12+
13+
// Regression test for https://github.com/nodejs/node/issues/58231
14+
// When a dual package exposes both ESM and CJS entry points via the
15+
// "exports" field with "import"/"require" conditions, the ESM resolver
16+
// picks one file (e.g. index.js) and CJS require() picks another
17+
// (e.g. index.cjs). mock.module() must intercept both so that require()
18+
// of the mocked module does not return the original CJS file.
19+
test('mock.module intercepts dual package require with conditional exports',
20+
async()=>{
21+
constcwd=fixtures.path('test-runner');
22+
constfixture=fixtures.path('test-runner','mock-nm-dual-pkg.js');
23+
constargs=['--experimental-test-module-mocks',fixture];
24+
const{
25+
code,
26+
stdout,
27+
signal,
28+
}=awaitcommon.spawnPromisified(process.execPath,args,{ cwd });
29+
30+
assert.strictEqual(signal,null);
31+
assert.strictEqual(code,0,
32+
'child process exited with non-zero status\n'+
33+
`stdout:\n${stdout}`);
34+
assert.match(stdout,/pass1/);
35+
assert.match(stdout,/fail0/);
36+
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Commit 797ef40

Browse files
maruthangaduh95
authored andcommitted
test_runner: mock dual-package with conditional exports
When `mock.module()` targets a package whose `exports` field maps `import` and `require` to different files, the ESM resolver and the CJS resolver disagree on the resolved path. Only the ESM path was registered in `mockMap`, so `require()` of the mocked specifier bypassed the mock and loaded the real CJS module. Resolve the specifier through `Module._resolveFilename` from the caller's directory in addition to the existing ESM resolution. When the two paths differ, register the CJS path as a second key in `mockMap` and invalidate `Module._cache[cjsPath]`, restoring it on `restore()`. Single-resolution packages keep their existing behavior. Fixes: #58231 Signed-off-by: Maruthan G <maruthang4@gmail.com> PR-URL: #62943 Reviewed-By: Aviv Keller <me@aviv.sh> Reviewed-By: Moshe Atlow <moshe@atlow.co.il> Reviewed-By: Jacob Smith <jacob@frende.me>
1 parent 1ad7ca3 commit 797ef40

6 files changed

Lines changed: 173 additions & 0 deletions

File tree

β€Žlib/internal/test_runner/mock/mock.jsβ€Ž

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const {
2020
ReflectConstruct,
2121
ReflectGet,
2222
SafeMap,
23+
StringPrototypeIncludes,
2324
StringPrototypeSlice,
2425
StringPrototypeStartsWith,
2526
}=primordials;
@@ -207,6 +208,7 @@ class MockModuleContext {
207208
baseURL,
208209
cache,
209210
caller,
211+
cjsPath,
210212
format,
211213
fullPath,
212214
moduleExports,
@@ -222,12 +224,25 @@ class MockModuleContext {
222224

223225
sharedState.mockMap.set(baseURL,config);
224226
sharedState.mockMap.set(fullPath,config);
227+
// For dual packages (e.g., a package with a "exports" field that exposes
228+
// both ESM and CJS entry points), the file selected by the ESM resolver
229+
// (used to compute fullPath) may differ from the one selected by CJS
230+
// require(). Register the CJS-resolved path so that require() also picks
231+
// up the mock. See https://github.com/nodejs/node/issues/58231.
232+
if(cjsPath!==null&&cjsPath!==fullPath){
233+
sharedState.mockMap.set(cjsPath,config);
234+
}
225235

226236
this.#sharedState =sharedState;
227237
this.#restore ={
228238
__proto__: null,
229239
baseURL,
230240
cached: fullPathinModule._cache,
241+
cjsPath,
242+
cjsCached: cjsPath!==null&&cjsPath!==fullPath&&
243+
cjsPathinModule._cache,
244+
cjsValue: cjsPath!==null&&cjsPath!==fullPath ?
245+
Module._cache[cjsPath] : undefined,
231246
format,
232247
fullPath,
233248
value: Module._cache[fullPath],
@@ -257,6 +272,9 @@ class MockModuleContext {
257272
}
258273

259274
deleteModule._cache[fullPath];
275+
if(cjsPath!==null&&cjsPath!==fullPath){
276+
deleteModule._cache[cjsPath];
277+
}
260278
sharedState.mockExports.set(baseURL,{
261279
__proto__: null,
262280
moduleExports,
@@ -276,6 +294,14 @@ class MockModuleContext {
276294
Module._cache[this.#restore.fullPath]=this.#restore.value;
277295
}
278296

297+
if(this.#restore.cjsPath!==null&&
298+
this.#restore.cjsPath!==this.#restore.fullPath){
299+
deleteModule._cache[this.#restore.cjsPath];
300+
if(this.#restore.cjsCached){
301+
Module._cache[this.#restore.cjsPath]=this.#restore.cjsValue;
302+
}
303+
}
304+
279305
constmock=mocks.get(this.#restore.baseURL);
280306

281307
if(mock!==undefined){
@@ -285,6 +311,10 @@ class MockModuleContext {
285311

286312
this.#sharedState.mockMap.delete(this.#restore.baseURL);
287313
this.#sharedState.mockMap.delete(this.#restore.fullPath);
314+
if(this.#restore.cjsPath!==null&&
315+
this.#restore.cjsPath!==this.#restore.fullPath){
316+
this.#sharedState.mockMap.delete(this.#restore.cjsPath);
317+
}
288318
this.#restore =undefined;
289319
}
290320
}
@@ -680,11 +710,19 @@ class MockTracker {
680710

681711
constfullPath=StringPrototypeStartsWith(url,'file://') ?
682712
fileURLToPath(url) : null;
713+
// For dual packages, the ESM resolver may return a different file than
714+
// CJS require() would for the same specifier (e.g., when a package's
715+
// "exports" field points to different files for the "import" and
716+
// "require" conditions). Compute the CJS-resolved path so that
717+
// require() of a mocked module also picks up the mock.
718+
// See https://github.com/nodejs/node/issues/58231.
719+
constcjsPath=resolveAsCJS(mockSpecifier,caller,fullPath);
683720
constctx=newMockModuleContext({
684721
__proto__: null,
685722
baseURL: baseURL.href,
686723
cache,
687724
caller,
725+
cjsPath,
688726
format,
689727
fullPath,
690728
moduleExports,
@@ -987,6 +1025,54 @@ function cjsMockModuleLoad(request, parent, isMain) {
9871025
returnmodExports;
9881026
}
9891027

1028+
// Resolve `specifier` using CJS resolution rules so that mocks for dual
1029+
// packages (e.g., a package whose "exports" field points to different files
1030+
// for the "import" and "require" conditions) also intercept require().
1031+
// Returns an absolute file path on success, or null when the specifier cannot
1032+
// be resolved as CJS (for example, when the package is ESM-only or when it is
1033+
// a non-file URL such as data: or node:).
1034+
functionresolveAsCJS(specifier,callerURL,esmFullPath){
1035+
if(isBuiltin(specifier)||
1036+
StringPrototypeStartsWith(specifier,'node:')||
1037+
StringPrototypeStartsWith(specifier,'data:')){
1038+
returnnull;
1039+
}
1040+
1041+
letparentPath;
1042+
if(StringPrototypeStartsWith(callerURL,'file://')){
1043+
try{
1044+
parentPath=fileURLToPath(callerURL);
1045+
}catch{
1046+
returnnull;
1047+
}
1048+
}else{
1049+
returnnull;
1050+
}
1051+
1052+
try{
1053+
consttmpModule=newModule(parentPath,null);
1054+
tmpModule.paths=_nodeModulePaths(parentPath);
1055+
constresolved=_resolveFilename(specifier,tmpModule,false);
1056+
if(typeofresolved!=='string'){
1057+
returnnull;
1058+
}
1059+
// If the resolution matches what the ESM resolver picked, there is
1060+
// nothing additional to register.
1061+
if(resolved===esmFullPath){
1062+
returnesmFullPath;
1063+
}
1064+
// If the resolution returned something that is not a filesystem path
1065+
// (e.g., a builtin id without a slash or backslash), ignore it.
1066+
if(!StringPrototypeIncludes(resolved,'/')&&
1067+
!StringPrototypeIncludes(resolved,'\\')){
1068+
returnnull;
1069+
}
1070+
returnresolved;
1071+
}catch{
1072+
returnnull;
1073+
}
1074+
}
1075+
9901076
functionvalidateStringOrSymbol(value,name){
9911077
if(typeofvalue!=='string'&&typeofvalue!=='symbol'){
9921078
thrownewERR_INVALID_ARG_TYPE(name,['string','symbol'],value);
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict';
2+
constassert=require('node:assert');
3+
const{ test }=require('node:test');
4+
constfixture='dual-pkg-with-exports';
5+
6+
test('mock node_modules dual package with conditional exports',async(t)=>{
7+
constmock=t.mock.module(fixture,{
8+
namedExports: {add(x,y){return1+x+y;},flavor: 'mocked'},
9+
});
10+
11+
// CJS require should pick up the mock even though the package's "exports"
12+
// field maps the "require" condition to a different file than "import".
13+
constcjsImpl=require(fixture);
14+
assert.strictEqual(cjsImpl.add(4,5),10);
15+
assert.strictEqual(cjsImpl.flavor,'mocked');
16+
17+
// ESM dynamic import should also pick up the mock.
18+
constesmImpl=awaitimport(fixture);
19+
assert.strictEqual(esmImpl.add(4,5),10);
20+
assert.strictEqual(esmImpl.flavor,'mocked');
21+
22+
mock.restore();
23+
24+
// After restore, both module systems should see the original exports.
25+
constrestoredCjs=require(fixture);
26+
assert.strictEqual(restoredCjs.add(4,5),9);
27+
assert.strictEqual(restoredCjs.flavor,'cjs');
28+
29+
constrestoredEsm=awaitimport(fixture);
30+
assert.strictEqual(restoredEsm.add(4,5),9);
31+
assert.strictEqual(restoredEsm.flavor,'esm');
32+
});

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.cjsβ€Ž

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.jsβ€Ž

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/package.jsonβ€Ž

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
constcommon=require('../common');
3+
const{ isMainThread }=require('worker_threads');
4+
5+
if(!isMainThread){
6+
common.skip('registering customization hooks in Workers does not work');
7+
}
8+
9+
constfixtures=require('../common/fixtures');
10+
constassert=require('node:assert');
11+
const{ test }=require('node:test');
12+
13+
// Regression test for https://github.com/nodejs/node/issues/58231
14+
// When a dual package exposes both ESM and CJS entry points via the
15+
// "exports" field with "import"/"require" conditions, the ESM resolver
16+
// picks one file (e.g. index.js) and CJS require() picks another
17+
// (e.g. index.cjs). mock.module() must intercept both so that require()
18+
// of the mocked module does not return the original CJS file.
19+
test('mock.module intercepts dual package require with conditional exports',
20+
async()=>{
21+
constcwd=fixtures.path('test-runner');
22+
constfixture=fixtures.path('test-runner','mock-nm-dual-pkg.js');
23+
constargs=['--experimental-test-module-mocks',fixture];
24+
const{
25+
code,
26+
stdout,
27+
signal,
28+
}=awaitcommon.spawnPromisified(process.execPath,args,{ cwd });
29+
30+
assert.strictEqual(signal,null);
31+
assert.strictEqual(code,0,
32+
'child process exited with non-zero status\n'+
33+
`stdout:\n${stdout}`);
34+
assert.match(stdout,/pass1/);
35+
assert.match(stdout,/fail0/);
36+
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 797ef40

Browse files
maruthangaduh95
authored andcommitted
test_runner: mock dual-package with conditional exports
When `mock.module()` targets a package whose `exports` field maps `import` and `require` to different files, the ESM resolver and the CJS resolver disagree on the resolved path. Only the ESM path was registered in `mockMap`, so `require()` of the mocked specifier bypassed the mock and loaded the real CJS module. Resolve the specifier through `Module._resolveFilename` from the caller's directory in addition to the existing ESM resolution. When the two paths differ, register the CJS path as a second key in `mockMap` and invalidate `Module._cache[cjsPath]`, restoring it on `restore()`. Single-resolution packages keep their existing behavior. Fixes: #58231 Signed-off-by: Maruthan G <maruthang4@gmail.com> PR-URL: #62943 Reviewed-By: Aviv Keller <me@aviv.sh> Reviewed-By: Moshe Atlow <moshe@atlow.co.il> Reviewed-By: Jacob Smith <jacob@frende.me>
1 parent 1ad7ca3 commit 797ef40

6 files changed

Lines changed: 173 additions & 0 deletions

File tree

β€Žlib/internal/test_runner/mock/mock.jsβ€Ž

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const {
2020
ReflectConstruct,
2121
ReflectGet,
2222
SafeMap,
23+
StringPrototypeIncludes,
2324
StringPrototypeSlice,
2425
StringPrototypeStartsWith,
2526
}=primordials;
@@ -207,6 +208,7 @@ class MockModuleContext {
207208
baseURL,
208209
cache,
209210
caller,
211+
cjsPath,
210212
format,
211213
fullPath,
212214
moduleExports,
@@ -222,12 +224,25 @@ class MockModuleContext {
222224

223225
sharedState.mockMap.set(baseURL,config);
224226
sharedState.mockMap.set(fullPath,config);
227+
// For dual packages (e.g., a package with a "exports" field that exposes
228+
// both ESM and CJS entry points), the file selected by the ESM resolver
229+
// (used to compute fullPath) may differ from the one selected by CJS
230+
// require(). Register the CJS-resolved path so that require() also picks
231+
// up the mock. See https://github.com/nodejs/node/issues/58231.
232+
if(cjsPath!==null&&cjsPath!==fullPath){
233+
sharedState.mockMap.set(cjsPath,config);
234+
}
225235

226236
this.#sharedState =sharedState;
227237
this.#restore ={
228238
__proto__: null,
229239
baseURL,
230240
cached: fullPathinModule._cache,
241+
cjsPath,
242+
cjsCached: cjsPath!==null&&cjsPath!==fullPath&&
243+
cjsPathinModule._cache,
244+
cjsValue: cjsPath!==null&&cjsPath!==fullPath ?
245+
Module._cache[cjsPath] : undefined,
231246
format,
232247
fullPath,
233248
value: Module._cache[fullPath],
@@ -257,6 +272,9 @@ class MockModuleContext {
257272
}
258273

259274
deleteModule._cache[fullPath];
275+
if(cjsPath!==null&&cjsPath!==fullPath){
276+
deleteModule._cache[cjsPath];
277+
}
260278
sharedState.mockExports.set(baseURL,{
261279
__proto__: null,
262280
moduleExports,
@@ -276,6 +294,14 @@ class MockModuleContext {
276294
Module._cache[this.#restore.fullPath]=this.#restore.value;
277295
}
278296

297+
if(this.#restore.cjsPath!==null&&
298+
this.#restore.cjsPath!==this.#restore.fullPath){
299+
deleteModule._cache[this.#restore.cjsPath];
300+
if(this.#restore.cjsCached){
301+
Module._cache[this.#restore.cjsPath]=this.#restore.cjsValue;
302+
}
303+
}
304+
279305
constmock=mocks.get(this.#restore.baseURL);
280306

281307
if(mock!==undefined){
@@ -285,6 +311,10 @@ class MockModuleContext {
285311

286312
this.#sharedState.mockMap.delete(this.#restore.baseURL);
287313
this.#sharedState.mockMap.delete(this.#restore.fullPath);
314+
if(this.#restore.cjsPath!==null&&
315+
this.#restore.cjsPath!==this.#restore.fullPath){
316+
this.#sharedState.mockMap.delete(this.#restore.cjsPath);
317+
}
288318
this.#restore =undefined;
289319
}
290320
}
@@ -680,11 +710,19 @@ class MockTracker {
680710

681711
constfullPath=StringPrototypeStartsWith(url,'file://') ?
682712
fileURLToPath(url) : null;
713+
// For dual packages, the ESM resolver may return a different file than
714+
// CJS require() would for the same specifier (e.g., when a package's
715+
// "exports" field points to different files for the "import" and
716+
// "require" conditions). Compute the CJS-resolved path so that
717+
// require() of a mocked module also picks up the mock.
718+
// See https://github.com/nodejs/node/issues/58231.
719+
constcjsPath=resolveAsCJS(mockSpecifier,caller,fullPath);
683720
constctx=newMockModuleContext({
684721
__proto__: null,
685722
baseURL: baseURL.href,
686723
cache,
687724
caller,
725+
cjsPath,
688726
format,
689727
fullPath,
690728
moduleExports,
@@ -987,6 +1025,54 @@ function cjsMockModuleLoad(request, parent, isMain) {
9871025
returnmodExports;
9881026
}
9891027

1028+
// Resolve `specifier` using CJS resolution rules so that mocks for dual
1029+
// packages (e.g., a package whose "exports" field points to different files
1030+
// for the "import" and "require" conditions) also intercept require().
1031+
// Returns an absolute file path on success, or null when the specifier cannot
1032+
// be resolved as CJS (for example, when the package is ESM-only or when it is
1033+
// a non-file URL such as data: or node:).
1034+
functionresolveAsCJS(specifier,callerURL,esmFullPath){
1035+
if(isBuiltin(specifier)||
1036+
StringPrototypeStartsWith(specifier,'node:')||
1037+
StringPrototypeStartsWith(specifier,'data:')){
1038+
returnnull;
1039+
}
1040+
1041+
letparentPath;
1042+
if(StringPrototypeStartsWith(callerURL,'file://')){
1043+
try{
1044+
parentPath=fileURLToPath(callerURL);
1045+
}catch{
1046+
returnnull;
1047+
}
1048+
}else{
1049+
returnnull;
1050+
}
1051+
1052+
try{
1053+
consttmpModule=newModule(parentPath,null);
1054+
tmpModule.paths=_nodeModulePaths(parentPath);
1055+
constresolved=_resolveFilename(specifier,tmpModule,false);
1056+
if(typeofresolved!=='string'){
1057+
returnnull;
1058+
}
1059+
// If the resolution matches what the ESM resolver picked, there is
1060+
// nothing additional to register.
1061+
if(resolved===esmFullPath){
1062+
returnesmFullPath;
1063+
}
1064+
// If the resolution returned something that is not a filesystem path
1065+
// (e.g., a builtin id without a slash or backslash), ignore it.
1066+
if(!StringPrototypeIncludes(resolved,'/')&&
1067+
!StringPrototypeIncludes(resolved,'\\')){
1068+
returnnull;
1069+
}
1070+
returnresolved;
1071+
}catch{
1072+
returnnull;
1073+
}
1074+
}
1075+
9901076
functionvalidateStringOrSymbol(value,name){
9911077
if(typeofvalue!=='string'&&typeofvalue!=='symbol'){
9921078
thrownewERR_INVALID_ARG_TYPE(name,['string','symbol'],value);
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict';
2+
constassert=require('node:assert');
3+
const{ test }=require('node:test');
4+
constfixture='dual-pkg-with-exports';
5+
6+
test('mock node_modules dual package with conditional exports',async(t)=>{
7+
constmock=t.mock.module(fixture,{
8+
namedExports: {add(x,y){return1+x+y;},flavor: 'mocked'},
9+
});
10+
11+
// CJS require should pick up the mock even though the package's "exports"
12+
// field maps the "require" condition to a different file than "import".
13+
constcjsImpl=require(fixture);
14+
assert.strictEqual(cjsImpl.add(4,5),10);
15+
assert.strictEqual(cjsImpl.flavor,'mocked');
16+
17+
// ESM dynamic import should also pick up the mock.
18+
constesmImpl=awaitimport(fixture);
19+
assert.strictEqual(esmImpl.add(4,5),10);
20+
assert.strictEqual(esmImpl.flavor,'mocked');
21+
22+
mock.restore();
23+
24+
// After restore, both module systems should see the original exports.
25+
constrestoredCjs=require(fixture);
26+
assert.strictEqual(restoredCjs.add(4,5),9);
27+
assert.strictEqual(restoredCjs.flavor,'cjs');
28+
29+
constrestoredEsm=awaitimport(fixture);
30+
assert.strictEqual(restoredEsm.add(4,5),9);
31+
assert.strictEqual(restoredEsm.flavor,'esm');
32+
});

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.cjsβ€Ž

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.jsβ€Ž

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/package.jsonβ€Ž

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
constcommon=require('../common');
3+
const{ isMainThread }=require('worker_threads');
4+
5+
if(!isMainThread){
6+
common.skip('registering customization hooks in Workers does not work');
7+
}
8+
9+
constfixtures=require('../common/fixtures');
10+
constassert=require('node:assert');
11+
const{ test }=require('node:test');
12+
13+
// Regression test for https://github.com/nodejs/node/issues/58231
14+
// When a dual package exposes both ESM and CJS entry points via the
15+
// "exports" field with "import"/"require" conditions, the ESM resolver
16+
// picks one file (e.g. index.js) and CJS require() picks another
17+
// (e.g. index.cjs). mock.module() must intercept both so that require()
18+
// of the mocked module does not return the original CJS file.
19+
test('mock.module intercepts dual package require with conditional exports',
20+
async()=>{
21+
constcwd=fixtures.path('test-runner');
22+
constfixture=fixtures.path('test-runner','mock-nm-dual-pkg.js');
23+
constargs=['--experimental-test-module-mocks',fixture];
24+
const{
25+
code,
26+
stdout,
27+
signal,
28+
}=awaitcommon.spawnPromisified(process.execPath,args,{ cwd });
29+
30+
assert.strictEqual(signal,null);
31+
assert.strictEqual(code,0,
32+
'child process exited with non-zero status\n'+
33+
`stdout:\n${stdout}`);
34+
assert.match(stdout,/pass1/);
35+
assert.match(stdout,/fail0/);
36+
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Commit 797ef40

Browse files
maruthangaduh95
authored andcommitted
test_runner: mock dual-package with conditional exports
When `mock.module()` targets a package whose `exports` field maps `import` and `require` to different files, the ESM resolver and the CJS resolver disagree on the resolved path. Only the ESM path was registered in `mockMap`, so `require()` of the mocked specifier bypassed the mock and loaded the real CJS module. Resolve the specifier through `Module._resolveFilename` from the caller's directory in addition to the existing ESM resolution. When the two paths differ, register the CJS path as a second key in `mockMap` and invalidate `Module._cache[cjsPath]`, restoring it on `restore()`. Single-resolution packages keep their existing behavior. Fixes: #58231 Signed-off-by: Maruthan G <maruthang4@gmail.com> PR-URL: #62943 Reviewed-By: Aviv Keller <me@aviv.sh> Reviewed-By: Moshe Atlow <moshe@atlow.co.il> Reviewed-By: Jacob Smith <jacob@frende.me>
1 parent 1ad7ca3 commit 797ef40

6 files changed

Lines changed: 173 additions & 0 deletions

File tree

β€Žlib/internal/test_runner/mock/mock.jsβ€Ž

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const {
2020
ReflectConstruct,
2121
ReflectGet,
2222
SafeMap,
23+
StringPrototypeIncludes,
2324
StringPrototypeSlice,
2425
StringPrototypeStartsWith,
2526
}=primordials;
@@ -207,6 +208,7 @@ class MockModuleContext {
207208
baseURL,
208209
cache,
209210
caller,
211+
cjsPath,
210212
format,
211213
fullPath,
212214
moduleExports,
@@ -222,12 +224,25 @@ class MockModuleContext {
222224

223225
sharedState.mockMap.set(baseURL,config);
224226
sharedState.mockMap.set(fullPath,config);
227+
// For dual packages (e.g., a package with a "exports" field that exposes
228+
// both ESM and CJS entry points), the file selected by the ESM resolver
229+
// (used to compute fullPath) may differ from the one selected by CJS
230+
// require(). Register the CJS-resolved path so that require() also picks
231+
// up the mock. See https://github.com/nodejs/node/issues/58231.
232+
if(cjsPath!==null&&cjsPath!==fullPath){
233+
sharedState.mockMap.set(cjsPath,config);
234+
}
225235

226236
this.#sharedState =sharedState;
227237
this.#restore ={
228238
__proto__: null,
229239
baseURL,
230240
cached: fullPathinModule._cache,
241+
cjsPath,
242+
cjsCached: cjsPath!==null&&cjsPath!==fullPath&&
243+
cjsPathinModule._cache,
244+
cjsValue: cjsPath!==null&&cjsPath!==fullPath ?
245+
Module._cache[cjsPath] : undefined,
231246
format,
232247
fullPath,
233248
value: Module._cache[fullPath],
@@ -257,6 +272,9 @@ class MockModuleContext {
257272
}
258273

259274
deleteModule._cache[fullPath];
275+
if(cjsPath!==null&&cjsPath!==fullPath){
276+
deleteModule._cache[cjsPath];
277+
}
260278
sharedState.mockExports.set(baseURL,{
261279
__proto__: null,
262280
moduleExports,
@@ -276,6 +294,14 @@ class MockModuleContext {
276294
Module._cache[this.#restore.fullPath]=this.#restore.value;
277295
}
278296

297+
if(this.#restore.cjsPath!==null&&
298+
this.#restore.cjsPath!==this.#restore.fullPath){
299+
deleteModule._cache[this.#restore.cjsPath];
300+
if(this.#restore.cjsCached){
301+
Module._cache[this.#restore.cjsPath]=this.#restore.cjsValue;
302+
}
303+
}
304+
279305
constmock=mocks.get(this.#restore.baseURL);
280306

281307
if(mock!==undefined){
@@ -285,6 +311,10 @@ class MockModuleContext {
285311

286312
this.#sharedState.mockMap.delete(this.#restore.baseURL);
287313
this.#sharedState.mockMap.delete(this.#restore.fullPath);
314+
if(this.#restore.cjsPath!==null&&
315+
this.#restore.cjsPath!==this.#restore.fullPath){
316+
this.#sharedState.mockMap.delete(this.#restore.cjsPath);
317+
}
288318
this.#restore =undefined;
289319
}
290320
}
@@ -680,11 +710,19 @@ class MockTracker {
680710

681711
constfullPath=StringPrototypeStartsWith(url,'file://') ?
682712
fileURLToPath(url) : null;
713+
// For dual packages, the ESM resolver may return a different file than
714+
// CJS require() would for the same specifier (e.g., when a package's
715+
// "exports" field points to different files for the "import" and
716+
// "require" conditions). Compute the CJS-resolved path so that
717+
// require() of a mocked module also picks up the mock.
718+
// See https://github.com/nodejs/node/issues/58231.
719+
constcjsPath=resolveAsCJS(mockSpecifier,caller,fullPath);
683720
constctx=newMockModuleContext({
684721
__proto__: null,
685722
baseURL: baseURL.href,
686723
cache,
687724
caller,
725+
cjsPath,
688726
format,
689727
fullPath,
690728
moduleExports,
@@ -987,6 +1025,54 @@ function cjsMockModuleLoad(request, parent, isMain) {
9871025
returnmodExports;
9881026
}
9891027

1028+
// Resolve `specifier` using CJS resolution rules so that mocks for dual
1029+
// packages (e.g., a package whose "exports" field points to different files
1030+
// for the "import" and "require" conditions) also intercept require().
1031+
// Returns an absolute file path on success, or null when the specifier cannot
1032+
// be resolved as CJS (for example, when the package is ESM-only or when it is
1033+
// a non-file URL such as data: or node:).
1034+
functionresolveAsCJS(specifier,callerURL,esmFullPath){
1035+
if(isBuiltin(specifier)||
1036+
StringPrototypeStartsWith(specifier,'node:')||
1037+
StringPrototypeStartsWith(specifier,'data:')){
1038+
returnnull;
1039+
}
1040+
1041+
letparentPath;
1042+
if(StringPrototypeStartsWith(callerURL,'file://')){
1043+
try{
1044+
parentPath=fileURLToPath(callerURL);
1045+
}catch{
1046+
returnnull;
1047+
}
1048+
}else{
1049+
returnnull;
1050+
}
1051+
1052+
try{
1053+
consttmpModule=newModule(parentPath,null);
1054+
tmpModule.paths=_nodeModulePaths(parentPath);
1055+
constresolved=_resolveFilename(specifier,tmpModule,false);
1056+
if(typeofresolved!=='string'){
1057+
returnnull;
1058+
}
1059+
// If the resolution matches what the ESM resolver picked, there is
1060+
// nothing additional to register.
1061+
if(resolved===esmFullPath){
1062+
returnesmFullPath;
1063+
}
1064+
// If the resolution returned something that is not a filesystem path
1065+
// (e.g., a builtin id without a slash or backslash), ignore it.
1066+
if(!StringPrototypeIncludes(resolved,'/')&&
1067+
!StringPrototypeIncludes(resolved,'\\')){
1068+
returnnull;
1069+
}
1070+
returnresolved;
1071+
}catch{
1072+
returnnull;
1073+
}
1074+
}
1075+
9901076
functionvalidateStringOrSymbol(value,name){
9911077
if(typeofvalue!=='string'&&typeofvalue!=='symbol'){
9921078
thrownewERR_INVALID_ARG_TYPE(name,['string','symbol'],value);
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict';
2+
constassert=require('node:assert');
3+
const{ test }=require('node:test');
4+
constfixture='dual-pkg-with-exports';
5+
6+
test('mock node_modules dual package with conditional exports',async(t)=>{
7+
constmock=t.mock.module(fixture,{
8+
namedExports: {add(x,y){return1+x+y;},flavor: 'mocked'},
9+
});
10+
11+
// CJS require should pick up the mock even though the package's "exports"
12+
// field maps the "require" condition to a different file than "import".
13+
constcjsImpl=require(fixture);
14+
assert.strictEqual(cjsImpl.add(4,5),10);
15+
assert.strictEqual(cjsImpl.flavor,'mocked');
16+
17+
// ESM dynamic import should also pick up the mock.
18+
constesmImpl=awaitimport(fixture);
19+
assert.strictEqual(esmImpl.add(4,5),10);
20+
assert.strictEqual(esmImpl.flavor,'mocked');
21+
22+
mock.restore();
23+
24+
// After restore, both module systems should see the original exports.
25+
constrestoredCjs=require(fixture);
26+
assert.strictEqual(restoredCjs.add(4,5),9);
27+
assert.strictEqual(restoredCjs.flavor,'cjs');
28+
29+
constrestoredEsm=awaitimport(fixture);
30+
assert.strictEqual(restoredEsm.add(4,5),9);
31+
assert.strictEqual(restoredEsm.flavor,'esm');
32+
});

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.cjsβ€Ž

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.jsβ€Ž

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/package.jsonβ€Ž

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
constcommon=require('../common');
3+
const{ isMainThread }=require('worker_threads');
4+
5+
if(!isMainThread){
6+
common.skip('registering customization hooks in Workers does not work');
7+
}
8+
9+
constfixtures=require('../common/fixtures');
10+
constassert=require('node:assert');
11+
const{ test }=require('node:test');
12+
13+
// Regression test for https://github.com/nodejs/node/issues/58231
14+
// When a dual package exposes both ESM and CJS entry points via the
15+
// "exports" field with "import"/"require" conditions, the ESM resolver
16+
// picks one file (e.g. index.js) and CJS require() picks another
17+
// (e.g. index.cjs). mock.module() must intercept both so that require()
18+
// of the mocked module does not return the original CJS file.
19+
test('mock.module intercepts dual package require with conditional exports',
20+
async()=>{
21+
constcwd=fixtures.path('test-runner');
22+
constfixture=fixtures.path('test-runner','mock-nm-dual-pkg.js');
23+
constargs=['--experimental-test-module-mocks',fixture];
24+
const{
25+
code,
26+
stdout,
27+
signal,
28+
}=awaitcommon.spawnPromisified(process.execPath,args,{ cwd });
29+
30+
assert.strictEqual(signal,null);
31+
assert.strictEqual(code,0,
32+
'child process exited with non-zero status\n'+
33+
`stdout:\n${stdout}`);
34+
assert.match(stdout,/pass1/);
35+
assert.match(stdout,/fail0/);
36+
});

0 commit comments

Comments
Β (0)
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Commit 797ef40

Browse files
maruthangaduh95
authored andcommitted
test_runner: mock dual-package with conditional exports
When `mock.module()` targets a package whose `exports` field maps `import` and `require` to different files, the ESM resolver and the CJS resolver disagree on the resolved path. Only the ESM path was registered in `mockMap`, so `require()` of the mocked specifier bypassed the mock and loaded the real CJS module. Resolve the specifier through `Module._resolveFilename` from the caller's directory in addition to the existing ESM resolution. When the two paths differ, register the CJS path as a second key in `mockMap` and invalidate `Module._cache[cjsPath]`, restoring it on `restore()`. Single-resolution packages keep their existing behavior. Fixes: #58231 Signed-off-by: Maruthan G <maruthang4@gmail.com> PR-URL: #62943 Reviewed-By: Aviv Keller <me@aviv.sh> Reviewed-By: Moshe Atlow <moshe@atlow.co.il> Reviewed-By: Jacob Smith <jacob@frende.me>
1 parent 1ad7ca3 commit 797ef40

6 files changed

Lines changed: 173 additions & 0 deletions

File tree

β€Žlib/internal/test_runner/mock/mock.jsβ€Ž

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const {
2020
ReflectConstruct,
2121
ReflectGet,
2222
SafeMap,
23+
StringPrototypeIncludes,
2324
StringPrototypeSlice,
2425
StringPrototypeStartsWith,
2526
}=primordials;
@@ -207,6 +208,7 @@ class MockModuleContext {
207208
baseURL,
208209
cache,
209210
caller,
211+
cjsPath,
210212
format,
211213
fullPath,
212214
moduleExports,
@@ -222,12 +224,25 @@ class MockModuleContext {
222224

223225
sharedState.mockMap.set(baseURL,config);
224226
sharedState.mockMap.set(fullPath,config);
227+
// For dual packages (e.g., a package with a "exports" field that exposes
228+
// both ESM and CJS entry points), the file selected by the ESM resolver
229+
// (used to compute fullPath) may differ from the one selected by CJS
230+
// require(). Register the CJS-resolved path so that require() also picks
231+
// up the mock. See https://github.com/nodejs/node/issues/58231.
232+
if(cjsPath!==null&&cjsPath!==fullPath){
233+
sharedState.mockMap.set(cjsPath,config);
234+
}
225235

226236
this.#sharedState =sharedState;
227237
this.#restore ={
228238
__proto__: null,
229239
baseURL,
230240
cached: fullPathinModule._cache,
241+
cjsPath,
242+
cjsCached: cjsPath!==null&&cjsPath!==fullPath&&
243+
cjsPathinModule._cache,
244+
cjsValue: cjsPath!==null&&cjsPath!==fullPath ?
245+
Module._cache[cjsPath] : undefined,
231246
format,
232247
fullPath,
233248
value: Module._cache[fullPath],
@@ -257,6 +272,9 @@ class MockModuleContext {
257272
}
258273

259274
deleteModule._cache[fullPath];
275+
if(cjsPath!==null&&cjsPath!==fullPath){
276+
deleteModule._cache[cjsPath];
277+
}
260278
sharedState.mockExports.set(baseURL,{
261279
__proto__: null,
262280
moduleExports,
@@ -276,6 +294,14 @@ class MockModuleContext {
276294
Module._cache[this.#restore.fullPath]=this.#restore.value;
277295
}
278296

297+
if(this.#restore.cjsPath!==null&&
298+
this.#restore.cjsPath!==this.#restore.fullPath){
299+
deleteModule._cache[this.#restore.cjsPath];
300+
if(this.#restore.cjsCached){
301+
Module._cache[this.#restore.cjsPath]=this.#restore.cjsValue;
302+
}
303+
}
304+
279305
constmock=mocks.get(this.#restore.baseURL);
280306

281307
if(mock!==undefined){
@@ -285,6 +311,10 @@ class MockModuleContext {
285311

286312
this.#sharedState.mockMap.delete(this.#restore.baseURL);
287313
this.#sharedState.mockMap.delete(this.#restore.fullPath);
314+
if(this.#restore.cjsPath!==null&&
315+
this.#restore.cjsPath!==this.#restore.fullPath){
316+
this.#sharedState.mockMap.delete(this.#restore.cjsPath);
317+
}
288318
this.#restore =undefined;
289319
}
290320
}
@@ -680,11 +710,19 @@ class MockTracker {
680710

681711
constfullPath=StringPrototypeStartsWith(url,'file://') ?
682712
fileURLToPath(url) : null;
713+
// For dual packages, the ESM resolver may return a different file than
714+
// CJS require() would for the same specifier (e.g., when a package's
715+
// "exports" field points to different files for the "import" and
716+
// "require" conditions). Compute the CJS-resolved path so that
717+
// require() of a mocked module also picks up the mock.
718+
// See https://github.com/nodejs/node/issues/58231.
719+
constcjsPath=resolveAsCJS(mockSpecifier,caller,fullPath);
683720
constctx=newMockModuleContext({
684721
__proto__: null,
685722
baseURL: baseURL.href,
686723
cache,
687724
caller,
725+
cjsPath,
688726
format,
689727
fullPath,
690728
moduleExports,
@@ -987,6 +1025,54 @@ function cjsMockModuleLoad(request, parent, isMain) {
9871025
returnmodExports;
9881026
}
9891027

1028+
// Resolve `specifier` using CJS resolution rules so that mocks for dual
1029+
// packages (e.g., a package whose "exports" field points to different files
1030+
// for the "import" and "require" conditions) also intercept require().
1031+
// Returns an absolute file path on success, or null when the specifier cannot
1032+
// be resolved as CJS (for example, when the package is ESM-only or when it is
1033+
// a non-file URL such as data: or node:).
1034+
functionresolveAsCJS(specifier,callerURL,esmFullPath){
1035+
if(isBuiltin(specifier)||
1036+
StringPrototypeStartsWith(specifier,'node:')||
1037+
StringPrototypeStartsWith(specifier,'data:')){
1038+
returnnull;
1039+
}
1040+
1041+
letparentPath;
1042+
if(StringPrototypeStartsWith(callerURL,'file://')){
1043+
try{
1044+
parentPath=fileURLToPath(callerURL);
1045+
}catch{
1046+
returnnull;
1047+
}
1048+
}else{
1049+
returnnull;
1050+
}
1051+
1052+
try{
1053+
consttmpModule=newModule(parentPath,null);
1054+
tmpModule.paths=_nodeModulePaths(parentPath);
1055+
constresolved=_resolveFilename(specifier,tmpModule,false);
1056+
if(typeofresolved!=='string'){
1057+
returnnull;
1058+
}
1059+
// If the resolution matches what the ESM resolver picked, there is
1060+
// nothing additional to register.
1061+
if(resolved===esmFullPath){
1062+
returnesmFullPath;
1063+
}
1064+
// If the resolution returned something that is not a filesystem path
1065+
// (e.g., a builtin id without a slash or backslash), ignore it.
1066+
if(!StringPrototypeIncludes(resolved,'/')&&
1067+
!StringPrototypeIncludes(resolved,'\\')){
1068+
returnnull;
1069+
}
1070+
returnresolved;
1071+
}catch{
1072+
returnnull;
1073+
}
1074+
}
1075+
9901076
functionvalidateStringOrSymbol(value,name){
9911077
if(typeofvalue!=='string'&&typeofvalue!=='symbol'){
9921078
thrownewERR_INVALID_ARG_TYPE(name,['string','symbol'],value);
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'use strict';
2+
constassert=require('node:assert');
3+
const{ test }=require('node:test');
4+
constfixture='dual-pkg-with-exports';
5+
6+
test('mock node_modules dual package with conditional exports',async(t)=>{
7+
constmock=t.mock.module(fixture,{
8+
namedExports: {add(x,y){return1+x+y;},flavor: 'mocked'},
9+
});
10+
11+
// CJS require should pick up the mock even though the package's "exports"
12+
// field maps the "require" condition to a different file than "import".
13+
constcjsImpl=require(fixture);
14+
assert.strictEqual(cjsImpl.add(4,5),10);
15+
assert.strictEqual(cjsImpl.flavor,'mocked');
16+
17+
// ESM dynamic import should also pick up the mock.
18+
constesmImpl=awaitimport(fixture);
19+
assert.strictEqual(esmImpl.add(4,5),10);
20+
assert.strictEqual(esmImpl.flavor,'mocked');
21+
22+
mock.restore();
23+
24+
// After restore, both module systems should see the original exports.
25+
constrestoredCjs=require(fixture);
26+
assert.strictEqual(restoredCjs.add(4,5),9);
27+
assert.strictEqual(restoredCjs.flavor,'cjs');
28+
29+
constrestoredEsm=awaitimport(fixture);
30+
assert.strictEqual(restoredEsm.add(4,5),9);
31+
assert.strictEqual(restoredEsm.flavor,'esm');
32+
});

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.cjsβ€Ž

Lines changed: 5 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/index.jsβ€Ž

Lines changed: 2 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

β€Žtest/fixtures/test-runner/node_modules/dual-pkg-with-exports/package.jsonβ€Ž

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'use strict';
2+
constcommon=require('../common');
3+
const{ isMainThread }=require('worker_threads');
4+
5+
if(!isMainThread){
6+
common.skip('registering customization hooks in Workers does not work');
7+
}
8+
9+
constfixtures=require('../common/fixtures');
10+
constassert=require('node:assert');
11+
const{ test }=require('node:test');
12+
13+
// Regression test for https://github.com/nodejs/node/issues/58231
14+
// When a dual package exposes both ESM and CJS entry points via the
15+
// "exports" field with "import"/"require" conditions, the ESM resolver
16+
// picks one file (e.g. index.js) and CJS require() picks another
17+
// (e.g. index.cjs). mock.module() must intercept both so that require()
18+
// of the mocked module does not return the original CJS file.
19+
test('mock.module intercepts dual package require with conditional exports',
20+
async()=>{
21+
constcwd=fixtures.path('test-runner');
22+
constfixture=fixtures.path('test-runner','mock-nm-dual-pkg.js');
23+
constargs=['--experimental-test-module-mocks',fixture];
24+
const{
25+
code,
26+
stdout,
27+
signal,
28+
}=awaitcommon.spawnPromisified(process.execPath,args,{ cwd });
29+
30+
assert.strictEqual(signal,null);
31+
assert.strictEqual(code,0,
32+
'child process exited with non-zero status\n'+
33+
`stdout:\n${stdout}`);
34+
assert.match(stdout,/pass1/);
35+
assert.match(stdout,/fail0/);
36+
});

0 commit comments

Comments
Β (0)