Skip to content

Commit

Permalink
test_runner: support module detection in module mocks
Browse files Browse the repository at this point in the history
PR-URL: nodejs#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>
  • Loading branch information
GeoffreyBooth committed Jul 4, 2024
1 parent 85f56ae commit 18a1ac9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 7 deletions.
4 changes: 3 additions & 1 deletion lib/internal/test_runner/mock/mock.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
20 changes: 14 additions & 6 deletions lib/test/mock_loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -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}')) {
Expand Down

0 comments on commit 18a1ac9

Please sign in to comment.