• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2const common = require('../common');
3const tmpdir = require('../common/tmpdir');
4const assert = require('assert');
5const { spawnSync } = require('child_process');
6const fs = require('fs');
7const path = require('path');
8const { createRequire } = require('module');
9
10for (const name in ['test', 'test/reporters']) {
11  assert.throws(
12    () => require(name),
13    common.expectsError({ code: 'MODULE_NOT_FOUND' }),
14  );
15
16  (async () => {
17    await assert.rejects(
18      async () => import(name),
19      common.expectsError({ code: 'ERR_MODULE_NOT_FOUND' }),
20    );
21  })().then(common.mustCall());
22
23  assert.throws(
24    () => require.resolve(name),
25    common.expectsError({ code: 'MODULE_NOT_FOUND' }),
26  );
27}
28
29// Verify that files in node_modules can be resolved.
30tmpdir.refresh();
31
32const packageRoot = path.join(tmpdir.path, 'node_modules', 'test');
33const reportersDir = path.join(tmpdir.path, 'node_modules', 'test', 'reporters');
34const indexFile = path.join(packageRoot, 'index.js');
35const reportersIndexFile = path.join(reportersDir, 'index.js');
36
37fs.mkdirSync(reportersDir, { recursive: true });
38fs.writeFileSync(indexFile, 'module.exports = { marker: 1 };');
39fs.writeFileSync(reportersIndexFile, 'module.exports = { marker: 1 };');
40
41function test(argv, expectedToFail = false) {
42  const child = spawnSync(process.execPath, argv, { cwd: tmpdir.path });
43  if (expectedToFail) {
44    assert.strictEqual(child.status, 1);
45    assert.strictEqual(child.stdout.toString().trim(), '');
46  } else {
47    assert.strictEqual(child.status, 0);
48    assert.strictEqual(child.stdout.toString().trim(), '{ marker: 1 }');
49  }
50}
51
52test(['-e', 'console.log(require("test"))']);
53test(['-e', 'console.log(require("test/reporters"))']);
54test(['-e', 'import("test").then(m=>console.log(m.default))']);
55test(['-e', 'import("test/reporters").then(m=>console.log(m.default))'], true);
56test(['--input-type=module', '-e', 'import test from "test";console.log(test)']);
57test(['--input-type=module', '-e', 'import test from "test/reporters";console.log(test)'], true);
58test(['--input-type=module', '-e', 'console.log((await import("test")).default)']);
59test(['--input-type=module', '-e', 'console.log((await import("test/reporters")).default)'], true);
60
61{
62  const dummyFile = path.join(tmpdir.path, 'file.js');
63  const require = createRequire(dummyFile);
64  assert.strictEqual(require.resolve('test'), indexFile);
65  assert.strictEqual(require.resolve('test/reporters'), reportersIndexFile);
66}
67