node/test/module-hooks/test-module-hooks-create-require-with-url.mjs
Joyee Cheung 8674f6527f
module: preserve URL in the parent created by createRequire()
Previously, createRequire() does not preserve the URL it gets
passed in the mock parent module created, which can be
observable if it's used together with module.registerHooks().
This patch adds preservation of the URL if createRequire()
is invoked with one.

PR-URL: https://github.com/nodejs/node/pull/60974
Fixes: https://github.com/nodejs/node/issues/60973
Reviewed-By: Benjamin Gruenbaum <benjamingr@gmail.com>
Reviewed-By: Geoffrey Booth <webadmin@geoffreybooth.com>
2026-02-17 15:14:21 +01:00

26 lines
930 B
JavaScript

// Verify that if URL is used to createRequire, that URL is passed to the resolve hook
// as parentURL.
import * as common from '../common/index.mjs';
import assert from 'node:assert';
import { registerHooks } from 'node:module';
import * as fixtures from '../common/fixtures.mjs';
const fixtureURL = fixtures.fileURL('module-hooks/create-require-with-url.mjs').href + '?test=1';
registerHooks({
resolve: common.mustCall((specifier, context, defaultResolve) => {
const resolved = defaultResolve(specifier, context, defaultResolve);
if (specifier.startsWith('node:')) {
return resolved;
}
if (specifier === fixtureURL) {
assert.strictEqual(context.parentURL, import.meta.url);
} else { // From the createRequire call.
assert.strictEqual(specifier, './empty.mjs');
assert.strictEqual(context.parentURL, fixtureURL);
}
return resolved;
}, 3),
});
await import(fixtureURL);