Cypress-Audit生成Lighthouse报告时文件被覆盖的问题求助
解决Cypress-Audit Lighthouse报告被覆盖的问题
要避免多次调用cy.lighthouse时报告被覆盖,核心思路是为每个页面生成唯一的报告文件名,以下是两种可行的实现方式:
方式1:基于页面URL自动生成唯一文件名
利用Lighthouse报告中自带的页面URL信息,提取关键部分结合时间戳生成不重复的文件名,确保每个页面的报告独立保存:
lighthouse: lighthouse((lighthouseReport) => { console.log("---- Writing lighthouse report to disk ----"); // 从报告中获取当前测试页面的URL const pageUrl = new URL(lighthouseReport.lhr.requestedUrl); // 处理URL为合法文件名(替换特殊字符) const pageIdentifier = pageUrl.hostname + pageUrl.pathname.replace(/[/:]/g, "_"); // 添加时间戳确保同一页面多次测试也不会覆盖 const timestamp = new Date().toISOString().replace(/[:.]/g, "-"); const uniqueFileName = `lighthouse_${pageIdentifier}_${timestamp}.html`; fs.writeFile(uniqueFileName, lighthouseReport.report, (error: any) => { error ? console.error(error) : console.log(`Report saved successfully: ${uniqueFileName}`); }); }),
方式2:在测试用例中手动指定文件名
如果是遍历固定页面集合,可以直接在测试逻辑中为每个页面指定自定义名称,更直观可控:
// 定义需要测试的页面列表 const testPages = [ { path: "/", name: "homepage" }, { path: "/about-us", name: "about_page" }, { path: "/products", name: "products_list" } ]; // 遍历页面执行Lighthouse测试 testPages.forEach(page => { it(`Generate Lighthouse report for ${page.name}`, () => { cy.visit(page.path); cy.lighthouse({}, (lighthouseReport) => { const fileName = `lighthouse_${page.name}.html`; fs.writeFile(fileName, lighthouseReport.report, (error) => { error ? console.error(`Failed to save report: ${error}`) : console.log(`Saved report: ${fileName}`); }); }); }); });
关键说明
- 原代码问题:所有报告都写入同一个
lighthouse.html文件,后执行的测试会覆盖之前的报告。 - 优化核心:通过页面标识(URL/自定义名称)+ 时间戳组合生成唯一文件名,确保每个报告文件不重复。
- 路径可选:如果需要统一存放报告,可以指定具体目录,比如
./cypress/reports/${uniqueFileName},注意提前确保目录存在。
内容的提问来源于stack exchange,提问作者itsBlooDy
相关产品推荐
相关产品推荐

