You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jest测试框架中实现函数调用计时?

用Jest测试函数执行耗时的方案

嘿,我之前也遇到过同样的需求——想用Jest来监控函数执行耗时,确保不超过阈值。虽然Jest确实没有内置专门的API来做这件事,但我们可以结合它的断言系统和原生JS的计时能力轻松实现,而且灵活性拉满!

方法一:基础单次计时断言

我们可以封装一个简单的工具函数,在调用目标函数前后记录时间,然后用Jest的toBeLessThan断言来验证耗时是否符合要求。不管是同步还是异步函数都能适配:

// 封装计时断言工具
const expectToExecuteWithin = async (fn, maxDurationMs) => {
  const startTime = performance.now();
  // 异步函数需要await,同步函数会自动跳过await逻辑
  await fn();
  const endTime = performance.now();
  const executionTime = endTime - startTime;
  
  // 用Jest原生断言验证耗时
  expect(executionTime).toBeLessThan(maxDurationMs);
};

// 测试同步函数
test('syncFunction runs within 100ms', () => {
  expectToExecuteWithin(() => syncFunction(), 100);
});

// 测试异步函数
test('asyncFunction runs within 200ms', async () => {
  await expectToExecuteWithin(() => asyncFunction(), 200);
});

方法二:多次执行取平均(避免单次波动)

如果担心单次执行的耗时波动影响测试结果,可以封装一个取平均耗时的工具,多次执行目标函数后计算平均值再断言:

const expectAverageExecutionWithin = (fn, maxAvgDurationMs, iterations = 10) => {
  let totalDuration = 0;
  
  for (let i = 0; i < iterations; i++) {
    const start = performance.now();
    fn();
    totalDuration += performance.now() - start;
  }
  
  const avgDuration = totalDuration / iterations;
  expect(avgDuration).toBeLessThan(maxAvgDurationMs);
};

// 测试示例:要求10次执行的平均耗时不超过50ms
test('syncFunction has average execution time under 50ms', () => {
  expectAverageExecutionWithin(() => syncFunction(), 50);
});

注意事项

  • 对于异步函数,一定要记得在测试用例和工具函数中使用await,否则计时会在函数还未执行完成时就结束,导致结果完全不准确。
  • performance.now()比Date.now()的计时精度更高,更适合做性能测试;如果运行环境不支持performance API,也可以替换成Date.now()。
  • 如果你的函数有依赖外部资源(比如API请求、数据库操作),建议在测试前模拟这些依赖,避免外部因素影响计时结果。

内容的提问来源于stack exchange,提问作者terrible-coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:17:50