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

如何在Cypress中模拟浏览器后退时的HTTP POST重载行为?

解决Cypress中cy.go('back')处理POST页面后退的问题

问题核心

POST加载的页面手动后退时,浏览器会读取磁盘缓存自动完成重发,但Cypress执行cy.go('back')时触发net::ERR_CACHE_MISS/NS_ERROR_DOCUMENT_NOT_CACHED错误,导致浏览器弹出重新提交提示。本质是Cypress默认浏览器配置禁用了磁盘缓存,或代理机制影响了缓存存储逻辑。

解决方案

1. 配置Cypress启用浏览器磁盘缓存

修改cypress.config.js,为Chrome/Firefox添加启用磁盘缓存的启动参数,同时调整Cypress缓存策略:

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

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // 针对Chrome配置
      on('before:browser:launch', (browser = {}, launchOptions) => {
        if (browser.name === 'chrome') {
          launchOptions.args.push('--disk-cache-size=1073741824');
          launchOptions.args.push('--disable-features=CacheDeleteOnExit');
        }
        if (browser.name === 'firefox') {
          launchOptions.preferences['browser.cache.disk.enable'] = true;
          launchOptions.preferences['browser.cache.disk.capacity'] = 1073741824;
        }
        return launchOptions;
      });
    },
    experimentalSessionAndOrigin: true,
    cacheAcrossSpecs: true,
  },
});

2. 拦截POST请求并手动缓存响应

如果浏览器配置调整无效,用cy.intercept拦截初始POST请求并缓存响应,后退触发重复POST时直接返回缓存内容:

describe('test', () => {
  let postResponse;

  const visit = () => {
    cy.visit('https://example.org');
    cy.intercept('POST', '/your-post-endpoint').as('postRequest');
    cy.get('#button').click();
    cy.wait('@postRequest').then((interception) => {
      postResponse = interception.response;
    });
  };

  it('Iterate over all links and back', () => {
    visit();
    cy.intercept('POST', '/your-post-endpoint', (req) => {
      req.reply(postResponse);
    });

    cy.get('a.link')
      .each((el, index) => {
        cy.get('a.link').eq(index).click();
        /* Do my thing */
        cy.go('back');
        cy.get('#button').should('be.visible');
      });
  });
})

注意:替换/your-post-endpoint为实际的POST请求路径

3. 模拟浏览器确认重发POST请求

作为兜底方案,直接模拟浏览器确认弹窗,自动点击"确认"按钮:

describe('test', () => {
  const visit = () => {
    cy.visit('https://example.org');
    cy.get('#button').click();
  };

  it('Iterate over all links and back', () => {
    visit();
    cy.window().then((win) => {
      cy.stub(win, 'confirm').returns(true);
    });

    cy.get('a.link')
      .each((el, index) => {
        cy.get('a.link').eq(index).click();
        /* Do my thing */
        cy.go('back');
        cy.get('#button').should('be.visible');
      });
  });
})

注意事项

  • 方案1需确保Cypress代理证书已正确添加到信任存储(你已完成此步骤),否则磁盘缓存可能仍无法生效。
  • 方案3未模拟手动缓存加载的真实行为,仅强制确认重发,建议优先尝试前两种方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 07:57:37