(
from: string,
moduleName?: string,
options?: TransformOptions,
isRequireActual = false,
)
| 61 | } |
| 62 | |
| 63 | requireModule<T = unknown>( |
| 64 | from: string, |
| 65 | moduleName?: string, |
| 66 | options?: TransformOptions, |
| 67 | isRequireActual = false, |
| 68 | ): T { |
| 69 | const isInternal = options?.isInternalModule ?? false; |
| 70 | const moduleID = this.mockState.getCjsModuleId(from, moduleName); |
| 71 | let modulePath: string | undefined; |
| 72 | |
| 73 | // Some old tests rely on this mocking behavior. Ideally we'll change this |
| 74 | // to be more explicit. |
| 75 | const moduleResource = moduleName && this.resolution.getModule(moduleName); |
| 76 | const manualMock = |
| 77 | moduleName && this.resolution.getCjsMockModule(from, moduleName); |
| 78 | if ( |
| 79 | !options?.isInternalModule && |
| 80 | !isRequireActual && |
| 81 | !moduleResource && |
| 82 | manualMock && |
| 83 | manualMock !== this.executor.getCurrentlyExecutingManualMock() && |
| 84 | !this.mockState.isExplicitlyUnmocked(moduleID) |
| 85 | ) { |
| 86 | modulePath = manualMock; |
| 87 | } |
| 88 | |
| 89 | if (moduleName && this.resolution.isCoreModule(moduleName)) { |
| 90 | return this.coreModule.require( |
| 91 | moduleName, |
| 92 | supportsNodeColonModulePrefixInRequire, |
| 93 | ) as T; |
| 94 | } |
| 95 | |
| 96 | if (!modulePath) { |
| 97 | modulePath = this.resolution.resolveCjs(from, moduleName); |
| 98 | } |
| 99 | |
| 100 | if (this.resolution.shouldLoadAsEsm(modulePath)) { |
| 101 | if (!supportsSyncEvaluate) { |
| 102 | const error: NodeJS.ErrnoException = new Error( |
| 103 | `Must use import to load ES Module: ${modulePath}\n` + |
| 104 | "Jest's require(ESM) requires Node v24.9+ for " + |
| 105 | 'synchronous vm module APIs; the current Node version does not ' + |
| 106 | 'expose them.', |
| 107 | ); |
| 108 | error.code = 'ERR_REQUIRE_ESM'; |
| 109 | throw error; |
| 110 | } |
| 111 | // Fast path: skip the graph walker on cache hits. |
| 112 | const reg = this.registries.getActiveEsmRegistry(); |
| 113 | const cached = reg.get(modulePath); |
| 114 | if (cached && !(cached instanceof Promise)) { |
| 115 | return (cached as VMModule).namespace as T; |
| 116 | } |
| 117 | return this.requireEsm<T>(modulePath); |
| 118 | } |
| 119 | |
| 120 | const moduleRegistry = isInternal |
no test coverage detected