Skip to content

Commit f83e7df

Browse files
authored
test: add a simple test for import defer of a CJS module
This tests imports a CommonJS modules with the `defer` modifier. It ensures that the imported module is not evaluated before accessing properties from its exports. Signed-off-by: Maya Lekova <maya@igalia.com> PR-URL: #64694 Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
1 parent 3a35e48 commit f83e7df

2 files changed

Lines changed: 47 additions & 0 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Flags: --js-defer-import-eval
2+
3+
// Test that uses import.defer for a CJS module. It ensures that:
4+
// 1. the module is imported successfully;
5+
// 2. it's evaluated synchronously, regardless of the `defer` modifier;
6+
// 3. Evaluation of the imported module is deferred
7+
// until first namespace access.
8+
9+
import '../common/index.mjs';
10+
import * as assert from 'assert';
11+
12+
// Import the CJS module with the `defer` modifier.
13+
import defer * as imported from '../fixtures/es-modules/module-cjs-deferred-eval.js';
14+
15+
// At this point, the deferred module should not yet be evaluated. Initialize
16+
// the `eval_list`, which will be populated only when the module is evaluated
17+
// for the first time, triggered by namespace access below.
18+
globalThis.eval_list = [];
19+
20+
// Additionally check that the exported properties `foo` and `identifier`
21+
// are defined and have their values assigned at this point.
22+
assert.strictEqual(imported.foo, 42);
23+
assert.strictEqual(imported.identifier, 'package-type-commonjs');
24+
25+
// Check that the module has been evaluated at this point,
26+
// also that it's not evaluated more than once.
27+
assert.deepStrictEqual(['defer-1'], globalThis.eval_list);
28+
29+
// Clean-up
30+
delete globalThis.eval_list;
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// This fixture is imported as a module
2+
// in test/es-module/test-cjs-defer-static-import-eval.mjs
3+
// to ensure a CommonJS module imported with `import defer`
4+
// is only executed once.
5+
const assert = require('assert');
6+
7+
const identifier = 'package-type-commonjs';
8+
9+
module.exports.foo = 42;
10+
module.exports.identifier = identifier;
11+
12+
// The `eval_list` is initialised by the importing module,
13+
// so by the time the fixture is executed, `eval_list` should
14+
// already be initialised.
15+
assert.deepEqual(globalThis.eval_list, []);
16+
17+
globalThis.eval_list.push('defer-1');

0 commit comments

Comments
 (0)