Cypress中Lighthouse单页测试失败后如何继续遍历所有页面
批量Lighthouse审计单页失败后继续执行解决方案
问题描述
批量对Excel中的多页面执行Lighthouse审计,已基于cypress-audit实现核心功能:读取Excel中的URL,依次访问页面并执行审计。但当前某页面审计失败时,会中断整个遍历流程,需要实现单页失败后仍继续完成所有页面的审计。
依赖版本
@cypress-audit/lighthouse: ^1.3.1cypress: ^10.9.0cypress-audit: ^1.1.0cypress-cucumber-preprocessor: ^4.3.1
解决方案
核心思路是临时捕获单个页面审计的失败错误,阻止错误传播中断整个流程,同时确保异步操作按顺序执行。
修改后的代码
calculationStoryService 文件
export function getLighthouseAuditForCalculationStory() { getAllCalculationStoriesFromExcel().then(stories => { // 使用Cypress.Promise.each按顺序处理每个页面,保证异步操作串行执行 return Cypress.Promise.each(stories, (story) => { // 临时覆盖fail事件,处理当前页面的审计失败 cy.on('fail', (error, runnable) => { console.log(`页面【${story.name}】审计失败:`, error.message); // 返回false阻止Cypress标记整个测试失败,继续执行后续页面 return false; }); cy.visit(story.url); cy.wait(Cypress.env("storyTableViewResultColumnCheckLoadingTimeout")); lighthouseAudit(story.name); // 恢复默认的fail事件处理,避免影响后续测试逻辑 cy.on('fail', null); }); }); } function lighthouseAudit(name) { let baseValueData = getBaseValueData(); let desktopConfig= getDesktopConfig(); const lighthouseMetrics = { performance: baseValueData.performance, accessibility: baseValueData.accessibility, seo: baseValueData.seo, pwa: baseValueData.pwa }; cy.lighthouse(lighthouseMetrics, desktopConfig); }
测试文件(无需修改)
import { Given, Then } from "cypress-cucumber-preprocessor/steps"; import { signIn } from "../../../support/services/commonServices"; import { getLighthouseAuditForCalculationStory } from "../../../support/services/calculationStoryService"; Given('Logged in', () => { signIn (Cypress.env('username'), Cypress.env('password')); }); Then('navigate to page and generate lighthouse audit', () => { getLighthouseAuditForCalculationStory(); });
关键说明
- 串行异步处理:用
Cypress.Promise.each替代原生forEach,确保每个页面的访问、等待、审计操作完成后,再执行下一个页面的流程,避免异步队列混乱。 - 局部错误捕获:在单个页面的处理逻辑中,临时覆盖
cy.on('fail')事件,捕获失败后打印日志并返回false,阻止Cypress中断整个测试。 - 恢复默认行为:处理完当前页面后,将
fail事件恢复为默认值,避免影响后续其他测试用例的错误处理逻辑。
内容的提问来源于stack exchange,提问作者yasith rangana
相关产品推荐
相关产品推荐

