如何覆盖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
相关产品推荐
相关产品推荐

