如何为每条数据生成独立报告并汇总到 Excel?
解读
面试官抛出此题,核心想验证三件事:
- 你是否理解 Cypress 原生只产出 JSON/TXT/HTML 整体报告 的局限;
- 能否把“一条数据 = 一条测试用例”的模型落地,并做到 用例级粒度 的独立证据留存;
- 是否熟悉 Node 端二次加工 与 Excel 生态(xlsx、exceljs)在中国企业内网无公网环境下的离线方案。
回答时务必体现“合规可审计”“CI 落地”“性能不爆炸”这三点,否则会被追问“十万条数据怎么办”。
知识点
- Cypress 事件模型:
cy.task()是 Node 与浏览器之间的唯一官方通道,所有落盘必须走它。 - Mocha 运行时钩子:
beforeEach/afterEach在 每条数据驱动用例 开始与结束时触发,可拿到this.currentTest对象。 - 用例级 JSON 独立落盘:在
afterEach里把title、duration、err、screenshot、videoTimeOffset序列化成{uuid}.json,保证 后续可追踪。 - Node 端聚合:
cypress.config.js里注册on('after:run', async results),在该钩子内 同步读取所有 {uuid}.json,再调用exceljs按“序号、数据主键、结果、耗时、截图路径、错误信息”写表,最后输出report.xlsx到cypress/results。 - 中国内网 CI 场景:
- 禁用网络字体,避免 exceljs 拉 CDN;
- 使用
cnpm镜像安装exceljs@4.3.0; - 若涉密,把
report.xlsx自动转 受密码保护的 zip,密码走 KMS。
- 性能兜底:
- 截图走
cypress/screenshots/{uuid}.png,关闭trashAssetsBeforeRuns; - 超过 5000 条数据 时启用
stream模式写 Excel,防止内存溢出; - 视频只录失败用例,减少 IO。
- 截图走
答案
- 项目结构
cypress/
├─ fixtures/data.json // 数据池
├─ support/e2e.js
├─ plugins/excel-writer.js // Node 端 Excel 聚合
└─ results/ // 产出目录
- 数据驱动脚本
cypress/e2e/data-driven.cy.js
import data from '../fixtures/data.json';
describe('数据驱动独立报告', () => {
data.forEach((row, idx) => {
const uuid = `${Date.now()}-${idx}`;
it(`数据主键:${row.id}`, function () {
cy.wrap(row).as('row');
// 业务操作
cy.get('#input').type(row.keyword);
cy.contains('搜索').click();
cy.get('.result').should('contain', row.expect);
// 把 uuid 塞进环境,方便截图命名
Cypress.env('UUID', uuid);
});
afterEach(function () {
if (this.currentTest.state === 'failed') cy.screenshot(`${uuid}_fail`);
// 回写独立报告
cy.task('writeCaseJson', {
uuid,
title: this.currentTest.title,
state: this.currentTest.state,
duration: this.currentTest.duration,
error: this.currentTest.err?.message || '',
screenshot: this.currentTest.state === 'failed' ? `cypress/screenshots/${uuid}_fail.png` : ''
});
});
});
});
cypress/plugins/excel-writer.js(Node 端)
const ExcelJS = require('exceljs');
const fs = require('fs');
const path = require('path');
async function writeExcel(summaryArr) {
const book = new ExcelJS.Workbook();
const sheet = book.addWorksheet('汇总');
sheet.columns = [
{ header: '序号', key: 'idx', width: 8 },
{ header: '数据主键', key: 'id', width: 20 },
{ header: '结果', key: 'state', width: 12 },
{ header: '耗时(ms)', key: 'duration', width: 12 },
{ header: '截图路径', key: 'screenshot', width: 40 },
{ header: '错误信息', key: 'error', width: 60 }
];
summaryArr.forEach((r, i) => sheet.addRow({ ...r, idx: i + 1 }));
await book.xlsx.writeFile(path.resolve('cypress/results/report.xlsx'));
}
module.exports = { writeExcel };
cypress.config.js注册任务与聚合钩子
const { writeExcel } = require('./cypress/plugins/excel-writer');
const glob = require('glob');
module.exports = defineConfig({
e2e: {
setupNodeEvents(on, config) {
on('task', {
writeCaseJson(obj) {
require('fs').writeFileSync(
require('path').resolve(`cypress/results/${obj.uuid}.json`),
JSON.stringify(obj, null, 2)
);
return null;
}
});
on('after:run', async () => {
const files = glob.sync('cypress/results/*.json');
const rows = files.map(f => JSON.parse(require('fs').readFileSync(f, 'utf8')));
await writeExcel(rows);
console.log('✅ Excel 汇总已生成:cypress/results/report.xlsx');
});
}
}
});
- 运行与验证
npm run cypress:run -- --browser chrome
# 结束后自动得到
# cypress/results/
# ├─ {uuid}.json // 每条独立报告
# └─ report.xlsx // 中国领导最爱的 Excel
拓展思考
- 十万级数据 时,把
forEach换成cy.task('batchData')一次性灌入,再用cypress-grep动态生成 N 个 CI 分片,每片 500 条,最后把分片 Excel 用node-xlsx合并,防止内存炸掉。 - 合规审计:在
writeCaseJson里追加 Git commit hash、构建号、执行人邮箱,并写入 只读 MinIO 对象存储,满足金融客户 7 年可回溯 要求。 - 双向追溯:在 Excel 里插入
=HYPERLINK("file://"&截图路径),双击直接打开失败截图;同时把report.xlsx上传至 禅道/Jira 自定义字段,实现“需求-用例-缺陷”三单闭环。