### Install playwright-lighthouse Library Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md This command installs the `playwright-lighthouse` library using npm. This is a prerequisite for using the library's features for running Lighthouse audits within Playwright tests. ```bash npm install playwright-lighthouse ``` -------------------------------- ### Install Playwright Lighthouse, Playwright, and Lighthouse Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md Installs the necessary libraries for using Playwright with Lighthouse. This includes the main package, Playwright for browser automation, and Lighthouse for auditing. ```shell yarn add -D playwright-lighthouse playwright lighthouse # or npm install --save-dev playwright-lighthouse playwright lighthouse ``` -------------------------------- ### Clean Up Temporary Directories on Playwright Teardown (TypeScript) Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md This TypeScript function provides a global setup hook for Playwright tests. It defines a function that, when executed, cleans up temporary directories created by Playwright, such as those used for persistent contexts. This helps in maintaining a clean environment between test runs. ```typescript import rimraf from 'rimraf'; import os from 'os'; import path from 'path'; function globalSetup() { return () => { const tmpDirPath = path.join(os.tmpdir(), 'pw'); rimraf(tmpDirPath, console.log); }; } export default globalSetup; ``` -------------------------------- ### Playwright Test Runner Integration for Lighthouse Audits Source: https://context7.com/abhinaba-ghosh/playwright-lighthouse/llms.txt Integrate Lighthouse audits into Playwright's native test runner with proper parallel test support. Each worker gets a unique debugging port to avoid conflicts when running tests concurrently. This example uses playwright and playwright-lighthouse. ```javascript import { chromium } from 'playwright'; import { playAudit } from 'playwright-lighthouse'; import { test as base } from '@playwright/test'; const getPort = () => { return Math.floor(Math.random() * 10000) + 10000; }; export const lighthouseTest = base.extend({ port: [ async ({}, use) => { const port = getPort(); await use(port); }, { scope: 'worker' }, ], browser: [ async ({ port }, use) => { const browser = await chromium.launch({ args: [`--remote-debugging-port=${port}`], }); await use(browser); await browser.close(); }, { scope: 'worker' }, ], }); lighthouseTest.describe('Lighthouse Audits', () => { lighthouseTest('homepage performance', async ({ page, port }) => { await page.goto('http://localhost:3000'); await page.waitForSelector('#main-content'); await playAudit({ page, port, thresholds: { performance: 70, accessibility: 90, }, }); }); }); ``` -------------------------------- ### Error Handling and Logging for Lighthouse Audits Source: https://context7.com/abhinaba-ghosh/playwright-lighthouse/llms.txt Control error behavior and logging output with the `ignoreError` and `disableLogs` options. When `ignoreError` is true, threshold failures don't throw errors but are included in the returned result object. This example uses playwright and playwright-lighthouse. ```javascript import { playAudit } from 'playwright-lighthouse'; import playwright from 'playwright'; const browser = await playwright.chromium.launch({ args: ['--remote-debugging-port=9222'], }); const page = await browser.newPage(); await page.goto('https://example.com'); const result = await playAudit({ url: 'https://example.com', port: 9222, thresholds: { performance: 100, accessibility: 100, }, ignoreError: true, disableLogs: true, }); if (result.comparisonError) { console.log('Warning: Performance thresholds not met'); console.log(result.comparisonError); } console.log('Actual scores:', { performance: result.lhr.categories.performance.score * 100, accessibility: result.lhr.categories.accessibility.score * 100, }); await browser.close(); ``` -------------------------------- ### Run Lighthouse on Authenticated Routes with Playwright GlobalSetup Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md This snippet demonstrates how to configure Playwright's globalSetup to reuse saved state for authenticated routes when running Lighthouse audits. It utilizes `chromium.launchPersistentContext` and `addCookies` to apply saved authentication state. The `playAudit` function can accept a URL directly for efficiency. ```typescript 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'; // version ^5.1.1 due to issues with imports in playwright 1.20.1 export const lighthouseTest = base.extend< { context: BrowserContext }, { port: number } >({ port: [ async ({}, use) => { // Assign a unique port for each playwright worker to support parallel tests const port = await getPort(); await use(port); }, { scope: 'worker' }, ], context: [ async ({ port, launchOptions }, use) => { const userDataDir = path.join(os.tmpdir(), 'pw', String(Math.random())); const context = await chromium.launchPersistentContext(userDataDir, { args: [ ...(launchOptions.args || []), `--remote-debugging-port=${port}`, ], }); // apply state previously saved in the the `globalSetup` 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 }) => { // it's possible to pass url directly instead of a page // to avoid opening a page an extra time and keeping it opened await playAudit({ url: 'http://localhost:3000/my-profile', port, }); }); }); ``` -------------------------------- ### Automated Web Performance Testing with Playwright and Lighthouse Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md This JavaScript code snippet utilizes Playwright to launch a browser, navigate to a website, perform a search, and then runs a Lighthouse audit. It configures capabilities for LambdaTest, sets performance thresholds, and reports test status back to the LambdaTest dashboard. Dependencies include 'playwright' and 'playwright-lighthouse'. ```javascript import { chromium } from 'playwright'; import { playAudit } from 'playwright-lighthouse'; (async () => { let browser, page; try { const capabilities = { browserName: 'Chrome', // Browsers allowed: `Chrome`, `MicrosoftEdge` and `pw-chromium` browserVersion: 'latest', 'LT:Options': { platform: 'Windows 11', build: 'Web Performance testing', name: 'Lighthouse test', user: process.env.LT_USERNAME, accessKey: process.env.LT_ACCESS_KEY, network: true, video: true, console: true, }, }; browser = await chromium.connect({ wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`, }); page = await browser.newPage(); await page.goto('https://duckduckgo.com'); let element = await page.locator('[name="q"]'); await element.click(); await element.type('Playwright'); await element.press('Enter'); try { await playAudit({ url: 'https://duckduckgo.com', page: page, thresholds: { performance: 50, accessibility: 50, 'best-practices': 50, seo: 50, pwa: 10, }, reports: { formats: { json: true, html: true, csv: true, }, }, }); await page.evaluate( (_) => {}, `lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status: 'passed', remark: 'Web performance metrics are are above the thresholds.' } })}` ); } catch (e) { await page.evaluate( (_) => {}, `lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status: 'failed', remark: e.stack } })}` ); console.error(e); } } catch (e) { await page.evaluate( (_) => {}, `lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status: 'failed', remark: e.stack } })}` ); } finally { await page.close(); await browser.close(); } })(); ``` -------------------------------- ### Custom Lighthouse Configuration with Playwright Source: https://context7.com/abhinaba-ghosh/playwright-lighthouse/llms.txt Pass custom Lighthouse options and configuration to fine-tune the audit process. This allows control over device emulation, throttling, audits to run, and other Lighthouse-specific settings. It uses playwright and lighthouse libraries. ```javascript import { playAudit } from 'playwright-lighthouse'; import playwright from 'playwright'; import desktopConfig from 'lighthouse/core/config/lr-desktop-config.js'; const browser = await playwright.chromium.launch({ args: ['--remote-debugging-port=9222'], }); const page = await browser.newPage(); await page.goto('https://example.com'); const lighthouseOptions = { disableStorageReset: false, screenEmulation: { mobile: false, width: 1920, height: 1080, }, }; const lighthouseConfig = { extends: 'lighthouse:default', settings: { onlyCategories: ['performance', 'accessibility'], }, }; await playAudit({ page: page, port: 9222, opts: lighthouseOptions, config: desktopConfig, thresholds: { performance: 70, }, }); await browser.close(); ``` -------------------------------- ### Basic Page Audit with Playwright Lighthouse Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md Performs a basic Lighthouse audit on a specified web page using Playwright. It launches a browser, navigates to a URL, and then runs the audit. The browser is closed upon completion. ```javascript import { playAudit } from 'playwright-lighthouse'; import playwright from '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(); }); }); ``` -------------------------------- ### Configure LambdaTest Environment Variable for Lighthouse Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md This command sets the `LIGHTHOUSE_LAMBDATEST` environment variable to 'true'. This configuration is necessary to enable the execution of Lighthouse reports on the LambdaTest platform when running Playwright tests. ```bash export LIGHTHOUSE_LAMBDATEST='true' ``` -------------------------------- ### Run Lighthouse on Authenticated Routes with Persistent Context (JavaScript) Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md This snippet demonstrates how to run Lighthouse audits on pages that require authentication. It utilizes Playwright's `launchPersistentContext` to maintain authentication state (cookies, localStorage) across sessions, ensuring Lighthouse audits run with the correct user session. ```javascript import os from 'os'; import { playAudit } from 'playwright-lighthouse'; import { chromium } from 'playwright'; describe('audit example', () => { it('open browser', async () => { const userDataDir = path.join(os.tmpdir(), 'pw', String(Math.random())); const context = await chromium.launchPersistentContext(userDataDir, { args: ['--remote-debugging-port=9222'], }); const page = await context.newPage(); await page.goto('http://localhost:3000/'); // Perform login steps here which will save to cookie or localStorage // When lighthouse opens a new page the storage will be persisted meaning the new page will have the same user session await playAudit({ page: page, port: 9222, }); await context.close(); }); }); ``` -------------------------------- ### Passing Custom Lighthouse Config with Playwright Lighthouse Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md Allows passing custom Lighthouse options and configurations directly to the `playAudit` command. This enables fine-tuning of the audit process beyond standard thresholds, including disabling storage reset. ```javascript const thresholdsConfig = { /* ... */ }; const lighthouseOptions = { /* ... your lighthouse options */ }; const lighthouseConfig = { /* ... your lighthouse configs */ }; await playAudit({ thresholds: thresholdsConfig, opts: lighthouseOptions, config: lighthouseConfig, /* ... other configurations */ }); ``` ```javascript import lighthouseDesktopConfig from 'lighthouse/lighthouse-core/config/lr-desktop-config'; await playAudit({ thresholds: thresholdsConfig, opts: lighthouseOptions, config: lighthouseDesktopConfig, /* ... other configurations */ }); ``` ```javascript const opts = { disableStorageReset: false, }; await playAudit({ page, port: 9222, opts, }); ``` -------------------------------- ### Generate Lighthouse Audit Reports (JSON, HTML, CSV) Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md This code snippet shows how to configure the `playwright-lighthouse` library to generate audit reports in JSON, HTML, and CSV formats. You can specify the desired formats, the report name, and the output directory. The `playAudit` function returns a promise that resolves with the Lighthouse result object. ```javascript await playAudit({ /* ... other configurations */ reports: { formats: { json: true, //defaults to false html: true, //defaults to false csv: true, //defaults to false }, name: `name-of-the-report`, //defaults to `lighthouse-${new Date().getTime()}` directory: `path/to/directory`, //defaults to `${process.cwd()}/lighthouse` }, }); ``` ```javascript const lighthouseReport = await playAudit({ /* ... configurations */ }); // lightHouse report contains the report results ``` -------------------------------- ### Page Audit with Custom Thresholds using Playwright Lighthouse Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md Conducts a Lighthouse audit with custom thresholds for performance metrics. If any metric falls below the specified values, the test will fail. This allows for stricter or more specific performance requirements. ```javascript import { playAudit } from 'playwright-lighthouse'; import playwright from '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(); }); }); ``` -------------------------------- ### Execute Lighthouse Audit with LambdaTest Integration using Playwright Source: https://context7.com/abhinaba-ghosh/playwright-lighthouse/llms.txt This JavaScript code snippet demonstrates how to perform a Lighthouse audit using Playwright and integrate it with LambdaTest for cloud-based testing. It requires setting environment variables for LambdaTest credentials and configuring browser capabilities. The `playAudit` function is used to run the audit, with results reported and test status updated on LambdaTest. ```javascript import { chromium } from 'playwright'; import { playAudit } from 'playwright-lighthouse'; // Set environment variable: export LIGHTHOUSE_LAMBDATEST='true' const capabilities = { browserName: 'Chrome', browserVersion: 'latest', 'LT:Options': { platform: 'Windows 11', build: 'Performance Testing', name: 'Lighthouse Audit', user: process.env.LT_USERNAME, accessKey: process.env.LT_ACCESS_KEY, network: true, video: true, }, }; const browser = await chromium.connect({ wsEndpoint: `wss://cdp.lambdatest.com/playwright?capabilities=${encodeURIComponent(JSON.stringify(capabilities))}`, }); const page = await browser.newPage(); await page.goto('https://example.com'); try { await playAudit({ url: 'https://example.com', page: page, thresholds: { performance: 50, accessibility: 70, }, reports: { formats: { html: true, json: true, }, }, }); await page.evaluate((_) => {}, `lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status: 'passed', remark: 'Performance metrics passed' } })}` ); } catch (error) { await page.evaluate((_) => {}, `lambdatest_action: ${JSON.stringify({ action: 'setTestStatus', arguments: { status: 'failed', remark: error.message } })}` ); } await page.close(); await browser.close(); ``` -------------------------------- ### Configure Custom Performance Thresholds for Lighthouse Audits Source: https://context7.com/abhinaba-ghosh/playwright-lighthouse/llms.txt Sets specific performance thresholds for Lighthouse metric categories (performance, accessibility, best-practices, seo, pwa). The audit fails if any category's score falls below the defined threshold. Scores range from 0 to 100. ```javascript import { playAudit } from 'playwright-lighthouse'; import playwright from 'playwright'; const browser = await playwright.chromium.launch({ args: ['--remote-debugging-port=9222'], }); const page = await browser.newPage(); await page.goto('https://angular.io/'); try { await playAudit({ page: page, thresholds: { performance: 50, accessibility: 80, 'best-practices': 70, seo: 60, pwa: 30, }, port: 9222, }); console.log('All thresholds passed!'); } catch (error) { console.error('Performance audit failed:', error.message); } await browser.close(); ``` -------------------------------- ### Perform Basic Lighthouse Performance Audit with Playwright Source: https://context7.com/abhinaba-ghosh/playwright-lighthouse/llms.txt Executes a standard Lighthouse performance audit on a given Playwright page or URL. It requires the remote debugging port and either a Playwright page object or a URL. The function returns a promise that resolves with the complete Lighthouse report data. ```javascript import { playAudit } from 'playwright-lighthouse'; import playwright from 'playwright'; const browser = await playwright.chromium.launch({ args: ['--remote-debugging-port=9222'], }); const page = await browser.newPage(); await page.goto('https://example.com'); await playAudit({ page: page, port: 9222, }); await browser.close(); ``` -------------------------------- ### Generate Lighthouse Audit Reports in Multiple Formats Source: https://context7.com/abhinaba-ghosh/playwright-lighthouse/llms.txt Generates Lighthouse audit reports in JSON, HTML, and CSV formats, saving them to a specified directory with a custom name. This is useful for archiving performance metrics and tracking them over time, especially within CI/CD pipelines. ```javascript import { playAudit } from 'playwright-lighthouse'; import playwright from 'playwright'; const browser = await playwright.chromium.launch({ args: ['--remote-debugging-port=9222'], }); const page = await browser.newPage(); await page.goto('https://example.com'); const lighthouseReport = await playAudit({ page: page, port: 9222, thresholds: { performance: 50, }, reports: { formats: { json: true, html: true, csv: true, }, name: 'example-com-audit', directory: './lighthouse-reports', }, }); console.log('Performance score:', lighthouseReport.lhr.categories.performance.score * 100); await browser.close(); ``` -------------------------------- ### Run Lighthouse on Authenticated Routes with Test Runner (TypeScript) Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md This advanced snippet extends the Playwright Test Runner for authenticated routes. It sets up a persistent browser context and an authenticated page, allowing Lighthouse audits to be performed on pages requiring login. It also manages unique ports for parallel test execution. ```typescript 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; } >({ // We need to assign a unique port for each lighthouse test to allow // lighthouse tests to run in parallel port: [ async ({}, use) => { const port = await getPort(); await use(port); }, { scope: 'worker' }, ], // As lighthouse opens a new page, and as playwright does not by default allow // shared contexts, we need to explicitly create a persistent context to // allow lighthouse to run behind authenticated routes. context: [ async ({ port }, use) => { const userDataDir = path.join(os.tmpdir(), 'pw', String(Math.random())); const context = await chromium.launchPersistentContext(userDataDir, { args: [`--remote-debugging-port=${port}`], }); await use(context); await context.close(); }, { scope: 'test' }, ], authenticatedPage: [ async ({ context, page }, use) => { // Mock any requests on the entire context await context.route('https://example.com/token', (route) => { return route.fulfill({ status: 200, body: JSON.stringify({ // ... }), headers: { // ... }, }); }); await page.goto('http://localhost:3000'); // Setup your auth state by inserting cookies or localStorage values 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, }); } ); }); ``` -------------------------------- ### Audit Authenticated Pages Using Persistent Playwright Context Source: https://context7.com/abhinaba-ghosh/playwright-lighthouse/llms.txt Audits web pages that require authentication by leveraging Playwright's persistent contexts. This ensures that authentication state (cookies, localStorage) is maintained when Lighthouse opens a new page for the audit. ```javascript import os from 'os'; import path from 'path'; import { playAudit } from 'playwright-lighthouse'; import { chromium } from 'playwright'; const userDataDir = path.join(os.tmpdir(), 'pw', String(Math.random())); const context = await chromium.launchPersistentContext(userDataDir, { args: ['--remote-debugging-port=9222'], }); const page = await context.newPage(); await page.goto('http://localhost:3000/login'); // Perform login await page.fill('#username', 'testuser'); await page.fill('#password', 'password123'); await page.click('#submit'); await page.waitForNavigation(); // Audit authenticated page await playAudit({ page: page, port: 9222, thresholds: { performance: 60, accessibility: 80, }, }); await context.close(); ``` -------------------------------- ### URL-based Lighthouse Audit with Playwright Source: https://context7.com/abhinaba-ghosh/playwright-lighthouse/llms.txt Execute Lighthouse audits using a URL directly instead of a page object, which can improve performance by avoiding unnecessary page creation. This is particularly useful in Playwright Test Runner contexts with persistent authentication. It requires playwright and playwright-lighthouse. ```javascript import { playAudit } from 'playwright-lighthouse'; import { chromium } from 'playwright'; import path from 'path'; import os from 'os'; const userDataDir = path.join(os.tmpdir(), 'pw', String(Math.random())); const context = await chromium.launchPersistentContext(userDataDir, { args: ['--remote-debugging-port=9222'], }); // Set up authentication state const page = await context.newPage(); await page.goto('http://localhost:3000/login'); // ... perform login ... await page.close(); // Audit without keeping a page open await playAudit({ url: 'http://localhost:3000/dashboard', port: 9222, thresholds: { performance: 50, accessibility: 80, }, }); await context.close(); ``` -------------------------------- ### Audit with Specific Metric Threshold using Playwright Lighthouse Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md Performs a Lighthouse audit focusing on a single metric, 'performance', with a specific threshold. The test will only fail if the performance score is below the defined value, ignoring other metrics. ```javascript await playAudit({ page: page, thresholds: { performance: 85, }, port: 9222, }); ``` -------------------------------- ### Usage with Playwright Test Runner (TypeScript) Source: https://github.com/abhinaba-ghosh/playwright-lighthouse/blob/master/README.md This snippet shows how to integrate Lighthouse audits into the Playwright Test Runner. It extends Playwright's test functionality to manage a unique debugging port for each worker and launch a browser instance, enabling parallel execution of Lighthouse audits. ```typescript 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) => { // Assign a unique port for each playwright worker to support parallel tests 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, }); }); }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.