Skip to content

Commit e6a1eeb

Browse files
GeoffreyBoothaduh95
authored andcommitted
test_runner: support module detection in module mocks
PR-URL: #53642 Reviewed-By: Colin Ihrig <cjihrig@gmail.com> Reviewed-By: Chemi Atlow <chemi@atlow.co.il> Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com> Reviewed-By: James M Snell <jasnell@gmail.com>
1 parent ac9c2e6 commit e6a1eeb

2 files changed

Lines changed: 17 additions & 7 deletions

File tree

‎lib/internal/test_runner/mock/mock.js‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -513,7 +513,9 @@ class MockTracker {
513513
mockSpecifier,caller,null,
514514
);
515515
debug('module mock, url = "%s", format = "%s", caller = "%s"',url,format,caller);
516-
validateOneOf(format,'format',kSupportedFormats);
516+
if(format){// Format is not yet known for ambiguous files when detection is enabled.
517+
validateOneOf(format,'format',kSupportedFormats);
518+
}
517519
constbaseURL=URL.parse(url);
518520

519521
if(!baseURL){

‎lib/test/mock_loader.js‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -143,26 +143,34 @@ async function load(url, context, nextLoad) {
143143
constbaseURL=parsedURL ? parsedURL.href : url;
144144
constmock=mocks.get(baseURL);
145145

146+
constoriginal=awaitnextLoad(url,context);
146147
debug('load hook, mock = %o',mock);
147148
if(mock?.active!==true){
148-
returnnextLoad(url);
149+
returnoriginal;
149150
}
150151

151152
// Treat builtins as commonjs because customization hooks do not allow a
152153
// core module to be replaced.
153-
constformat=mock.format==='builtin' ? 'commonjs' : mock.format;
154+
// Also collapse 'commonjs-sync' and 'require-commonjs' to 'commonjs'.
155+
constformat=(
156+
original.format==='builtin'||
157+
original.format==='commonjs-sync'||
158+
original.format==='require-commonjs') ? 'commonjs' : original.format;
154159

155-
return{
160+
constresult={
156161
__proto__: null,
157162
format,
158163
shortCircuit: true,
159-
source: awaitcreateSourceFromMock(mock),
164+
source: awaitcreateSourceFromMock(mock,format),
160165
};
166+
167+
debug('load hook finished, result = %o',result);
168+
returnresult;
161169
}
162170

163-
asyncfunctioncreateSourceFromMock(mock){
171+
asyncfunctioncreateSourceFromMock(mock,format){
164172
// Create mock implementation from provided exports.
165-
const{ exportNames,format,hasDefaultExport, url }=mock;
173+
const{ exportNames, hasDefaultExport, url }=mock;
166174
constuseESM=format==='module';
167175
constsource=`${testImportSource(useESM)}
168176
if (!$__test.mock._mockExports.has('${url}')) {

0 commit comments

Comments
 (0)