如何监听 Runtime.exceptionThrown 并截图?

解读

在国内一线大厂的 Cypress 面试中,这道题考察的是“当页面出现未捕获异常时,测试脚本如何主动感知并留存现场”。
很多候选人只回答 cy.screenshot(),却忽略了两个关键点:

  1. Cypress 默认不会把浏览器 Console 里的 Runtime.exceptionThrown 当成测试失败,除非手动监听;
  2. 截图必须与异常发生时的上下文(测试用例名、浏览器视口、时间戳)绑定,否则在 CI 里无法定位。
    因此,面试官想听到的是“在 Node 层打通 Chrome DevTools Protocol,把异常事件同步到 Cypress 命令队列,并保证截图命名可追踪”的完整闭环。

知识点

  1. Chrome DevTools Protocol(CDP):Cypress 通过 Cypress.automation('remote:debugger:protocol', ...) 暴露底层调试接口,可订阅 Runtime.exceptionThrown。
  2. Cypress 任务队列:Node 插件(setupNodeEvents)里注册的 task 是唯一能把异步异常信息带回命令队列的通道。
  3. 截图时机:必须等异常信息到达 Node 端后再调用 cy.screenshot(),否则截图里可能还没抛出异常。
  4. 命名规范:国内公司普遍要求“用例名_时间戳_异常类型”作为文件名,方便 Allure 或 Mochawesome 报告聚合。
  5. CI 兼容性:在 Docker 容器里跑测试时,要确认 --disable-dev-shm-usage 与 --no-sandbox 不会关闭 CDP。

答案

  1. 在 cypress.config.js 中接入 CDP:
const { defineConfig } = require('cypress');
let exceptionInfo = null;

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('before:browser:launch', (browser, launchOptions) => {
        if (browser.family === 'chromium') {
          launchOptions.args.push('--remote-debugging-port=9222');
        }
        return launchOptions;
      });

      on('task', {
        async registerExceptionListener() {
          const cdp = await require('chrome-remote-interface')();
          await cdp.Runtime.enable();
          cdp.Runtime.exceptionThrown(({ exceptionDetails }) => {
            exceptionInfo = {
              description: exceptionDetails.exception.description,
              timestamp: Date.now(),
              url: exceptionDetails.url,
              lineNumber: exceptionDetails.lineNumber,
            };
          });
          return null;
        },

        getLastException() {
          const tmp = exceptionInfo;
          exceptionInfo = null;   // 消费后清空
          return tmp;
        },
      });
    },
  },
});
  1. 在支持用例里先注册监听器,再断言异常并截图:
describe('异常捕获与截图', () => {
  before(() => {
    cy.task('registerExceptionListener');
  });

  it('**点击按钮触发未捕获异常时应自动截图**', () => {
    cy.visit('/demo');
    cy.get('#crash-btn').click();

    // 等待异常信息回传
    cy.task('getLastException').should('not.be.null').then((ex) => {
      cy.log(`捕获异常: ${ex.description}`);
      cy.screenshot(
        `exception_${Cypress.currentTest.title}_${ex.timestamp}`,
        { capture: 'fullPage' }
      );
    });
  });
});
  1. 在 CI 脚本里把截图目录 cypress/screenshots 作为制品(artifact)上传,即可在 Allure 报告里看到“用例名_exception_时间戳.png”的附件。

拓展思考

  • 多浏览器兼容:Firefox 与 Edge 也支持 CDP,但协议版本号不同,需在 before:browser:launch 里动态判断 browser.majorVersion,避免本地调试正常、线上容器失效。
  • 重复异常降噪:如果同一用例连续抛出多条异常,可在 Node 端做滑动时间窗口去重(如 500 ms 内只保留第一条),防止截图爆炸。
  • 与 Cypress FailFast 插件结合:在 support/index.js 里监听 Cypress.on('fail'),把异常截图路径写入环境变量,供后续步骤直接上传 OSS,实现“失败即留痕、秒级回传”,满足国内金融客户对审计的硬性要求。