☕️ Classic, reliable, trusted test framework for Node.js and the browser
ESM: fix swallowing MODULE_NOT_FOUND errors in case of type:module (#4687)
Gil Tayar68308215a348
diff --git a/lib/esm-utils.js b/lib/esm-utils.jsindex 1e123059..fd51e012 100644--- a/lib/esm-utils.js+++ b/lib/esm-utils.js@@ -52,7 +52,21 @@ exports.requireOrImport = hasStableEsmImplementationerr.code === 'ERR_UNKNOWN_FILE_EXTENSION' ||err.code === 'ERR_UNSUPPORTED_DIR_IMPORT') {- return require(file);+ try {+ return require(file);+ } catch (requireErr) {+ if (requireErr.code === 'ERR_REQUIRE_ESM') {+ // This happens when the test file is a JS file, but via type:module is actually ESM,+ // AND has an import to a file that doesn't exist.+ // This throws an `ERR_MODULE_NOT_FOUND` // error above,+ // and when we try to `require` it here, it throws an `ERR_REQUIRE_ESM`.+ // What we want to do is throw the original error (the `ERR_MODULE_NOT_FOUND`),+ // and not the `ERR_REQUIRE_ESM` error, which is a red herring.+ throw err;+ } else {+ throw requireErr;+ }+ }} else {throw err;}diff --git a/test/integration/esm.spec.js b/test/integration/esm.spec.jsindex 7cf1c390..7398af4e 100644--- a/test/integration/esm.spec.js+++ b/test/integration/esm.spec.js@@ -1,8 +1,6 @@'use strict';var path = require('path');-var helpers = require('./helpers');-var run = helpers.runMochaJSON;-var runMochaAsync = helpers.runMochaAsync;+const {runMochaJSON: run, runMochaAsync} = require('./helpers');var utils = require('../../lib/utils');var args =+process.versions.node.split('.')[0] >= 13 ? [] : ['--experimental-modules'];@@ -81,4 +79,18 @@ describe('esm', function() {expect(result, 'to have passed test count', 1);});++ it('should throw an ERR_MODULE_NOT_FOUND and not ERR_REQUIRE_ESM if file imports a non-existing module', async function() {+ const fixture =+ 'esm/type-module/test-that-imports-non-existing-module.fixture.js';++ const err = await runMochaAsync(fixture, ['--unhandled-rejections=warn'], {+ stdio: 'pipe'+ }).catch(err => err);++ expect(err.output, 'to contain', 'ERR_MODULE_NOT_FOUND').and(+ 'to contain',+ 'test-that-imports-non-existing-module'+ );+ });});diff --git a/test/integration/fixtures/esm/type-module/package.json b/test/integration/fixtures/esm/type-module/package.jsonnew file mode 100644index 00000000..3dbc1ca5--- /dev/null+++ b/test/integration/fixtures/esm/type-module/package.json@@ -0,0 +1,3 @@+{+ "type": "module"+}diff --git a/test/integration/fixtures/esm/type-module/test-that-imports-non-existing-module.fixture.js b/test/integration/fixtures/esm/type-module/test-that-imports-non-existing-module.fixture.jsnew file mode 100644index 00000000..c75f4ee1--- /dev/null+++ b/test/integration/fixtures/esm/type-module/test-that-imports-non-existing-module.fixture.js@@ -0,0 +1,6 @@+import assert from 'assert';+import './this-module-does-not-exist.js';++it('should not pass (or even run) because above import will fail', () => {+ assert(true);+});