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: https://github.com/nodejs/node/pull/64694
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
This commit is contained in:
Maya Lekova authored and Antoine du Hamel committed 2026-08-26 00:56:04 +02:00
1 parent 099801641b
commit bca3367583
2 files changed
+47

No files matched your search

@@ -0,0 +1,30 @@
// Flags: --js-defer-import-eval
// Test that uses import.defer for a CJS module. It ensures that:
// 1. the module is imported successfully;
// 2. it's evaluated synchronously, regardless of the `defer` modifier;
// 3. Evaluation of the imported module is deferred
// until first namespace access.
import '../common/index.mjs';
import * as assert from 'assert';
// Import the CJS module with the `defer` modifier.
import defer * as imported from '../fixtures/es-modules/module-cjs-deferred-eval.js';
// At this point, the deferred module should not yet be evaluated. Initialize
// the `eval_list`, which will be populated only when the module is evaluated
// for the first time, triggered by namespace access below.
globalThis.eval_list = [];
// Additionally check that the exported properties `foo` and `identifier`
// are defined and have their values assigned at this point.
assert.strictEqual(imported.foo, 42);
assert.strictEqual(imported.identifier, 'package-type-commonjs');
// Check that the module has been evaluated at this point,
// also that it's not evaluated more than once.
assert.deepStrictEqual(['defer-1'], globalThis.eval_list);
// Clean-up
delete globalThis.eval_list;
+17
View File
@@ -0,0 +1,17 @@
// This fixture is imported as a module
// in test/es-module/test-cjs-defer-static-import-eval.mjs
// to ensure a CommonJS module imported with `import defer`
// is only executed once.
const assert = require('assert');
const identifier = 'package-type-commonjs';
module.exports.foo = 42;
module.exports.identifier = identifier;
// The `eval_list` is initialised by the importing module,
// so by the time the fixture is executed, `eval_list` should
// already be initialised.
assert.deepEqual(globalThis.eval_list, []);
globalThis.eval_list.push('defer-1');