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

Cypress中如何同时Stub请求并获取响应?

解决Cypress Stub响应同时获取真实响应数据的问题

当你直接用cy.intercept的第二个参数传入Stub数据时,Cypress会跳过真实后端请求,直接返回你定义的Stub内容,所以$resp.response里只有Stub数据,自然拿不到真实响应里的date值。要同时实现Stub响应和获取真实数据,你可以用以下两种方式:

方式一:通过req.reply函数捕获真实响应

用函数式的req.reply,先获取真实后端的响应,再返回自定义Stub数据,同时保存真实响应里的date:

cy.intercept('POST', '**/myURL', (req) => {
  // 先请求真实后端获取响应
  req.reply((res) => {
    // 提取真实响应中的date值
    const realDate = res.body.date;
    // 保存date供后续使用
    cy.wrap(realDate).as('realResponseDate');
    
    // 返回Stub数据,也可以结合真实数据一起返回
    res.send({
      ...res.body,  // 可选:保留真实响应的其他字段
      customStubField: 'stubbed content'  // 自定义Stub字段
    });
  });
}).as('successfulAction');

cy.get('button').click();

cy.wait('@successfulAction').then(($resp) => {
  // 打印Stub后的响应数据
  cy.log('Stub响应数据:', $resp.response.body);
  // 取出之前保存的真实date值
  cy.get('@realResponseDate').then((date) => {
    cy.log('真实响应的date:', date);
  });
});

方式二:使用中间件拦截并修改响应

开启middleware: true,先捕获真实响应,再替换为Stub内容,同时保留真实数据:

cy.intercept({
  method: 'POST',
  url: '**/myURL',
  middleware: true  // 开启中间件,确保优先处理真实请求
}, (req) => {
  req.continue((res) => {
    // 提取真实响应的date
    const realDate = res.body.date;
    cy.wrap(realDate).as('realDate');
    
    // 将响应替换为Stub数据
    res.body = { stubbedKey: 'stubbed value' };
  });
}).as('successfulAction');

cy.get('button').click();

cy.wait('@successfulAction').then(($resp) => {
  cy.log('Stub响应:', $resp.response.body);
  cy.get('@realDate').then((date) => {
    cy.log('真实date:', date);
  });
});

核心逻辑是:不要直接在cy.intercept的第二个参数传Stub对象,而是用函数形式先获取真实后端的响应,再返回Stub内容,这样就能同时拿到真实数据和自定义的Stub响应了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:57:09