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

如何使用cypress-image-snapshot避免每次测试生成带编号的重复截图

问题核心原因&解决方法

  • 参数类型错误
    你调用cy.screenshot时传入的overwrite: 'true'是字符串类型,Cypress要求该参数为布尔值,去掉引号改为overwrite: true才能生效。

  • 配置覆盖范围不匹配
    你在addMatchImageSnapshotCommand中配置的overwrite: true仅对matchImageSnapshot生成的差异截图生效,主动调用的cy.screenshot()不受该插件配置控制,需单独传参或者在Cypress全局配置中统一设置。

  • 重复截图触发重名规则
    你当前的逻辑包含两次截图操作:主动调用cy.screenshot()、matchImageSnapshot自动生成截图,两次默认都使用测试用例名作为文件名,重名后Cypress会自动加编号后缀。你可以选择两种方案规避:

    • 给两次截图分别指定不同的自定义文件名
    • 删掉主动的cy.screenshot()调用,仅用matchImageSnapshot完成基准图存储和对比逻辑
  • 全局配置补充
    在Cypress配置文件中开启自动清理旧资源的开关,从根源避免重名冲突:
    如果是Cypress 10+版本,修改cypress.config.js:

const { defineConfig } = require('cypress');
const { addMatchImageSnapshotPlugin } = require('cypress-image-snapshot/plugin');

module.exports = defineConfig({
  e2e: {
    trashAssetsBeforeRuns: true, // 每次运行测试前自动清空旧截图、录像
    screenshotOnRunFailure: false, // 测试失败时不自动生成额外的失败截图
    setupNodeEvents(on, config) {
      addMatchImageSnapshotPlugin(on, config);
      return config;
    },
  },
});

修正后的代码示例

// 步骤定义
When('the page is displayed on a mobile viewport', () => {
    cy.viewport(800, 750);
});

Then('the page should not be scrollable in a horizontal direction', () => {
    cy.window().scrollTo('right');
    // 指定固定快照名,开启覆盖,不需要提前单独截图
    cy.matchImageSnapshot('grid-mobile-horizontal-test', { overwrite: true });
})

如果需要更新基准快照,运行测试时添加参数即可直接覆盖旧基准图:
cypress run --env updateSnapshots=true


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 19:45:03