如何将Cypress(配Cucumber-preprocessor)运行结果存入变量并传给API?
捕获Cypress+Cucumber测试运行结果的方法
下面两种方案可以帮你捕获测试执行结果并传递给API调用:
方案1:使用Cypress全局after:run钩子
Cypress 6.0及以上版本提供了after:run钩子,能直接获取完整的测试运行结果对象,无需解析控制台文本输出。
在cypress.config.js(旧版本用cypress/plugins/index.js)中添加以下代码:
module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { on('after:run', (results) => { // 提取需要的结果字段 const testSummary = { totalTests: results.totalTests, passed: results.passedTests, failed: results.failedTests, duration: results.totalDuration, // 单位为毫秒 specName: results.specs[0].name // 单spec场景下的文件名 }; // 直接调用API传递结果,示例用axios发送请求 const axios = require('axios'); axios.post('你的API接口地址', testSummary) .then(() => console.log('测试结果已提交')) .catch(err => console.error('结果提交失败:', err)); }); }, specPattern: 'cypress/e2e/**/*.feature', // Cucumber用例文件路径 // 其他Cypress配置项... }, });
这个钩子会在所有测试运行完成后触发,results对象包含了你需要的所有核心数据:总测试数、通过/失败数、总耗时、运行的用例文件等,完全不需要手动解析控制台输出。
方案2:命令行生成JSON报告并解析
如果需要通过外部脚本处理结果,可以让Cypress生成JSON格式的测试报告,再用Node脚本读取解析。
- 运行Cypress时指定JSON报告器:
npx cypress run --reporter json --reporter-options "output=test-results.json"
- 编写Node脚本(比如
process-results.js)读取并解析报告:
const fs = require('fs'); const axios = require('axios'); // 读取JSON结果文件 const rawResults = fs.readFileSync('test-results.json', 'utf8'); const results = JSON.parse(rawResults); // 提取需要的字段 const testSummary = { totalTests: results.tests.length, passed: results.tests.filter(test => test.state === 'passed').length, failed: results.tests.filter(test => test.state === 'failed').length, duration: results.totalDuration, specName: results.spec.name }; // 调用API传递结果 axios.post('你的API接口地址', testSummary) .then(() => console.log('结果提交成功')) .catch(err => console.error('提交失败:', err));
- 测试完成后执行脚本:
npx cypress run --reporter json --reporter-options "output=test-results.json" && node process-results.js
注意事项
- 旧版Cypress(低于6.0)可在
plugins/index.js中配置after:run钩子,语法逻辑一致。 - 对于Cucumber-preprocessor,
after:run钩子不受预处理器影响,依然能正常获取完整测试结果。
内容的提问来源于stack exchange,提问作者Sagarika
相关产品推荐
相关产品推荐

