如何对 performance.now() 做高精度 mock?
解读
国内一线公司(阿里、字节、腾讯、美团)的单测面试里,高频追问“浏览器 API 怎么 mock”。
performance.now() 返回 DOMHighResTimeStamp(微秒级,双精度浮点),在单元测试里需要满足:
- 可重复:同一用例多次跑结果一致;
- 可递增:用来测节流、动画帧、超时逻辑时,时间必须“往前走”;
- 高精度:不能只用整数毫秒,否则 0.1 ms 的误差会导致用例抖动;
- 零副作用:跑完用例后把全局对象恢复原状,避免污染其他用例。
Jest 官方只有 jest.spyOn(global, 'Date').mockImplementation() 的示例,没有高精度时间。
面试官想看你是否能把 spy、mockImplementation、mockRestore、闭包变量、BigInt 微秒换算等知识点串起来,给出一个“可插拔、可复用、可链式调用”的通用方案。
知识点
- Jest spy & mock:jest.spyOn、mockImplementation、mockReturnValue、mockRestore。
- performance.now 规范:返回值单位毫秒,但带小数,精度 5µs 以内。
- 闭包保存“虚拟时间”:用 Number 或 BigInt 保存微秒,避免浮点累加误差。
- 递增策略:
- 固定步长( deterministicStep )
- 随机抖动( jitter )
- 真实时间缩放( accelerated )
- 清理机制:afterEach / beforeEach 自动 restore,防止测试间污染。
- TypeScript 类型:declare global { interface Performance { now: () => number } }。
- 并发场景:并行跑测试时,每个文件需要独立虚拟时间,禁止共享全局变量。
- 与 Timer Mocks 的区别:jest.useFakeTimers 只能 mock setTimeout/Date,不覆盖 performance。
答案
// __tests__/utils/performanceMock.js
export function installPerformanceMock(opts = {}) {
const {
initialTime = 0, // 起始时间,单位毫秒
step = 0.123, // 每次调用递增步长,默认 123 微秒
maxDrift = 0, // 允许随机抖动,单位毫秒
} = opts;
// 用 BigInt 保存微秒,避免浮点误差
let microTime = BigInt(Math.round(initialTime * 1000));
const spy = jest.spyOn(global.performance, 'now').mockImplementation(() => {
const drift = maxDrift ? Math.random() * maxDrift : 0;
const currentMs = Number(microTime) / 1000 + drift;
microTime += BigInt(Math.round(step * 1000));
return currentMs;
});
// 提供“快进”api,方便测节流函数
spy.advance = (ms) => {
microTime += BigInt(Math.round(ms * 1000));
};
// 提供“重置”api,支持多轮断言
spy.reset = (newInitial = initialTime) => {
microTime = BigInt(Math.round(newInitial * 1000));
};
return spy;
}
// 使用示例
// __tests__/throttle.test.js
import { installPerformanceMock } from './utils/performanceMock';
describe('throttle(fn, 16ms)', () => {
let perfSpy;
beforeEach(() => {
perfSpy = installPerformanceMock({ step: 0.1 });
});
afterEach(() => {
perfSpy.mockRestore();
});
it('should only invoke once within 16ms window', () => {
const fn = jest.fn();
const throttled = throttle(fn, 16);
throttled(); // 0ms
expect(fn).toHaveBeenCalledTimes(1);
perfSpy.advance(15.9); // 高精度
throttled();
expect(fn).toHaveBeenCalledTimes(1);
perfSpy.advance(0.2); // 16.1ms
throttled();
expect(fn).toHaveBeenCalledTimes(2);
});
});
要点回顾
- 用 BigInt 保存微秒,彻底规避 0.1+0.2≠0.3 的浮点坑。
- spy 附带 advance/reset,让用例代码“指哪打哪”。
- afterEach 统一 restore,保证测试隔离。
- 支持并发:每个文件内部闭包,互不干扰。
拓展思考
-
快照测试:把 performance.now() 序列化到 Jest Snapshot 时,如何隐藏平台差异?
答:在序列化器里把返回值统一截断到小数后三位,或把 spy 换成固定步长 0.001。 -
Web Worker 环境:worker 里拿不到 global.performance,需要把 mock 注入到 worker 上下文。
答:用 jest-worker 或 node-worker-thread 时,在 setup 文件里 postMessage 把虚拟时间基准传进去,再在 worker 内部重新 install。 -
与 Chrome DevTools 的 Performance 面板对齐:
如果要做“端到端性能断言”,可把虚拟时间序列导出为 JSON,再写脚本生成 trace-event 格式,直接拖进 DevTools 验证关键路径。 -
0 ms 边界:
当 step=0 时,performance.now() 恒定返回 initialTime,可用来测纯函数是否依赖时间戳。 -
多运行时复用:
把 installPerformanceMock 抽成 npm 包(如 jest-performance-now-mock),在 CI 里同时跑 Node 14/16/18 与 Chromium 环境,验证高精度递增策略是否跨平台一致。