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

Playwright中安装clock后performance.getEntriesByName为何无结果?

解决方案

原因分析

Playwright的page.clock.install()会替换浏览器原生的时间相关API(如setTimeout、Date),但浏览器的Performance Timeline API依赖内部真实时间推进逻辑,不会与模拟时钟同步,因此在模拟时钟下无法自动生成性能条目,包括导航、资源请求等类型的条目。

替代方案:使用Playwright网络监控API

放弃依赖浏览器的Performance API,改用Playwright内置的网络监听能力来捕获请求并验证相关信息,该方式不受模拟时钟影响,且能精准获取请求的时序数据:

await page.goto("my/url");
await page.clock.install();

// 提前监听目标请求和响应
const targetUrl = "http://localhost/my/other/url";
const requestWaiter = page.waitForRequest(targetUrl);
const responseWaiter = page.waitForResponse(targetUrl);

// 触发请求
await page.evaluate(async () => {
  await fetch("my/other/url");
});

// 获取请求和响应对象
const request = await requestWaiter;
const response = await responseWaiter;

// 验证响应状态(示例)
expect(response.status()).toBe(200);

// 获取Playwright记录的请求时序数据(替代Performance条目)
const timing = request.timing();
// 可断言时序指标,比如请求总耗时
expect(timing.responseEnd - timing.requestStart).toBeLessThan(1000);

额外说明

如果你的测试场景必须依赖Performance API的原生行为,目前Playwright的模拟时钟暂不支持同步Performance Timeline,这种情况下可以考虑:

  • 针对该测试用例关闭模拟时钟,改用真实时间(可通过缩短实际超时时间优化测试速度,比如将30秒改为1秒,只要逻辑验证通过即可)
  • 手动在evaluate中创建Performance标记(但这属于模拟测试数据,仅适用于特定场景)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 19:19:50