Lighthouse Playwright - NPM Package
Lighthouse is a tool developed by Google that analyzes web apps and web pages, collecting modern performance metrics and insights on developer best practices.
Playwright is a Node library to automate Chromium, Firefox and WebKit with a single API. Playwright is built to enable cross-browser web automation that is ever-green, capable, reliable and fast.
The purpose of this package is to produce web audit report for several pages in connected mode and in an automated (programmatic) way.
Usage
Installation
Add the playwright-lighthouse
, playwright
& lighthouse
libraries to your project:
$ yarn add -D playwright-lighthouse playwright lighthouse
$ npm install --save-dev playwright-lighthouse playwright lighthouse
In your code
After completion of the Installation, you can use playwright-lighthouse
in your code to audit the current page.
In your test code you need to import playwright-lighthouse
and assign a port
for the lighthouse scan. You can choose any non-allocated port.
const { playAudit } = require('playwright-lighthouse');
const playwright = require('playwright');
describe('audit example', () => {
it('open browser', async () => {
const browser = await playwright['chromium'].launch({
args: ['--remote-debugging-port=9222'],
});
const page = await browser.newPage();
await page.goto('https://angular.io/');
await playAudit({
page: page,
port: 9222,
});
await browser.close();
});
});
Thresholds per tests
If you don't provide any threshold argument to the playAudit
command, the test will fail if at least one of your metrics is under 100
.
You can make assumptions on the different metrics by passing an object as argument to the playAudit
command:
const { playAudit } = require('playwright-lighthouse');
const playwright = require('playwright');
describe('audit example', () => {
it('open browser', async () => {
const browser = await playwright['chromium'].launch({
args: ['--remote-debugging-port=9222'],
});
const page = await browser.newPage();
await page.goto('https://angular.io/');
await playAudit({
page: page,
thresholds: {
performance: 50,
accessibility: 50,
'best-practices': 50,
seo: 50,
pwa: 50,
},
port: 9222,
});
await browser.close();
});
});
If the Lighthouse analysis returns scores that are under the one set in arguments, the test will fail.
You can also make assumptions only on certain metrics. For example, the following test will only verify the "correctness" of the performance
metric:
await playAudit({
page: page,
thresholds: {
performance: 85,
},
port: 9222,
});
This test will fail only when the performance
metric provided by Lighthouse will be under 85
.
Passing different Lighthouse config to playwright-lighthouse directly
You can also pass any argument directly to the Lighthouse module using the second and third options of the command:
const thresholdsConfig = {
};
const lighthouseOptions = {
};
const lighthouseConfig = {
};
await playAudit({
thresholds: thresholdsConfig,
opts: lighthouseOptions,
config: lighthouseConfig,
});
You can pass default lighthouse configs like so:
import lighthouseDesktopConfig from 'lighthouse/lighthouse-core/config/lr-desktop-config';
await playAudit({
thresholds: thresholdsConfig,
opts: lighthouseOptions,
config: lighthouseDesktopConfig,
});
Sometimes it's important to pass a parameter disableStorageReset as false. You can easily make it like this:
const opts = {
disableStorageReset: false,
};
await playAudit({
page,
port: 9222,
opts,
});
Running lighthouse on authenticated routes
Playwright by default does not share any context (eg auth state) between pages. Lighthouse will open a new page and thus any previous authentication steps are void. To persist auth state you need to use a persistent context:
const os = require('os');
const { playAudit } = require('playwright-lighthouse');
const { chromium } = require('playwright');
describe('audit example', () => {
it('open browser', async () => {
const context = await chromium.launchPersistentContext(os.tmpdir(), {
args: ['--remote-debugging-port=9222'],
});
const page = await context.newPage();
await page.goto('http://localhost:3000/');
await playAudit({
page: page,
port: 9222,
});
await context.close();
});
});
Usage with Playwright Test Runner
import { chromium } from 'playwright';
import type { Browser } from 'playwright';
import { playAudit } from 'playwright-lighthouse';
import { test as base } from '@playwright/test';
import getPort from 'get-port';
export const lighthouseTest = base.extend<
{},
{ port: number; browser: Browser }
>({
port: [
async ({}, use) => {
const port = await getPort();
await use(port);
},
{ scope: 'worker' },
],
browser: [
async ({ port }, use) => {
const browser = await chromium.launch({
args: [`--remote-debugging-port=${port}`],
});
await use(browser);
},
{ scope: 'worker' },
],
});
lighthouseTest.describe('Lighthouse', () => {
lighthouseTest('should pass lighthouse tests', async ({ page, port }) => {
await page.goto('http://example.com');
await page.waitForSelector('#some-element');
await playAudit({
page,
port,
});
});
});
Running lighthouse on authenticated routes with the test runner
import os from 'os';
import getPort from 'get-port';
import { BrowserContext, chromium, Page } from 'playwright';
import { test as base } from '@playwright/test';
import { playAudit } from 'playwright-lighthouse';
export const lighthouseTest = base.extend<
{
authenticatedPage: Page;
context: BrowserContext;
},
{
port: number;
}
>({
port: [
async ({}, use) => {
const port = await getPort();
await use(port);
},
{ scope: 'worker' },
],
context: [
async ({ port }, use) => {
const userDataDir = os.tmpdir();
const context = await chromium.launchPersistentContext(userDataDir, {
args: [`--remote-debugging-port=${port}`],
});
await use(context);
await context.close();
},
{ scope: 'test' },
],
authenticatedPage: [
async ({ context, page }, use) => {
await context.route('https://example.com/token', (route) => {
return route.fulfill({
status: 200,
body: JSON.stringify({
}),
headers: {
},
});
});
await page.goto('http://localhost:3000');
await insertAuthState(page);
await use(page);
},
{ scope: 'test' },
],
});
lighthouseTest.describe('Authenticated route', () => {
lighthouseTest(
'should pass lighthouse tests',
async ({ port, authenticatedPage: page }) => {
await page.goto('http://localhost:3000/my-profile');
await playAudit({
page,
port,
});
}
);
});
Running lighthouse on authenticated routes with globalSetup
In case you have a globalSetup
script in your test you might want to reuse saved state instead of running auth before every test.
Additionally, you may pass url
instead of page
to speedup execution and save resources.
import os from 'os'
import path from 'path'
import { chromium, test as base } from '@playwright/test'
import type { BrowserContext } from '@playwright/test'
import getPort from 'get-port'
export const lighthouseTest = base.extend<{ context: BrowserContext }, { port: number }>({
port: [
async ({}, use) => {
const port = await getPort()
await use(port)
},
{ scope: 'worker' },
],
context: [
async ({ port, launchOptions }, use) => {
const context = await chromium.launchPersistentContext(path.join(os.tmpdir(), 'pw', `${Math.random()}`.replace('.', '')), {
args: [...(launchOptions.args || []), `--remote-debugging-port=${port}`],
})
await context.addCookies(require('../../state-chrome.json').cookies)
await use(context)
await context.close()
},
{ scope: 'test' },
],
})
lighthouseTest.describe('Authenticated route after globalSetup', () => {
lighthouseTest(
'should pass lighthouse tests',
async ({ port }) => {
await playAudit({
url: 'http://localhost:3000/my-profile',
port,
});
}
);
});
Generating audit reports
playwright-lighthouse
library can produce Lighthouse CSV, HTML and JSON audit reports, that you can host in your CI server. These reports can be useful for ongoing audits and monitoring from build to build.
await playAudit({
reports: {
formats: {
json: true,
html: true,
csv: true,
},
name: `name-of-the-report`,
directory: `path/to/directory`,
},
});
Sample HTML report:
playAudit function also provides a promise that resolves with the Lighthouse result object containing the LHR (Lighthouse report in JSON format).
const lighthouseReport = await playAudit({
});
Tell me your issues
you can raise any issue here
Before you go
If it works for you , give a Star! :star:
- Copyright © 2020- Abhinaba Ghosh