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
相关产品推荐
相关产品推荐

