Files
novalon-website/test-framework/shared/utils/performance/LighthouseRunner.ts
T
2026-03-06 12:08:30 +08:00

85 lines
2.6 KiB
TypeScript

import { Page } from '@playwright/test';
import { LighthouseResult } from '../../types';
export class LighthouseRunner {
constructor(private page: Page) {}
async runLighthouse(url: string): Promise<LighthouseResult> {
const results = await this.page.evaluate(async () => {
return new Promise((resolve) => {
if (!(window as any).lighthouse) {
resolve({
performance: 0,
accessibility: 0,
bestPractices: 0,
seo: 0,
pwa: 0
});
return;
}
(window as any).lighthouse(url, {
onlyCategories: ['performance', 'accessibility', 'best-practices', 'seo', 'pwa']
}).then((result: any) => {
resolve({
performance: Math.round(result.categories.performance.score * 100),
accessibility: Math.round(result.categories.accessibility.score * 100),
bestPractices: Math.round(result.categories['best-practices'].score * 100),
seo: Math.round(result.categories.seo.score * 100),
pwa: Math.round(result.categories.pwa.score * 100)
});
});
});
});
return results;
}
async runPerformanceAudit(): Promise<{
score: number;
metrics: {
firstContentfulPaint: number;
largestContentfulPaint: number;
cumulativeLayoutShift: number;
firstInputDelay: number;
speedIndex: number;
};
}> {
const results = await this.page.evaluate(async () => {
return new Promise((resolve) => {
if (!(window as any).lighthouse) {
resolve({
score: 0,
metrics: {
firstContentfulPaint: 0,
largestContentfulPaint: 0,
cumulativeLayoutShift: 0,
firstInputDelay: 0,
speedIndex: 0
}
});
return;
}
(window as any).lighthouse(location.href, {
onlyCategories: ['performance']
}).then((result: any) => {
const audits = result.audits;
resolve({
score: Math.round(result.categories.performance.score * 100),
metrics: {
firstContentfulPaint: audits['first-contentful-paint'].numericValue,
largestContentfulPaint: audits['largest-contentful-paint'].numericValue,
cumulativeLayoutShift: audits['cumulative-layout-shift'].numericValue,
firstInputDelay: audits['max-potential-fid'].numericValue,
speedIndex: audits['speed-index'].numericValue
}
});
});
});
});
return results;
}
}