|
| 1 | +// Flags: --experimental-vm-modules |
| 2 | +'use strict'; |
| 3 | + |
| 4 | +const common = require('../common'); |
| 5 | + |
| 6 | +const assert = require('assert'); |
| 7 | +const { createContext, Script, SourceTextModule } = require('vm'); |
| 8 | + |
| 9 | +// Verifies that a `import` call returns a promise created in the context |
| 10 | +// where the `import` was called, not the context of `importModuleDynamically` |
| 11 | +// callback. |
| 12 | + |
| 13 | +async function testScript() { |
| 14 | + const ctx = createContext(); |
| 15 | + |
| 16 | + const mod1 = new SourceTextModule('export const a = 1;', { |
| 17 | + context: ctx, |
| 18 | + }); |
| 19 | + // No import statements, so must not link statically. |
| 20 | + await mod1.link(common.mustNotCall()); |
| 21 | + |
| 22 | + const script2 = new Script(` |
| 23 | + const promise = import("mod1"); |
| 24 | + if (Object.getPrototypeOf(promise) !== Promise.prototype) { |
| 25 | + throw new Error('Expected promise to be a Promise'); |
| 26 | + } |
| 27 | + `, { |
| 28 | + importModuleDynamically: common.mustCall((specifier, referrer) => { |
| 29 | + assert.strictEqual(specifier, 'mod1'); |
| 30 | + assert.strictEqual(referrer, script2); |
| 31 | + return mod1; |
| 32 | + }), |
| 33 | + }); |
| 34 | + script2.runInContext(ctx); |
| 35 | +} |
| 36 | + |
| 37 | +async function testModule() { |
| 38 | + const ctx = createContext(); |
| 39 | + |
| 40 | + const mod1 = new SourceTextModule('export const a = 1;', { |
| 41 | + context: ctx, |
| 42 | + }); |
| 43 | + // No import statements, so must not link statically. |
| 44 | + await mod1.link(common.mustNotCall()); |
| 45 | + |
| 46 | + const mod2 = new SourceTextModule(` |
| 47 | + const promise = import("mod1"); |
| 48 | + if (Object.getPrototypeOf(promise) !== Promise.prototype) { |
| 49 | + throw new Error('Expected promise to be a Promise'); |
| 50 | + } |
| 51 | + `, { |
| 52 | + context: ctx, |
| 53 | + importModuleDynamically: common.mustCall((specifier, referrer) => { |
| 54 | + assert.strictEqual(specifier, 'mod1'); |
| 55 | + assert.strictEqual(referrer, mod2); |
| 56 | + return mod1; |
| 57 | + }), |
| 58 | + }); |
| 59 | + // No import statements, so must not link statically. |
| 60 | + await mod2.link(common.mustNotCall()); |
| 61 | + await mod2.evaluate(); |
| 62 | +} |
| 63 | + |
| 64 | +Promise.all([ |
| 65 | + testScript(), |
| 66 | + testModule(), |
| 67 | +]).then(common.mustCall()); |
0 commit comments