示例工程 15-why-bundlers
15-why-bundlers/03-wrapped-runtime/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { GRAPH, buildBundle, evaluateBundle, run } from './main.js';
const bundle = buildBundle(GRAPH, './main.js');
test('打包产物是一个可求值的表达式,包含模块表与 __require', () => {
assert.match(bundle, /function __require/);
assert.match(bundle, /"\.\/main\.js": function/);
assert.match(bundle, /"\.\/utils\.js": function/);
});
test('入口模块返回预期结果', () => {
const result = evaluateBundle(bundle);
assert.equal(result.run(), '[DEMO]');
});
test('同一模块只执行一次,缓存复用', () => {
const result = evaluateBundle(bundle);
assert.equal(result.utilsCalls(), 1);
assert.equal(result.sameUtils, true);
});
test('每次求值产物都有独立缓存', () => {
const a = evaluateBundle(bundle);
const b = evaluateBundle(bundle);
assert.notEqual(a, b);
assert.equal(a.run(), b.run());
});
test('缺少模块时运行时抛错', () => {
const broken = buildBundle({ './main.js': "require('./missing.js');" }, './main.js');
assert.throws(() => evaluateBundle(broken), /modules\[id\] is not a function/);
});
test('run 输出结果与统计', () => {
const out = [];
const result = run((s) => out.push(s));
assert.equal(result.run, '[DEMO]');
assert.equal(result.calls, 1);
assert.match(out.at(-1), /每个模块一层函数/);
});