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

Cypress测试如何清除浏览器缓存解决请求拦截失败问题

Cypress测试静态资源请求时被缓存导致拦截失败的解决方法

问题场景

编写Cypress E2E用例,校验商品详情页点击主图触发放大操作时,是否发起指定webp格式的图片资源请求。首次执行用例可正常拦截目标请求,重复执行时由于浏览器缓存了静态图片资源,不会重新发起网络请求,导致cy.intercept无法捕获对应请求,用例断言失败。
原有问题代码如下:

it('should request webp image format for zoomed pdp image', () => {
  cy.intercept(
    '**/cdn/cs/set/assets/blt2bd0405f3cb027cb/5005769.jpg?fit=bounds&format=webply&quality=80&width=1600&height=1600&dpr=1.5'
  ).as('zoomedImageRequest');
  cy.gotoPage('product/transparent-red-sorting-case-to-go-5005769');
  cy.get(pdp.pdpImage).click();
  cy.wait('@zoomedImageRequest').then((xhr) => {
    const zoomedImageUrl = xhr.response.url;
    expect(zoomedImageUrl).to.contain('format=webply');
  });
});

可行解决方案

方案1:全局配置浏览器禁用缓存(最推荐,稳定性最高)

通过Cypress的浏览器启动钩子,在测试启动时直接关闭浏览器缓存能力,从根源避免静态资源被缓存,一次配置所有用例生效。
修改cypress.config.js配置文件:

const { defineConfig } = require("cypress");

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on('before:browser:launch', (browser, launchOptions) => {
        // Chromium内核浏览器(Chrome、Edge、Electron)配置
        if (browser.family === 'chromium') {
          launchOptions.args.push('--disk-cache-size=0');
          launchOptions.args.push('--disable-application-cache');
          // 可选:开启匿名模式,每次运行用全新上下文
          launchOptions.args.push('--incognito');
        }
        // Firefox浏览器配置
        if (browser.family === 'firefox') {
          launchOptions.preferences['browser.cache.disk.enable'] = false;
          launchOptions.preferences['browser.cache.memory.enable'] = false;
          launchOptions.preferences['network.http.use-cache'] = false;
          launchOptions.args.push('-private');
        }
        return launchOptions;
      })
    },
  },
});

额外补充全局beforeEach兜底逻辑,在cypress/support/e2e.js中添加:

beforeEach(() => {
  cy.clearAllCookies();
  cy.clearAllLocalStorage();
  cy.clearAllSessionStorage();
  // Cypress 13.3及以上版本支持直接调用API清空浏览器缓存
  if (Cypress.version >= '13.3.0' && Cypress.isBrowser('chromium')) {
    Cypress.automation('clear:browser:cache', {}).catch(() => {});
  }
});

方案2:单用例内拦截请求时强制绕开缓存

如果不想修改全局配置,可以针对单个用例的拦截规则,修改请求头强制不使用缓存,同时添加缓存破坏参数确保请求重新发送。
修改后的用例代码:

it('should request webp image format for zoomed pdp image', () => {
  cy.intercept(
    // 用通配符匹配,避免参数顺序、额外参数导致漏拦截
    '**/cdn/cs/set/assets/blt2bd0405f3cb027cb/5005769.jpg*',
    (req) => {
      // 设置无缓存请求头
      req.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate';
      req.headers['Pragma'] = 'no-cache';
      // 追加随机时间戳参数,破坏缓存命中条件
      req.query['_cb'] = Date.now() + Math.random();
      req.continue();
    }
  ).as('zoomedImageRequest');
  cy.gotoPage('product/transparent-red-sorting-case-to-go-5005769');
  cy.get(pdp.pdpImage).click();
  cy.wait('@zoomedImageRequest').then((interception) => {
    // 直接取请求query对象校验,避免追加的缓存参数影响url匹配
    expect(interception.request.query.format).to.eq('webply');
  });
});

注意:不要直接匹配完整url做断言,追加缓存参数后url会新增自定义字段,直接读取request.query中对应字段校验更准确。


方案选择建议

优先选择方案1,不需要修改单个用例逻辑,不会因为漏配拦截规则导致偶现失败,适合测试套件内所有涉及静态资源请求校验的场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 05:24:28