如何开启 Chrome DevTools Protocol 并获取 Performance 日志?

解读

面试官抛出此题,核心想验证三件事:

  1. 你是否知道 Cypress 默认并未直接暴露 CDP(Chrome DevTools Protocol),需要借助官方插件或底层驱动;
  2. 你是否理解 CDP 与 Performance 日志(Performance.getMetrics / Performance.enable)的调用链路;
  3. 你是否能把“开启协议—订阅事件—收集数据—注入报告”完整串起来,并能在国内网络环境下跑通(考虑 Electron 镜像、公司私有 NPM 源、Docker 内网代理等现实因素)。
    答得太浅(“装个插件就行”)会被追问细节;答得太偏(“自己改源码重编 Electron”)会被质疑可维护性。最佳策略是给出官方推荐路径 + 最小可运行代码 + 可落地的工程化封装。

知识点

  1. ** Cypress 底层依赖 Chrome Remote Interface(CRI)**,但只在 cypress run 模式下默认启用;cypress open 需要手动 CYPRESS_REMOTE_DEBUGGING_PORT=9222 开启。
  2. @cypress/chrome-recorder 与 cypress-devtools 社区插件均基于 CDP,但最稳定的是官方 cypress/chrome-recorder 里的 Cypress.automation('remote:debugger:protocol', …) 通道。
  3. Performance 日志分两类:
    • 性能指标(Performance.getMetrics):页面加载完后一次性拉取;
    • 运行时轨迹(Tracing.start/Tracing.end):持续采集,文件大,需流式写盘。
  4. 国内 CI 常见坑:
    • Electron 下载慢 → 在 .npmrc 里写 ELECTRON_MIRROR="https://npmmirror.com/mirrors/electron/";
    • 公司代理拦截 wss → 在 cypress.config.js 里加 proxyBypass: "*.internal.com";
    • 容器无沙箱 → 启动参数加 --no-sandbox --disable-gpu。
  5. 数据闭环:采集后把 JSON 结果挂到 Cypress.mochawesome.reporter 的 addContext,让 Allure 或 ReportPortal 直接渲染趋势图,面试时提到这一点可体现“测试即资产”思维。

答案

下面给出一条在国内私有 NPM 源下可直接落地的最佳实践,覆盖 cypress open 与 cypress run 两种场景,无需改 Cypress 源码,也无需额外插件,仅用官方通道即可。

步骤 1:开启远程调试端口

# Linux / macOS
CYPRESS_REMOTE_DEBUGGING_PORT=9222 cypress open

# Windows PowerShell
$env:CYPRESS_REMOTE_DEBUGGING_PORT=9222; cypress open

步骤 2:在 cypress/support/e2e.js 里封装 CDP 客户端

let client;

Cypress.on('window:before:load', async (win) => {
  if (!client) {
    // 通过官方通道拿到 WebSocket 调试地址
    const wsUrl = await Cypress.automation('remote:debugger:protocol', {
      command: 'Browser.getVersion',
    }).then(() => Cypress.automation('remote:debugger:protocol', {
      command: 'Target.getTargets',
    }).then(res => res.targetInfos.find(t => t.type === 'page').targetId))
    .then(targetId => Cypress.automation('remote:debugger:protocol', {
      command: 'Target.attachToTarget',
      params: { targetId, flatten: true },
    })).then(res => res.sessionId);

    client = await globalThis.CDP({ target: wsUrl });
    await client.send('Performance.enable');
  }
});

Cypress.Commands.add('getPerformanceMetrics', () => {
  return cy.wrap(client.send('Performance.getMetrics')).then(metrics => {
    cy.task('log', metrics);          // 本地调试打印
    cy.task('saveMetrics', metrics);  // 写入 cypress/perf/metrics.json
    return metrics;
  });
});

步骤 3:在测试用例里断言关键指标

it('首页 FCP < 1.5s', () => {
  cy.visit('/');
  cy.getPerformanceMetrics().should(metrics => {
    const fcp = metrics.metrics.find(m => m.name === 'FirstContentfulPaint').value;
    expect(fcp).to.be.lessThan(1500);
  });
});

步骤 4:CI 中固化参数

# .gitlab-ci.yml
variables:
  CYPRESS_REMOTE_DEBUGGING_PORT: 9222
  ELECTRON_MIRROR: "https://npmmirror.com/mirrors/electron/"
script:
  - npm ci --registry=https://registry.npmmirror.com
  - npx cypress run --browser chrome --config video=false

至此,零插件、零源码侵入即可在本地与 CI 同时拿到 Performance 日志,且指标文件自动归档到 cypress/perf/ 目录,方便后续做趋势对比。

拓展思考

  1. 如果面试官追问“我想看长任务(Long Task)怎么办?”
    答:CDP 没有 Long Task 事件,但可在页面注入 PerformanceObserver,把 >50ms 的任务通过 window.postMessage 发到 Cypress 的 cy.window().then(win => win.longTasks),再与 CDP 的 Runtime.enable 时间轴对齐,实现双通道交叉验证。
  2. 若公司强制要求无头模式(gitlab-runner 无图形界面),而官方 --headless=old 在 Electron 下会丢失 CDP,怎么办?
    答:改用 cypress run --browser chrome:headless(新 headless=chrome 模式),并在启动参数里加 --disable-dev-shm-usage --no-sandbox,即可保持 CDP 全功能。
  3. 当性能基线随版本漂移,如何防止“测试红绿抖动”?
    答:把 cypress/perf/metrics.json 作为制品上传到内部 Artifactory,每次 MR 时通过 cypress-grep 动态挑选“性能冒烟用例”,用 cy.task('diffMetrics') 与基线对比,偏差 >10% 自动打回,并@代码提交人。这样就把“开启 CDP 拿日志”升级为质量门禁,面试时抛出可直接打动技术总监。