Skip to content

🐛 Bug: Mocha v11.7.3 and v11.7.4 fails with error ERR_REQUIRE_ESM #5494

@Geam

Description

@Geam

Bug Report Checklist

  • I have read and agree to Mocha's Code of Conduct and Contributing Guidelines
  • I have searched for related issues and issues with the faq label, 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

Unit tests runs as expected

Actual

Unit tests fail with error ERR_REQUIRE_ESM

After some investigation, this problem is the same as #5387 which was fixed in 11.7.1 and 11.7.2 but is broken again in 11.7.3 and 11.7.4 .
The problem has been re-introduced with PR #5408 and the issue might be in lib/nodejs/esm-utils.js line 108 in the PR, the condition reads

      if (
        /\.(cts|mts|ts)$/.test(file) || // <- or
        importErr.code === 'ERR_UNKNOWN_FILE_EXTENSION'
      ) {
        throw requireErr;
      }

but in the PR description it is

If the file being imported is a .cts, .mts, or .ts and the caught error from import() is for an unknown file extension, we know it's from a Node.js version that doesn't support those file extensions.

or in the code, and in description.

Note : While making the minimal reproducible example, it appears that if the imported module has no async bit the tests are not run and fail silently.

Minimal, Reproducible Example

// src/main.test.ts
import "./other.js";

describe("the test", function () {
  it("should work", function () {
    console.log("ok");
  });
});
// src/other.ts
export const ok = () => {
  console.log("ok");
};

// there must be an async involved somewhere or the error does not trigger
await Promise.resolve("something");

// simulate an error in a module
throw new Error("stop");
npx mocha '--import=data:text/javascript,import{register}from"node:module";import{pathToFileURL}from"node:url";register("ts-node/esm",pathToFileURL("./"));' --enable-source-maps --inspect 'src/*.test.ts'

Versions

v11.7.3, v11.7.4
Nodejs v24.3.0

Additional Info

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    status: accepting prsMocha can use your help with this one!type: buga defect, confirmed by a maintainer

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions