当使用 Cypress 13 的 native screenshot 时,如何开启 css-animation: paused?

解读

在国内一线大厂的面试里,这道题考察的是“截图稳定性”与“框架新特性”的结合。
Cypress 13 把截图引擎完全重写为 native screenshot,不再依赖外部 Electron 层,因此动画暂停策略也从过去的 cy.screenshot({ disableTimersAndAnimations: true }) 升级为 CSS 变量注入 + 全局样式覆盖。
面试官想确认两点:

  1. 你知道 13 版本以后 disableTimersAndAnimations 被 废弃;
  2. 你能给出 最小侵入、可恢复 的代码实现,而不是简单地把 * { animation-play-state: paused } 写死。

知识点

  • Cypress 13 native screenshot 不再读取 disableTimersAndAnimations 选项,动画控制完全交给用户代码。
  • css-animation: paused 本质是向页面注入 animation-play-state: paused; transition: none !important;。
  • 必须在 screenshot 前注入,screenshot 后恢复,否则后续用例可能因样式残留而失败。
  • 推荐用 Cypress.on('before:screenshot', ...) 与 Cypress.on('after:screenshot', ...) 做 全局钩子,保证所有 cy.screenshot() 及失败自动截图均生效。
  • 对 Web Component 影子 DOM 同样有效,需把样式插到 document.adoptedStyleSheets 或每个 shadowRoot 内。

答案

在 cypress/support/e2e.js 里添加以下代码即可:

// 创建可复用的 CSSStyleSheet
const pauseSheet = new CSSStyleSheet();
pauseSheet.replaceSync(`
  *, *::before, *::after {
    animation-play-state: paused !important;
    transition: none !important;
  }
`);

Cypress.on('before:screenshot', () => {
  // 注入到根文档
  document.adoptedStyleSheets = [...document.adoptedStyleSheets, pauseSheet];
  // 如果项目用了 Shadow DOM,循环注入
  document.querySelectorAll('*').forEach(el => {
    if (el.shadowRoot) {
      el.shadowRoot.adoptedStyleSheets = [...el.shadowRoot.adoptedStyleSheets, pauseSheet];
    }
  });
});

Cypress.on('after:screenshot', () => {
  // 恢复:移除本次注入的 sheet
  document.adoptedStyleSheets = document.adoptedStyleSheets.filter(s => s !== pauseSheet);
  document.querySelectorAll('*').forEach(el => {
    if (el.shadowRoot) {
      el.shadowRoot.adoptedStyleSheets = el.shadowRoot.adoptedStyleSheets.filter(s => s !== pauseSheet);
    }
  });
});

之后无论手动 cy.screenshot() 还是失败自动截图,css-animation 都会被暂停,截图完成后自动恢复,无需改动任何测试用例。

拓展思考

  1. CI 并发场景:若用 --parallel 跑 30+ 容器,上述方案依旧安全,因为每个容器都是独立浏览器实例,样式互不影响。
  2. 性能优化:如果页面动画极多,可在 before:screenshot 里先 cy.window().then(win => win.requestAnimationFrame = null) 进一步冻结帧循环,截图后再还原。
  3. 视觉回归:接入 cypress-image-diff-js 时,把暂停逻辑封装成自定义命令 cy.matchImageWithPause('home'),可让基线图 100% 稳定,零像素抖动。
  4. 兼容性兜底:部分老旧项目仍用 Cypress 10,可保留 disableTimersAndAnimations: true 作为降级,但需通过 Cypress.version 做 运行时分支,保证升级 13 时无缝切换。