From 18a1ac92d929165381cea81e0d55f749a5b8c181 Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Thu, 4 Jul 2024 06:30:01 -0700 Subject: [PATCH] test_runner: support module detection in module mocks PR-URL: https://github.com/nodejs/node/pull/53642 Reviewed-By: Colin Ihrig Reviewed-By: Chemi Atlow Reviewed-By: Benjamin Gruenbaum Reviewed-By: James M Snell --- lib/internal/test_runner/mock/mock.js | 4 +++- lib/test/mock_loader.js | 20 ++++++++++++++------ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/lib/internal/test_runner/mock/mock.js b/lib/internal/test_runner/mock/mock.js index 1aaefe222d926f..e492878479288c 100644 --- a/lib/internal/test_runner/mock/mock.js +++ b/lib/internal/test_runner/mock/mock.js @@ -513,7 +513,9 @@ class MockTracker { mockSpecifier, caller, null, ); debug('module mock, url = "%s", format = "%s", caller = "%s"', url, format, caller); - validateOneOf(format, 'format', kSupportedFormats); + if (format) { // Format is not yet known for ambiguous files when detection is enabled. + validateOneOf(format, 'format', kSupportedFormats); + } const baseURL = URL.parse(url); if (!baseURL) { diff --git a/lib/test/mock_loader.js b/lib/test/mock_loader.js index 426604b45daed6..307ad980856094 100644 --- a/lib/test/mock_loader.js +++ b/lib/test/mock_loader.js @@ -143,26 +143,34 @@ async function load(url, context, nextLoad) { const baseURL = parsedURL ? parsedURL.href : url; const mock = mocks.get(baseURL); + const original = await nextLoad(url, context); debug('load hook, mock = %o', mock); if (mock?.active !== true) { - return nextLoad(url); + return original; } // Treat builtins as commonjs because customization hooks do not allow a // core module to be replaced. - const format = mock.format === 'builtin' ? 'commonjs' : mock.format; + // Also collapse 'commonjs-sync' and 'require-commonjs' to 'commonjs'. + const format = ( + original.format === 'builtin' || + original.format === 'commonjs-sync' || + original.format === 'require-commonjs') ? 'commonjs' : original.format; - return { + const result = { __proto__: null, format, shortCircuit: true, - source: await createSourceFromMock(mock), + source: await createSourceFromMock(mock, format), }; + + debug('load hook finished, result = %o', result); + return result; } -async function createSourceFromMock(mock) { +async function createSourceFromMock(mock, format) { // Create mock implementation from provided exports. - const { exportNames, format, hasDefaultExport, url } = mock; + const { exportNames, hasDefaultExport, url } = mock; const useESM = format === 'module'; const source = `${testImportSource(useESM)} if (!$__test.mock._mockExports.has('${url}')) {