0
0
mirror of https://github.com/nodejs/node.git synced 2024-11-30 15:30:56 +01:00
nodejs/test/es-module/test-esm-dynamic-import.js
Thomas a25a628452
esm: better error message for unsupported URL
The default ESM loader supports only file and data URLs.
This PR adds better error message for it.

PR-URL: https://github.com/nodejs/node/pull/31129
Reviewed-By: Gus Caplan <me@gus.host>
Reviewed-By: Guy Bedford <guybedford@gmail.com>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
2020-01-03 15:33:16 +01:00

66 lines
2.2 KiB
JavaScript

'use strict';
const common = require('../common');
const assert = require('assert');
const { URL } = require('url');
const relativePath = '../fixtures/es-modules/test-esm-ok.mjs';
const absolutePath = require.resolve('../fixtures/es-modules/test-esm-ok.mjs');
const targetURL = new URL('file:///');
targetURL.pathname = absolutePath;
function expectErrorProperty(result, propertyKey, value) {
Promise.resolve(result)
.catch(common.mustCall((error) => {
assert.strictEqual(error[propertyKey], value);
}));
}
function expectModuleError(result, err) {
expectErrorProperty(result, 'code', err);
}
function expectOkNamespace(result) {
Promise.resolve(result)
.then(common.mustCall((ns) => {
const expected = { default: true };
Object.defineProperty(expected, Symbol.toStringTag, {
value: 'Module'
});
Object.setPrototypeOf(expected, Object.getPrototypeOf(ns));
assert.deepStrictEqual(ns, expected);
}));
}
function expectFsNamespace(result) {
Promise.resolve(result)
.then(common.mustCall((ns) => {
assert.strictEqual(typeof ns.default.writeFile, 'function');
assert.strictEqual(typeof ns.writeFile, 'function');
}));
}
// For direct use of import expressions inside of CJS or ES modules, including
// via eval, all kinds of specifiers should work without issue.
(function testScriptOrModuleImport() {
common.expectWarning('ExperimentalWarning',
'The ESM module loader is experimental.');
// Importing another file, both direct & via eval
// expectOkNamespace(import(relativePath));
expectOkNamespace(eval(`import("${relativePath}")`));
expectOkNamespace(eval(`import("${relativePath}")`));
expectOkNamespace(eval(`import("${targetURL}")`));
// Importing a built-in, both direct & via eval
expectFsNamespace(import('fs'));
expectFsNamespace(eval('import("fs")'));
expectFsNamespace(eval('import("fs")'));
expectModuleError(import('./not-an-existing-module.mjs'),
'ERR_MODULE_NOT_FOUND');
expectModuleError(import('node:fs'),
'ERR_UNSUPPORTED_ESM_URL_SCHEME');
expectModuleError(import('http://example.com/foo.js'),
'ERR_UNSUPPORTED_ESM_URL_SCHEME');
})();