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

如何覆盖cy.request并记录所有测试请求响应至文件(Cypress 13.2.0)

捕获Cypress中cy.request()发起的请求

问题背景

  • 使用Cypress 13.2.0进行E2E测试,需收集所有通过cy.request(...)发起的请求,用于流水线后续分析
  • cypress-har-generator插件仅能拦截浏览器请求,无法捕获cy.request在Node.js环境中执行的请求
  • cy.intercept仅针对应用发起的请求,不适用于cy.request

尝试过的方案及错误

第一次改写代码

Cypress.Commands.overwrite("request", (originalFn, ...options) => {
  return originalFn(...options).then(response => {
    try {
      cy.writeFile('requests.log', `${JSON.stringify({ options,  response })}\n`, {flag: 'a+'});
      // 尝试返回响应但仍报错
      // cy.wrap(response);
    } catch (e) {
      console.log(e)
    }
  })
});

运行时出现错误:

CypressError: Cypress detected that you returned a promise
from a command while also invoking one or more cy commands
in that promise.

The command that returned the promise was:

cy.request()

The cy command you invoked inside the promise was:

cy.writeFile()

Because Cypress commands are already promise-like,
you don't need to wrap them or return your own promise.

第二次修改(去掉return)

Cypress.Commands.overwrite("request", (originalFn, ...options) => {
  originalFn(...options).then(response => {
    try {
      cy.writeFile('requests.log', `${JSON.stringify({ options,  response })}\n`, {flag: 'a+'});
      // 加不加cy.wrap都报错
      cy.wrap(response)
    } catch (e) {
        console.log(e);
    }
  })
});

出现错误:

Cannot read properties of undefined (reading 'status')

正确解决方案

核心问题是不能在cy.request的Promise回调中直接调用Cypress命令(如cy.writeFile),需改用Node.js原生文件操作,并确保返回响应数据。

const fs = require('fs');
const path = require('path');

Cypress.Commands.overwrite("request", (originalFn, ...options) => {
  return originalFn(...options).then(response => {
    // 用Node同步写入文件,避免Cypress命令队列冲突
    const logEntry = `${JSON.stringify({ options, response })}\n`;
    const logFilePath = path.join(Cypress.config('projectRoot'), 'requests.log');
    fs.appendFileSync(logFilePath, logEntry);
    
    // 必须返回原始响应,保证测试代码能正常使用响应数据
    return response;
  });
});

方案说明

  • 使用Node.js的fs.appendFileSync同步写入日志,不会触发Cypress的命令异步队列冲突问题
  • 通过Cypress.config('projectRoot')获取项目根目录,确保日志文件路径正确
  • 明确返回response,让后续测试代码能正常获取cy.request的响应结果,避免undefined错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 09:40:23