示例工程 22-security-service-worker
22-security-service-worker/06-performance-marks/main.test.mjs
点击「运行示例」后,左侧显示源码、右侧显示运行结果;console 输出会实时回传。
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { measureWork, run } from './main.js';
test('measureWork 返回结果与耗时', () => {
const r = measureWork('t1', () => 42);
assert.equal(r.result, 42);
assert.ok(r.duration >= 0);
assert.equal(r.entries, 1);
});
test('重复同名 measure 会累积条目', () => {
measureWork('t2', () => {});
measureWork('t2', () => {});
const entries = performance.getEntriesByName('t2');
assert.ok(entries.length >= 2);
});
test('mark 名字包含 start/end', () => {
measureWork('t3', () => {});
assert.ok(performance.getEntriesByName('t3:start').length >= 1);
assert.ok(performance.getEntriesByName('t3:end').length >= 1);
});
test('函数抛错时仍记录 end mark', () => {
assert.throws(() => {
measureWork('t4', () => {
throw new Error('boom');
});
}, /boom/);
assert.ok(performance.getEntriesByName('t4:end').length >= 1);
});
test('run 输出结果与耗时', () => {
const out = [];
const r = run((s) => out.push(s));
assert.equal(r.result, 499999500000);
assert.match(out[1], /耗时/);
});