如何将Cypress TestRunner左侧命令日志保存为文本或JSON文件
可行实现方案
直接通过Cypress内置的日志监听事件捕获TestRunner左侧面板的原生日志,无需第三方插件,捕获的内容和左侧面板完全一致,可按需导出为JSON或纯文本格式。
实现步骤
1. 配置日志收集逻辑
在cypress/support/e2e.js(Cypress 10+版本,旧版对应cypress/support/index.js)中添加如下代码:
// 存储日志的全局数组 const testRunLogs = [] // 监听TestRunner日志添加事件,所有左侧面板展示的日志都会触发该事件 Cypress.on('log:added', (logInstance) => { // 过滤Cypress内部运行日志,只保留你需要的业务相关日志 if (logInstance.isInternal) return const formattedLog = { serialNumber: testRunLogs.length + 1, commandName: logInstance.displayName || logInstance.name, message: logInstance.message, runStatus: logInstance.state, // 针对XHR请求额外挂载全量请求响应信息 xhrDetail: logInstance.xhr ? { method: logInstance.xhr.method, url: logInstance.xhr.url, statusCode: logInstance.xhr.status, requestHeaders: logInstance.xhr.request?.headers, requestBody: logInstance.xhr.request?.body, responseHeaders: logInstance.xhr.response?.headers, responseBody: logInstance.xhr.response?.body } : null } testRunLogs.push(formattedLog) }) // 单条测试用例执行完成后写入日志文件 afterEach(() => { // 生成纯文本格式日志,符合你给出的示例格式 const plainTextContent = testRunLogs.map(log => { if (log.xhrDetail) { return `${log.serialNumber} (xhr) ${log.xhrDetail.method} ${log.xhrDetail.statusCode} ${log.xhrDetail.url}` } return `${log.serialNumber} ${log.commandName} ${log.message}` }).join('\n') // 以测试用例标题命名日志文件,避免覆盖 const logFileName = `${Cypress.currentTest.title.replace(/\W+/g, '_')}_run_log` // 导出纯文本格式 cy.writeFile(`cypress/logs/${logFileName}.txt`, plainTextContent) // 同时导出JSON格式方便后续自动化对比 cy.writeFile(`cypress/logs/${logFileName}.json`, testRunLogs) // 清空日志数组,避免和下一条用例日志混淆 testRunLogs.length = 0 })
2. 配置Cypress运行参数
修改cypress.config.js开启完整XHR内容捕获,并提前创建日志存储目录:
const { defineConfig } = require('cypress') const fs = require('fs') const path = require('path') module.exports = defineConfig({ e2e: { // 开启完整XHR请求响应内容捕获,默认只会记录基础信息 experimentalFetchPolyfill: true, setupNodeEvents(on, config) { // 自动创建日志存储目录,避免首次运行写入报错 const logDirPath = path.join(__dirname, 'cypress/logs') if (!fs.existsSync(logDirPath)) { fs.mkdirSync(logDirPath, { recursive: true }) } return config } } })
补充优化方案
如果仅需要收集XHR相关日志用于特征匹配,可以单独监听XHR专属事件,过滤掉无关的命令日志:
// 仅在support文件中添加这段即可,不需要监听通用log:added事件 const xhrLogs = [] Cypress.on('xhr:response', (xhr) => { xhrLogs.push({ method: xhr.method, url: xhr.url, status: xhr.status, reqHeaders: xhr.request.headers, reqBody: xhr.request.body, resBody: xhr.response.body }) }) afterEach(() => { cy.writeFile('cypress/logs/xhr_records.json', xhrLogs) xhrLogs.length = 0 })
所有日志会自动存储在项目的cypress/logs目录下,无头CI模式运行同样生效,你可以直接对比多次运行导出的JSON日志,筛选出目标XHR的固定特征字段。
内容的提问来源于stack exchange,提问作者CrashNeb
相关产品推荐
相关产品推荐

