Skip to content

armgit / mocha

Public Imported from GitHub
0

☕️ Classic, reliable, trusted test framework for Node.js and the browser

fix: stop masking import() errors for TypeScript files (#6367)

Mostafa Nazari8f525fb5df4d
diff --git a/lib/nodejs/esm-utils.cjs b/lib/nodejs/esm-utils.cjs
index 34b2e09a..45a2942f 100644
--- a/lib/nodejs/esm-utils.cjs
+++ b/lib/nodejs/esm-utils.cjs
@@ -110,7 +110,7 @@ const requireModule = async (file, esmDecorator) => {
// What we actually care about is the original require() error.
// See: https://github.com/mochajs/mocha/issues/5393
if (
- /\.(cts|mts|ts)$/.test(file) ||
+ /\.(cts|mts|ts)$/.test(file) &&
importErr.code === "ERR_UNKNOWN_FILE_EXTENSION"
) {
throw requireErr;
diff --git a/test/node-unit/esm-utils.spec.cjs b/test/node-unit/esm-utils.spec.cjs
index d8194828..e52a03e6 100644
--- a/test/node-unit/esm-utils.spec.cjs
+++ b/test/node-unit/esm-utils.spec.cjs
@@ -89,6 +89,29 @@ describe("esm-utils", function () {
},
);
});
+
+ it("should surface the import() error for a TypeScript file when the require() error is unrelated", async function () {
+ sinon
+ .stub(esmUtils, "doImport")
+ .rejects(
+ Object.assign(
+ new Error("Cannot find package 'non-existent-package'"),
+ { code: "ERR_MODULE_NOT_FOUND" },
+ ),
+ );
+
+ return expect(
+ () =>
+ esmUtils.requireOrImport(
+ "../../test/node-unit/fixtures/this-module-does-not-exist.ts",
+ ),
+ "to be rejected with error satisfying",
+ {
+ code: "ERR_MODULE_NOT_FOUND",
+ message: /non-existent-package/,
+ },
+ );
+ });
});
describe("loadFilesAsync()", function () {