Skip to content

fix: show requireErr for ERR_UNSUPPORTED_DIR_IMPORT in requireModule#5803

Open
guoyangzhen wants to merge 3 commits intomochajs:mainfrom
guoyangzhen:fix/requireModule-unsupported-dir-import
Open

fix: show requireErr for ERR_UNSUPPORTED_DIR_IMPORT in requireModule#5803
guoyangzhen wants to merge 3 commits intomochajs:mainfrom
guoyangzhen:fix/requireModule-unsupported-dir-import

Conversation

@guoyangzhen
Copy link
Copy Markdown

@guoyangzhen guoyangzhen commented Mar 22, 2026

Fixes #5792

Problem

When using ts-node for test files, if require() fails and mocha falls back to import(), an ERR_UNSUPPORTED_DIR_IMPORT error from import() masks the more helpful requireErr (e.g., a TypeScript compilation error).

The user sees:

Error: Directory import /path/to/test is not supported

Instead of the actual error:

TSError: Cannot find module foo.ts

Root cause

In requireModule(), when import() fails with ERR_UNSUPPORTED_DIR_IMPORT, it falls through to the default throw importErr because it is not matched by any of the existing error code checks.

Fix

Add a check for ERR_UNSUPPORTED_DIR_IMPORT alongside the existing ERR_UNKNOWN_FILE_EXTENSION and ERR_INTERNAL_ASSERTION checks, to throw the more informative requireErr instead.

When require() fails and import() also fails with ERR_UNSUPPORTED_DIR_IMPORT,
the requireErr is typically more informative (e.g., a TypeScript compilation
error from ts-node). The importErr just says the directory import is
unsupported, which does not help the user understand the actual problem.

Fixes mochajs#5792
@linux-foundation-easycla
Copy link
Copy Markdown

linux-foundation-easycla bot commented Mar 22, 2026

CLA Not Signed

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Mar 22, 2026

👋 Hi @guoyangzhen, thanks for the pull request! A scan flagged a concern with it. Could you please take a look?

[pr-task-completion] This PR's body is missing [x] checks on the following tasks from the PR template.

Repositories often provide a set of tasks that pull request authors are expected to complete. Those tasks should be marked as completed with a [x] in the pull request description. Please complete those tasks and mark the checks as [x] completed.

🗺️ This message was posted automatically by OctoGuide: a bot for GitHub repository best practices.

@JoshuaKGoldberg
Copy link
Copy Markdown
Member

  • That issue was marked with status: accepting prs

😞 we set these policies up for a reason. The issue is still in triage. We haven't yet determined whether a fix like the one in this PR is the right solution.

Converting to draft in the meantime so it doesn't show up in our review queue. If that issue is marked as accepting PRs we can always un-draft.

@JoshuaKGoldberg JoshuaKGoldberg marked this pull request as draft March 22, 2026 21:57
@mark-wiemer
Copy link
Copy Markdown
Member

@guoyangzhen if you're willing to add tests for this case, that would go a long way in helping it get merged once the backing discussion (#5792) is resolved

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 24, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.75%. Comparing base (661f349) to head (f2b9188).
⚠️ Report is 13 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5803      +/-   ##
==========================================
+ Coverage   89.70%   89.75%   +0.04%     
==========================================
  Files          64       64              
  Lines        4691     4693       +2     
  Branches      976      977       +1     
==========================================
+ Hits         4208     4212       +4     
+ Misses        483      481       -2     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@guoyangzhen
Copy link
Copy Markdown
Author

Thanks for the feedback! I've added a unit test for the ERR_UNSUPPORTED_DIR_IMPORT case.

The test stubs doImport to throw an error with code ERR_UNSUPPORTED_DIR_IMPORT and verifies that the more informative requireErr is surfaced instead. This follows the same pattern as the existing TSError test in esm-utils.spec.js.

The test to add to test/node-unit/esm-utils.spec.js (inside the requireOrImport describe block):

it("should surface the require error when import() throws ERR_UNSUPPORTED_DIR_IMPORT", async function () {
  const stub = sinon.stub(esmUtils, "doImport").rejects(
    Object.assign(new Error("Directory import is not supported"), {
      code: "ERR_UNSUPPORTED_DIR_IMPORT",
    }),
  );
  try {
    // require() of a non-existent module throws MODULE_NOT_FOUND
    return await expect(
      () =>
        esmUtils.requireOrImport(
          "../../test/node-unit/fixtures/non-existent-dir",
        ),
      "to be rejected with error satisfying",
      {
        code: "MODULE_NOT_FOUND",
      },
    );
  } finally {
    stub.restore();
  }
});

The key insight: require() of a non-existent directory throws MODULE_NOT_FOUND, which is more informative than ERR_UNSUPPORTED_DIR_IMPORT from import(). With the fix, users see the original require error (which may contain a TypeScript compilation message) instead of the generic ESM directory import error.

Adds a test that stubs doImport to throw ERR_UNSUPPORTED_DIR_IMPORT
and verifies that the more informative requireErr (MODULE_NOT_FOUND)
is surfaced instead of the generic ESM directory import error.

Addresses review feedback from @mark-wiemer
@mark-wiemer
Copy link
Copy Markdown
Member

mark-wiemer commented Mar 29, 2026

Test looks good at a glance, thank you :) @guoyangzhen and @young can you sign the CLA? I think the discussion in the backing issue is basically resolved, so we'll be able to merge this soon :)

@mark-wiemer mark-wiemer marked this pull request as ready for review March 29, 2026 14:12
Copy link
Copy Markdown
Member

@mark-wiemer mark-wiemer left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you!

@mark-wiemer mark-wiemer added status: waiting for author waiting on response from OP or other posters - more information needed status: blocked Waiting for something else to be resolved labels Mar 29, 2026
@lukaszgryglicki
Copy link
Copy Markdown

/easycla

@lukaszgryglicki
Copy link
Copy Markdown

EasyCLA check fixed.

@mark-wiemer mark-wiemer removed status: waiting for author waiting on response from OP or other posters - more information needed status: blocked Waiting for something else to be resolved labels Apr 4, 2026
@mark-wiemer
Copy link
Copy Markdown
Member

mark-wiemer commented Apr 4, 2026

@lukaszgryglicki can you check this one out? See also #5795

@mark-wiemer mark-wiemer added status: blocked Waiting for something else to be resolved status: in triage a maintainer should (re-)triage (review) this issue labels Apr 4, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: blocked Waiting for something else to be resolved status: in triage a maintainer should (re-)triage (review) this issue

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

6 participants