-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
🐛 Bug: esm-utils.js#requireModule() masks more helpful requireErr in some cases #5792
Description
Bug Report Checklist
- This is NOT a security,
npm audit, or GitHub Advisory issue. - I have read and agree to Mocha's Code of Conduct and Contributing Guidelines
- I have searched for related issues and issues with the
faqlabel, but none matched my issue. - I have 'smoke tested' the code to be tested by running it outside the real test suite to get a better sense of whether the problem is in the code under test, my usage of Mocha, or Mocha itself.
- I want to provide a PR to resolve this
Expected
If esm-utils.js cannot know for sure if a require() or import() error is most relevant, perhaps both should be shown to the user with context?
Actual
When using ts-node for test files (e.g. with "require": ["ts-node/register/transpile-only"], in .mocharc.json), a tsconfig.json that specifies CommonJS, and a Node.js version that does type-stripping by default (Node.js 22 and later),
then any accidental case that results in the require('./test/something.test.ts') throwing an error,
will result in mocha's esm-utils.js#requireModule() attempting to import(...) the test file.
If the import(...) also fails, then the importErr is (often) reported and the requireErr is not shown.
There is some guessing trying to decide which of importErr or requireErr to show.
opentelemetry-js-contrib.git another case where requireErr is more relevant, but importErr is shown.
The full case is described here: open-telemetry/opentelemetry-js-contrib#3418 (comment)
I made a smaller repro here: https://github.com/trentm/repro-mocha-unsupported-dir-import
Minimal, Complete and Verifiable Example
https://github.com/trentm/repro-mocha-unsupported-dir-import
Versions
% npx mocha --version
11.7.5
% node --version
v24.14.0
The combination here requires:
- a mocha which includes feat: use require to load esm #5366
- Node.js that supports
require(esm), Node.js 20 and later. - Node.js that does type-stripping by default, Node.js 22 and later.
Additional Info
I suppose a specific exclude for importErr.code === 'ERR_UNSUPPORTED_DIR_IMPORT' could be added to requireModule(), but I'm not sure if that completes the set of import() error codes that suggest "oops, this was likely a CommonJS file that we tried to import()".
Metadata
Metadata
Assignees
Labels
Type
Projects
Status