Jest 30 config loading ambiguity with concurrent .cjs and .mjs files
0 reputation · 12 Aug 2023, 02:30 UTC
0 reputation · 12 Aug 2023, 02:30 UTC
When a project upgrades from Jest 29 to Jest 30 and enables ES modules by setting "type": "module" in package.json, Jest attempts to load the test configuration using ESM‑aware resolution. If both jest.config.cjs and jest.config.mjs are present in the root directory, the loader that Jest 30 selects is not explicitly documented and appears to depend on Node’s internal module resolution order, which can vary between runs or environments.
The goal is to understand which configuration file Jest 30 will use under these conditions and whether the selection is deterministic, given the constraints of Node version (≥14.18), the presence of the type field, and any applicable CLI flags.
Which file does Jest 30 prioritize when both jest.config.cjs and jest.config.mjs exist? Does the "type":"module" setting influence the resolution order, and can the behavior be made deterministic through configuration or CLI options?
32275 reputation · 12 Aug 2023, 09:20 UTC
In Jest 30, when both jest.config.cjs and jest.config.mjs exist in the root directory, Jest follows a deterministic internal priority list to select the configuration file. While the "type": "module" setting in package.json dictates how .js files are interpreted, .cjs and .mjs extensions are explicit signals to the Node.js loader and Jest.
Jest prioritizes jest.config.mjs over jest.config.cjs when ESM is enabled. This alignment ensures that projects opting into ES modules use the modern module system for their configuration by default.
--config CLI flag bypasses all automatic discovery and forces Jest to use the specified file..mjs is always treated as an ES module, and .cjs is always treated as CommonJS, regardless of the package.json type field.The perceived non-determinism in some environments often stems from filesystem differences or cached configurations rather than a random selection process. However, maintaining both files is considered an anti-pattern because it creates ambiguity for developers and CI tools, even if the loader's priority list is technically fixed.
"type": "module", retain jest.config.mjs.package.json scripts:
"test": "jest --config jest.config.mjs"
npx jest --showConfig
Check the output for specific settings (like displayName) that you have uniquely defined in one of the two files.
Missing Diagnostic: To provide a more precise answer regarding your specific environment, please clarify if you are running Jest via a wrapper (like ts-jest or babel-jest) or using the native node --experimental-vm-modules flag.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.