如何对受保护URL执行Lighthouse测试并获取准确评分?
解决Cypress中Lighthouse测试的性能评分偏差与受保护页面访问问题
一、修复cypress-audit的性能评分偏差问题
cypress-audit性能分远低于DevTools插件,核心原因是Cypress运行环境会引入额外脚本注入、等待逻辑,且默认配置未匹配真实用户环境。可通过以下配置调整对齐DevTools测试结果:
自定义Lighthouse桌面配置,模拟真实环境
在cypress.config.js中修改配置,禁用Cypress干扰项并匹配DevTools的网络/设备设置:const { lighthouse, prepareAudit } = require("@cypress-audit/lighthouse"); module.exports = defineConfig({ e2e: { setupNodeEvents(on, config) { on("before:browser:launch", (browser = {}, launchOptions) => { prepareAudit(launchOptions); // 禁用Cypress自带的网络服务,减少性能干扰 launchOptions.args.push("--disable-features=NetworkService"); return launchOptions; }); on("task", { lighthouse: lighthouse((report) => console.log(report)), }); }, }, });在测试用例中使用贴合DevTools的桌面配置:
cy.lighthouse( { performance: 0, accessibility: 90 }, // 自定义评分阈值 { formFactor: "desktop", screenEmulation: { mobile: false, width: 1350, height: 940, deviceScaleFactor: 1, disabled: false, }, throttling: { rttMs: 40, throughputKbps: 10 * 1024, cpuSlowdownMultiplier: 1, // 关闭CPU节流,和DevTools默认一致 }, disableStorageReset: true, // 保留缓存,模拟真实用户二次访问 } );确保测试时机正确
执行Lighthouse前,等待页面核心资源完全加载,避免Cypress异步等待导致测试过早触发:cy.visit("/target-page"); cy.get("main.content").should("be.visible"); // 等待核心内容渲染完成 cy.window().should("have.property", "pageLoaded", true); // 监听自定义页面加载完成标识 cy.lighthouse(...);
二、实现受保护页面的Lighthouse测试(cy.exec方案优化)
直接用cy.exec调用全局Lighthouse时,Chrome实例无登录会话,可通过导出Cypress当前会话Cookie并传递给Lighthouse解决:
导出登录Cookie
登录成功后,获取当前域名下的所有Cookie,格式化为Lighthouse可识别的字符串:cy.getCookies().then((cookies) => { const cookieStr = cookies.map((c) => `${c.name}=${c.value}`).join("; "); Cypress.env("AUTH_COOKIES", cookieStr); });传递Cookie执行Lighthouse
通过--extra-headers参数将Cookie传入Lighthouse,确保Chrome实例携带登录会话:cy.exec( `lighthouse ${Cypress.config("baseUrl")}/protected-page --extra-headers '{"Cookie": "${Cypress.env("AUTH_COOKIES")}"}' --form-factor desktop --quiet` );若Cookie内容过长,可写入配置文件避免命令行参数异常:
// 生成headers配置文件 cy.writeFile("lighthouse-headers.json", { Cookie: Cypress.env("AUTH_COOKIES"), }); // 执行Lighthouse cy.exec( `lighthouse ${Cypress.config("baseUrl")}/protected-page --extra-headers ./lighthouse-headers.json --form-factor desktop --quiet` );
三、备选方案:使用cypress-lighthouse插件
若cypress-audit仍存在适配问题,可尝试维护更活跃的cypress-lighthouse插件,它默认配置更贴近DevTools,且天然支持Cypress会话保持:
const { lighthouse } = require("cypress-lighthouse"); module.exports = defineConfig({ e2e: { setupNodeEvents(on) { on("task", { lighthouse }); }, }, });
测试用例中直接调用即可:
cy.visit("/protected-page"); cy.lighthouse({ performance: 20, accessibility: 90 });
内容的提问来源于stack exchange,提问作者yasith rangana
相关产品推荐
相关产品推荐

