示例工程 15-why-bundlers
15-why-bundlers/01-dependency-graph/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { buildGraph, formatGraph, run } from './main.js';
const modules = {
'./main.js': { deps: ['./logger.js', './config.js'] },
'./logger.js': { deps: ['./utils.js'] },
'./config.js': { deps: [] },
'./utils.js': { deps: [] },
};
test('后序排列:依赖先于依赖者', () => {
const graph = buildGraph('./main.js', modules);
assert.deepEqual(graph.order, ['./utils.js', './logger.js', './config.js', './main.js']);
});
test('共享依赖只出现一次', () => {
const shared = {
'./main.js': { deps: ['./a.js', './b.js'] },
'./a.js': { deps: ['./core.js'] },
'./b.js': { deps: ['./core.js'] },
'./core.js': { deps: [] },
};
const graph = buildGraph('./main.js', shared);
assert.equal(graph.order.filter((id) => id === './core.js').length, 1);
assert.equal(graph.order.at(-1), './main.js');
});
test('缺失依赖被记录,不静默跳过', () => {
const graph = buildGraph('./main.js', {
'./main.js': { deps: ['./missing.js'] },
});
assert.deepEqual(graph.missing, [{ id: './missing.js', from: './main.js' }]);
});
test('循环依赖被记录', () => {
const graph = buildGraph('./a.js', {
'./a.js': { deps: ['./b.js'] },
'./b.js': { deps: ['./a.js'] },
});
assert.ok(graph.cycles.length > 0);
assert.equal(graph.order.at(-1), './a.js');
});
test('formatGraph 输出可读文本', () => {
const lines = formatGraph(buildGraph('./main.js', modules));
assert.equal(lines[0], '依赖边:');
assert.ok(lines.some((l) => l.includes('求值顺序')));
});
test('run 汇总模块数', () => {
const out = [];
const graph = run((s) => out.push(s));
assert.equal(graph.order.length, 4);
assert.match(out.at(-1), /模块数:4/);
});