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

本地与Jenkins流水线中Cypress截图尺寸不一致问题求助

解决Cypress + cypress-image-diff-js截图尺寸与视口配置不符的问题

以下是针对本地无头模式和Jenkins流水线中截图尺寸偏差的具体解决方案:

  • 显式在测试中锁定视口
    全局视口配置可能被测试用例、插件或浏览器默认行为覆盖,建议在测试前置钩子中强制设置:

    beforeEach(() => {
      cy.viewport(1300, 800);
    });
    
  • 配置无头Chrome的强制窗口参数
    无头模式下Chrome可能忽略Cypress的视口配置,需要在cypress.config.ts中添加Chrome启动参数,强制窗口尺寸和缩放比例:

    export default defineConfig({
      e2e: {
        baseUrl: "URL",
        chromeWebSecurity: false,
        supportFile: "./cypress/support/e2e-mock.ts",
        video: true,
        setupNodeEvents(on, config) {
          return getCompareSnapshotsPlugin(on, config);
        },
        chromeWebPreferences: {
          args: [
            '--window-size=1300,800',
            '--force-device-scale-factor=1' // 避免系统缩放导致尺寸偏差
          ]
        }
      },
      viewportWidth: 1300,
      viewportHeight: 800,
    });
    
  • 同步cypress-image-diff-js的截图尺寸配置
    在cypress-image-diff.config中明确指定截图的宽高,确保与视口配置一致:

    const config = {
      FAILURE_THRESHOLD: 0.02,
      RETRY_OPTIONS: {
        log: true,
        limit: 3,
        timeout: 20000,
        delay: 500,
      },
      CYPRESS_SCREENSHOT_OPTIONS: {
        capture: "viewport",
        width: 1300,
        height: 800
      },
    };
    
    module.exports = config;
    
  • Jenkins环境中禁用系统缩放
    Jenkins节点的系统缩放设置会影响截图尺寸,需在流水线中添加环境变量强制缩放为1:

    • Linux/macOS节点:
      export GDK_SCALE=1
      export GDK_DPI_SCALE=1
      
    • Windows节点:
      Set-ItemProperty -Path "HKCU:\Control Panel\Desktop" -Name LogPixels -Value 96
      
  • 调试验证视口尺寸
    在测试中添加日志,确认当前视口尺寸是否符合预期,方便定位问题:

    cy.viewport(1300, 800).then(() => {
      cy.window().then(win => {
        console.log('当前视口宽度:', win.innerWidth);
        console.log('当前视口高度:', win.innerHeight);
      });
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 03:03:34