Lighthouse 服务
一个 WebdriverIO 服务,允许您使用 Google Lighthouse 运行可访问性和性能测试。
**注意:**此服务目前仅支持在 Google Chrome 或 Chromium 上运行的测试!鉴于大多数云供应商不开放对 Chrome DevTools 协议的访问,这个服务通常只有在本地运行测试或通过 Selenium Grid v4 或更高版本时才能使用。
安装
最简单的方法是将 @wdio/lighthouse-service 作为开发依赖保留在您的 package.json 中,通过:
npm install @wdio/lighthouse-service --save-dev
关于如何安装 WebdriverIO 的说明可以在这里找到。
配置
要使用该服务,您只需要在 wdio.conf.js 的服务列表中添加该服务,如:
// wdio.conf.js
export const config = {
// ...
services: ['lighthouse'],
// ...
};
使用
@wdio/lighthouse-service 允许您通过 WebdriverIO 运行 Google Lighthouse 可访问性和性能测试。
性能测试
Lighthouse 服务允许您从每次页面加载或由点击引起的页面转换中捕获性能数据。要启用它,请调用 browser.enablePerformanceAudits(<options>)。在完成捕获所有必要的性能数据后,禁用它以恢复节流设置,例如:
import assert from 'node:assert'
describe('JSON.org page', () => {
before(async () => {
await browser.enablePerformanceAudits()
})
it('should load within performance budget', async () => {
/**
* this page load will take a bit longer as the DevTools service will
* capture all metrics in the background
*/
await browser.url('http://json.org')
let metrics = await browser.getMetrics()
assert.ok(metrics.speedIndex < 1500) // check that speedIndex is below 1.5ms
let score = await browser.getPerformanceScore() // get Lighthouse Performance score
assert.ok(score >= .99) // Lighthouse Performance score is at 99% or higher
$('=Esperanto').click()
metrics = await browser.getMetrics()
assert.ok(metrics.speedIndex < 1500)
score = await browser.getPerformanceScore()
assert.ok(score >= .99)
})
after(async () => {
await browser.disablePerformanceAudits()
})
})
以下命令及其结果可用:
getMetrics
获取最常用的性能指标,例如:
console.log(await browser.getMetrics())
/**
* { timeToFirstByte: 566,
* serverResponseTime: 566,
* domContentLoaded: 3397,
* firstVisualChange: 2610,
* firstPaint: 2822,
* firstContentfulPaint: 2822,
* firstMeaningfulPaint: 2822,
* largestContentfulPaint: 2822,
* lastVisualChange: 15572,
* interactive: 6135,
* load: 8429,
* speedIndex: 3259,
* totalBlockingTime: 31,
* maxPotentialFID: 161,
* cumulativeLayoutShift: 2822 }
*/
getDiagnostics
获取有关页面加载的一些有用诊断信息。
console.log(await browser.getDiagnostics())
/**
* { numRequests: 8,
* numScripts: 0,
* numStylesheets: 0,
* numFonts: 0,
* numTasks: 237,
* numTasksOver10ms: 5,
* numTasksOver25ms: 2,
* numTasksOver50ms: 2,
* numTasksOver100ms: 0,
* numTasksOver500ms: 0,
* rtt: 147.20600000000002,
* throughput: 47729.68474448835,
* maxRtt: 176.085,
* maxServerLatency: 1016.813,
* totalByteWeight: 62929,
* totalTaskTime: 254.07899999999978,
* mainDocumentTransferSize: 8023 }
*/
getMainThreadWorkBreakdown
返回包含所有主线程任务及其总持续时间的列表。
console.log(await browser.getMainThreadWorkBreakdown())
/**
* [ { group: 'styleLayout', duration: 130.59099999999998 },
* { group: 'other', duration: 44.819 },
* { group: 'paintCompositeRender', duration: 13.732000000000005 },
* { group: 'parseHTML', duration: 3.9080000000000004 },
* { group: 'scriptEvaluation', duration: 2.437999999999999 },
* { group: 'scriptParseCompile', duration: 0.20800000000000002 } ]
*/