From ce74d76262d487e8b75719f017957b12a941061f Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Wed, 25 Dec 2024 11:05:27 +0100 Subject: [PATCH] cli: better runtime support for ESM dependencies in tests Signed-off-by: Patrik Oldsberg --- packages/cli/config/jestCachingModuleLoader.js | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/packages/cli/config/jestCachingModuleLoader.js b/packages/cli/config/jestCachingModuleLoader.js index 95c6212123..3b7740a4f7 100644 --- a/packages/cli/config/jestCachingModuleLoader.js +++ b/packages/cli/config/jestCachingModuleLoader.js @@ -33,4 +33,22 @@ module.exports = class CachingJestRuntime extends JestRuntime { } return script; } + + // Notes(Rugvip): As far as I can tell this is the best we can currently do + // for runtime ESM support in Jest. What the below logic effectively does is + // to only allow packages to be loaded as ESM if all imports of that package + // are done in an ESM compatible way, as in either from ESM code or with a + // dynamic import. + cjsModules = new Set(); + _resolveCjsModule(...args) { + const path = super._resolveCjsModule(...args); + this.cjsModules.add(path); + return path; + } + unstable_shouldLoadAsEsm(path, ...restArgs) { + if (this.cjsModules.has(path)) { + return false; + } + return super.unstable_shouldLoadAsEsm(path, ...restArgs); + } };