使用Cypress与Lighthouse生成HTML报告时遇错误求助
解决Cypress + Lighthouse生成HTML报告时的"No browser artifacts are either provided or requested"错误
问题描述
已完成cypress-audit的Lighthouse插件配置,未指定output参数时可在控制台查看Lighthouse报告;但设置output: "html"时,抛出错误:
CypressError cy.task('lighthouse') failed with the following error:
No browser artifacts are either provided or requested
测试代码如下:
describe('Generate HTML report', () => { it('first test case', () => { cy.visit('http://localhost:3000/'); const thresholds = { "accessibility": 50, "best-practices": 50, "seo": 50, "pwa": 20, }; const LHOptions = { formFactor: 'desktop', screenEmulation: { disabled: true }, }; const LHConfig = { output: "html", // 不指定时会生成json报告 }; cy.lighthouse(thresholds, LHOptions, LHConfig); }) })
解决方法
Lighthouse生成HTML报告需要收集浏览器运行时的artifacts(如网络请求、页面数据等),默认配置未开启该收集,导致报错。按以下步骤调整:
1. 修正Lighthouse配置结构
将output参数放到settings节点下,同时开启artifacts收集,并指定报告输出路径:
const LHConfig = { settings: { output: ["html"], // 部分版本需用数组格式指定输出类型 artifacts: true // 强制收集浏览器artifacts }, outputPath: "./cypress/reports/lighthouse-report.html" // 自定义报告保存路径 };
2. 确认Cypress插件配置正确
检查你的Cypress配置文件(如cypress.config.js),确保lighthouse任务和prepareAudit钩子正确注册,这是收集artifacts的必要前提:
const { defineConfig } = require("cypress"); const { lighthouse, prepareAudit } = require("@cypress-audit/lighthouse"); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { // 为Lighthouse准备浏览器启动参数 on("before:browser:launch", (browser, launchOptions) => { prepareAudit(launchOptions); return launchOptions; }); // 注册lighthouse任务 on("task", { lighthouse: lighthouse((report) => { console.log("Lighthouse报告生成完成"); // 可选:在这里自定义报告处理逻辑 }) }); }, }, });
3. 验证依赖完整性
确保已安装所有必要依赖,若缺失可重新安装:
npm install @cypress-audit/lighthouse lighthouse --save-dev
执行测试后,HTML报告将生成到你指定的outputPath路径下。
内容的提问来源于stack exchange,提问作者PriyaU
相关产品推荐
相关产品推荐

