示例工程 08-event-loop-concurrency
08-event-loop-concurrency/03-worker-heavy/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { formatMs, heavySum, run } from './main.js';
test('heavySum 的结果与闭式公式一致', () => {
for (const n of [0, 1, 10, 1000]) {
assert.equal(heavySum(n), n === 0 ? 0 : (n * (n - 1)) / 2);
}
});
test('heavySum 在 5e7 规模下仍返回安全整数', () => {
const n = 5e7;
const result = heavySum(n);
assert.equal(result, (n * (n - 1)) / 2);
assert.ok(Number.isSafeInteger(result));
});
test('formatMs 保留一位小数', () => {
assert.equal(formatMs(12.345), '12.3ms');
assert.equal(formatMs(0), '0.0ms');
});
test('Node 里调用 run 给出环境错误', async () => {
await assert.rejects(() => run(() => {}), /需要浏览器环境/);
});