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

Karma无法触发onSpecStart事件,如何测量Angular测试用例耗时?

Angular测试用例计时Reporter修复方案

你的问题核心是Karma Reporter API中不存在针对单个测试用例的onSpecStart事件——这个事件实际是用来监听**测试套件(describe块)**启动的,而非单个it测试用例。

单个测试用例的启动/完成对应的正确事件是onTestStart和onTestComplete,修改后的Reporter代码如下:

function SpecTimingReporter(baseReporterDecorator, config, logger) {
  baseReporterDecorator(this);

  const log = logger.create('spec-timing-reporter');
  let testStartTime = 0;

  // 单个测试用例启动时触发
  this.onTestStart = function(test) {
    testStartTime = Date.now();
  };

  // 单个测试用例完成时触发
  this.onTestComplete = function(browser, testResult) {
    const elapsedTime = Date.now() - testStartTime;
    log.info(`Test "${testResult.description}" took ${elapsedTime} ms to complete.`);
  };
}

额外注意点:

  • 避免用this.startTime存储时间戳,普通函数的this上下文可能在事件触发时丢失,改用局部变量testStartTime更可靠
  • onTestStart的参数是单个测试用例的test对象,onTestComplete返回的testResult包含该测试的描述、结果等信息

内容的提问来源于stack exchange,提问作者SzymonPoltorak

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 02:49:55