示例工程 14-module-resolution-import-maps
14-module-resolution-import-maps/03-circular-esm-cjs/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { cjsCycle, esmCycle, run } from './main.js';
test('ESM 循环依赖在求值阶段抛 ReferenceError', async () => {
const r = await esmCycle();
assert.equal(r.ok, false);
assert.equal(r.name, 'ReferenceError');
assert.match(r.message, /before initialization/);
});
test('CJS 循环依赖不报错,但字段缺失', () => {
const r = cjsCycle();
assert.equal(r.a.name, 'a');
assert.equal(r.a.bName, 'b');
assert.equal(r.b.name, 'b');
assert.equal(r.b.sawA, 'a');
assert.equal(r.bAwareOfA, undefined);
});
test('修复方式:把跨模块访问推迟到函数调用', async () => {
const a = await import('./cycle-fixed-a.js');
const b = await import('./cycle-fixed-b.js');
assert.equal(a.getB(), 'b');
assert.equal(b.combined(), 'a-b');
});
test('run 汇总两种模型的结果', async () => {
const out = [];
const rows = await run((s) => out.push(s));
assert.equal(rows.length, 4);
assert.equal(rows[1][1], 'ReferenceError');
assert.match(out.at(-1), /半成品/);
});