#5792·mocha

Bug: esm-utils.js#requireModule() masks more helpful requireErr in some cases

Author: trentmCreated Mar 13, 2026Updated Sep 17, 2026
Labelstype: bugstatus: accepting prs

Bug Report Checklist

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: https://github.com/open-telemetry/opentelemetry-js-contrib/issues/3418#issuecomment-4057184822

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:

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()".