MCPcopy Index your code
hub / github.com/nodejs/node / module

Method module

lib/internal/test_runner/mock/mock.js:632–697  ·  view source on GitHub ↗
(specifier, options = kEmptyObject)

Source from the content-addressed store, hash-verified

630 }
631
632 module(specifier, options = kEmptyObject) {
633 emitExperimentalWarning('Module mocking');
634 if (typeof specifier !== 'string') {
635 if (!isURL(specifier))
636 throw new ERR_INVALID_ARG_TYPE('specifier', ['string', 'URL'], specifier);
637 specifier = `${specifier}`;
638 }
639 validateObject(options, 'options');
640 debug('module mock entry, specifier = "%s", options = %o', specifier, options);
641
642 const {
643 cache,
644 moduleExports,
645 } = normalizeModuleMockOptions(options);
646
647 const sharedState = setupSharedModuleState();
648 const mockSpecifier = StringPrototypeStartsWith(specifier, 'node:') ?
649 StringPrototypeSlice(specifier, 5) : specifier;
650
651 // Get the file that called this function. We need four stack frames:
652 // vm context -> getStructuredStack() -> this function -> actual caller.
653 const filename = getStructuredStack()[3]?.getFileName();
654 // If the caller is already a file URL, use it as is. Otherwise, convert it.
655 const hasFileProtocol = StringPrototypeStartsWith(filename, 'file://');
656 const caller = hasFileProtocol ? filename : pathToFileURL(filename).href;
657 const request = { __proto__: null, specifier: mockSpecifier, attributes: kEmptyObject };
658 const { format, url } = sharedState.moduleLoader.resolveSync(caller, request);
659 debug('module mock, url = "%s", format = "%s", caller = "%s"', url, format, caller);
660 if (format) { // Format is not yet known for ambiguous files when detection is enabled.
661 validateOneOf(format, 'format', kSupportedFormats);
662 }
663 const baseURL = URLParse(url);
664
665 if (!baseURL) {
666 throw new ERR_INVALID_ARG_VALUE(
667 'specifier', specifier, 'cannot compute URL',
668 );
669 }
670
671 if (baseURL.searchParams.has(kMockSearchParam)) {
672 throw new ERR_INVALID_STATE(
673 `Cannot mock '${specifier}'. The module is already mocked.`,
674 );
675 }
676
677 const fullPath = StringPrototypeStartsWith(url, 'file://') ?
678 fileURLToPath(url) : null;
679 const ctx = new MockModuleContext({
680 __proto__: null,
681 baseURL: baseURL.href,
682 cache,
683 caller,
684 format,
685 fullPath,
686 moduleExports,
687 sharedState,
688 specifier: mockSpecifier,
689 });

Callers

nothing calls this directly

Calls 10

emitExperimentalWarningFunction · 0.85
setupSharedModuleStateFunction · 0.85
getStructuredStackFunction · 0.85
fileURLToPathFunction · 0.85
hasMethod · 0.65
isURLFunction · 0.50
debugFunction · 0.50
pathToFileURLFunction · 0.50
resolveSyncMethod · 0.45

Tested by

no test coverage detected