当断言失败时,如何将每次重试的 DOM 快照保存为 GIF?
解读
面试官抛出这道题,核心想验证三件事:
- 你是否真的踩过“断言重试却看不到中间态”的坑;
- 对 Cypress 的失败重试机制与命令队列有没有源码级理解;
- 能否在不污染测试代码的前提下,把“重试现场”落地为可回溯的国产研发资产(GIF 比静态图更直观,方便国内飞书、钉钉群快速传播)。
注意:Cypress 默认只在最后一次失败时生成 PNG,不会为每次重试自动落盘,更不会直接出 GIF;需要我们自己“钩”住重试生命周期,把 DOM 变化帧序列串成 GIF。
知识点
- Cypress 重试模型:
- 命令队列在 cypress-runner 里循环执行,内部用
retryVerifier判断断言; - 每次重试都会触发
runner:retry事件,携带err、command、当前$el快照。
- 命令队列在 cypress-runner 里循环执行,内部用
- DOM 快照采集:
cy.screenshot()只能截整屏,无法精准捕获重试时的微小时差;- 更底层可用
Cypress.dom.getElementScreencapture($el)(私有 API,国内镜像源可正常访问)拿到元素级 canvas。
- GIF 合成:
- 在 Node 层用
gif-encoder-2或gifski-wasm(国内 npm 镜像同步及时); - 把每帧 canvas 转成 RGBA Buffer,控制 8 fps、256 色,单文件 <2 MB,方便上传国内 CI 产物仓库。
- 在 Node 层用
- 插件注入姿势:
- 必须写在
cypress/plugins/index.js的on('task')里,避免浏览器端权限问题; - 利用
on('task:retry')把帧数据通过 IPC 发到 Node 进程,边采集边流式写入,防止内存爆掉。
- 必须写在
- 合规与性能:
- 国内很多公司用 Windows 代理机,需把
gifski.exe一起打包到.gitignore例外目录; - 重试间隔默认 400 ms,可动态降到 200 ms 减少帧数,防止 GitLab-CI 上传超时。
- 国内很多公司用 Windows 代理机,需把
答案
-
安装依赖(华为云镜像示例)
npm i --save-dev gif-encoder-2 canvas globby -
在
cypress/plugins/retryGif.js实现任务const { createCanvas } = require('canvas'); const GIFEncoder = require('gif-encoder-2'); const fs = require('fs'); const path = require('path'); let encoder, frameIndex = 0; const tmpDir = path.join(__dirname, '../../.retry-gif'); module.exports = (on, config) => { on('task:retry', async ({ title, selector, html }) => { if (!encoder) { fs.mkdirSync(tmpDir, { recursive: true }); encoder = new GIFEncoder(800, 600, 'neuquant'); // 统一画布大小 encoder.start(); encoder.setRepeat(0); encoder.setDelay(200); // 与重试间隔对齐 } // 把 html 字符串画到 canvas const canvas = createCanvas(800, 600); const ctx = canvas.getContext('2d'); await require('canvas').loadImage(`data:text/html;charset=utf-8,${encodeURIComponent(html)}`) .then(img => ctx.drawImage(img, 0, 0)); encoder.addFrame(ctx); frameIndex++; return null; }); on('after:spec', (spec, results) => { if (encoder) { encoder.finish(); const buf = encoder.out.getData(); const file = path.join(tmpDir, `${spec.name}-${Date.now()}.gif`); fs.writeFileSync(file, buf); encoder = null; frameIndex = 0; console.log('**** 重试 GIF 已生成:', file); } }); }; -
在
cypress/support/e2e.js劫持重试Cypress.on('runner:retry', (retry) => { const $el = retry.command?.get('subject'); if ($el && $el.length) { cy.task('retry:gif', { title: retry.command.get('name'), selector: $el.selector, html: $el[0].outerHTML }, { log: false }); } }); -
配置
cypress.config.jsconst { defineConfig } = require('cypress'); const retryGif = require('./cypress/plugins/retryGif'); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { retryGif(on, config); return config; }, defaultCommandTimeout: 8000, // 给足重试次数 retries: { runMode: 3, openMode: 0 } } }); -
运行与取证
npx cypress run --spec 'cypress/e2e/flaky.cy.js' # 产物位于 .retry-gif/xxx.gif,可直接上传到阿里云 OSS 做持久化
拓展思考
- 如果测试跑在国产操作系统统信 UOS上,canvas 依赖的 Cairo 库可能缺失,可预装
libpixman-1-dev或改用 headless Chrome 的--disable-gpu模式。 - 当页面带视频或 CSS 动画时,静态 HTML 转 canvas 会掉帧,可在
runner:retry里先cy.get(selector).invoke('css', 'animation', 'none')冻结样式,保证 GIF 可重复。 - 为了对接国内测试平台(如飞书 TestHub、腾讯 WeTest),可把 GIF 二次压缩成 640×360、256 色、≤500 KB,再调用平台提供的
@testhub/uploaderSDK 自动关联用例 ID,实现“失败即在看板可播放”。