• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3// Flags: --experimental-vm-modules
4
5const common = require('../common');
6
7const assert = require('assert');
8const { Script, SourceTextModule, createContext } = require('vm');
9
10async function testNoCallback() {
11  const m = new SourceTextModule('import("foo")', { context: createContext() });
12  await m.link(common.mustNotCall());
13  const { result } = await m.evaluate();
14  let threw = false;
15  try {
16    await result;
17  } catch (err) {
18    threw = true;
19    assert.strictEqual(err.code, 'ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING');
20  }
21  assert(threw);
22}
23
24async function test() {
25  const foo = new SourceTextModule('export const a = 1;');
26  await foo.link(common.mustNotCall());
27  await foo.evaluate();
28
29  {
30    const s = new Script('import("foo")', {
31      importModuleDynamically: common.mustCall((specifier, wrap) => {
32        assert.strictEqual(specifier, 'foo');
33        assert.strictEqual(wrap, s);
34        return foo;
35      }),
36    });
37
38    const result = s.runInThisContext();
39    assert.strictEqual(foo.namespace, await result);
40  }
41
42  {
43    const m = new SourceTextModule('import("foo")', {
44      importModuleDynamically: common.mustCall((specifier, wrap) => {
45        assert.strictEqual(specifier, 'foo');
46        assert.strictEqual(wrap, m);
47        return foo;
48      }),
49    });
50    await m.link(common.mustNotCall());
51    const { result } = await m.evaluate();
52    assert.strictEqual(foo.namespace, await result);
53  }
54}
55
56async function testInvalid() {
57  const m = new SourceTextModule('import("foo")', {
58    importModuleDynamically: common.mustCall((specifier, wrap) => {
59      return 5;
60    }),
61  });
62  await m.link(common.mustNotCall());
63  const { result } = await m.evaluate();
64  await result.catch(common.mustCall((e) => {
65    assert.strictEqual(e.code, 'ERR_VM_MODULE_NOT_MODULE');
66  }));
67
68  const s = new Script('import("foo")', {
69    importModuleDynamically: common.mustCall((specifier, wrap) => {
70      return undefined;
71    }),
72  });
73  let threw = false;
74  try {
75    await s.runInThisContext();
76  } catch (e) {
77    threw = true;
78    assert.strictEqual(e.code, 'ERR_VM_MODULE_NOT_MODULE');
79  }
80  assert(threw);
81}
82
83async function testInvalidimportModuleDynamically() {
84  assert.throws(
85    () => new Script(
86      'import("foo")',
87      { importModuleDynamically: false }),
88    { code: 'ERR_INVALID_ARG_TYPE' }
89  );
90}
91
92(async function() {
93  await testNoCallback();
94  await test();
95  await testInvalid();
96  await testInvalidimportModuleDynamically();
97}()).then(common.mustCall());
98