Lighthouse Integration
Learn how to integrate Lighthouse in your Playwright tests.
Lighthouse
is a tool developed by Google that analyzes web apps and web pages, collecting modern performance metrics and insights on developer best practices.
Install the package
Run the following command to install the BrowserStack playwright-lighthouse
package to your project:
npm i "https://github.com/asambstack/playwright-lighthouse.git"
Export the LH_BROWSERSTACK
environment variable to your project environment as shown:
export LH_BROWSERSTACK='true'
Sample script
After installing the required libraries, you can use the following script to run the sample test:
//sample_test.js
'use strict';
const {chromium, firefox, webkit, test} = require('playwright');
const fs = require('fs')
const {promisify} = require('util');
const sleep = promisify(setTimeout);
const { playAudit } = require('playwright-lighthouse');
const run = async (browser_name, os_name, os_version_name, terminal = null, pw_version = null) => {
const tag = `Lighthouse Playwright`
const caps = {
build: `${tag}`,
name: `[${os_version_name}] ${browser_name}`,
browser: browser_name,
os: os_name,
os_version: os_version_name,
'browserstack.username': process.env.BROWSERSTACK_USERNAME || 'YOUR_USERNAME',
'browserstack.accessKey': process.env.BROWSERSTACK_ACCESS_KEY || 'YOUR_ACCESS_KEY',
'browserstack.networkLogs': true,
'browserstack.console': 'errors',
};
const browser = await webkit.connect({
wsEndpoint: `wss://cdp.browserstack.com/playwright?caps=${encodeURIComponent(JSON.stringify(caps))}`,
});
const context = await browser.newContext({
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
await page.goto('https://www.bstackdemo.com/',{ waitUntil: 'networkidle' });
await page.locator('[id="\\32 "]').getByText('Add to cart').click();
await page.getByText('Checkout').click();
await page.locator('#username svg').click();
await page.locator('#react-select-2-option-0-0').click();
await page.locator('#password svg').click();
await page.locator('#react-select-3-option-0-0').click();
await page.getByRole('button', { name: 'Log In' }).click();
await page.getByLabel('First Name').click();
await page.getByLabel('First Name').fill('SampleFirst');
await page.getByLabel('Last Name').click();
await page.getByLabel('Last Name').fill('sampleLast');
await page.getByLabel('Address').click();
await page.getByLabel('Address').fill('sampleAddress');
await page.getByLabel('State/Province').click();
await page.getByLabel('State/Province').fill('SampleState');
await page.getByLabel('Postal Code').click();
await page.getByLabel('Postal Code').fill('123456');
await page.getByRole('button', { name: 'Submit' }).click();
await page.getByRole('button', { name: 'Continue Shopping »' }).click();
try{
await playAudit({
page: page,
thresholds: {
performance: 10,
accessibility: 10,
'best-practices': 10,
seo: 10,
pwa: 10,
},
reports: {
formats: {
json: true,
html: true,
csv: true,
}
},
port: 9223
});
await page.evaluate(_ => {}, `browserstack_executor: ${JSON.stringify({action: 'setSessionStatus',arguments: {status: 'passed',reason: 'Performance score above the desired threshold'}})}`);
}
catch (e) {
console.log(e);
await page.evaluate(_ => {}, `browserstack_executor: ${JSON.stringify({action: 'setSessionStatus',arguments: {status: 'failed',reason: 'Performance score below the desired threshold'}})}`);
}
await page.close();
await browser.close();
};
Promise.all([
run('playwright-chromium', 'windows', '11'),
]).then( responses => {
for (const response of responses) {
console.log(response);
}
}).catch( error => {
console.error(`Failed to fetch: ${error}`)
});
Understanding the script
The above script performs the following actions:
- The sample test case opens the bstackdemo.com website.
- Adds a product to the cart, and verifies whether the performance is above the desired threshold.
Setting the threshold value
You can set the threshold value within the playAudit function to evaluate the performance. The threshold value ranges from 0 to 100, with 0 representing the lowest and 100 representing the highest value.
await playAudit({
page: page,
thresholds: {
performance: 10,
accessibility: 10,
'best-practices': 10,
seo: 10,
pwa: 10,
}}),
Generating the report
Within the playAudit function, you have the ability to generate reports in various formats such as json
, html
, and csv
. To specifically generate a report in html
format, you can set the corresponding parameter to true
as shown below:
await playAudit({
reports: {
formats: {
json: false,
html: true,
csv: false,
}}
}),
Setting Browser-OS combination
You can also try various Browser-OS combination to test your script as shown:
run('playwright-chromium', 'windows', '11'),
Due to the default behavior of Lighthouse with Playwright, the tests on playwright-chromium
browser will run in a new tab. However, tests with chrome
browser will run in the same tab as that of Playwright. Therefore, the Playwright code after the “playAudit execution” will fail in chrome
browser, as Lighthouse will close the tab once its execution is done. To run your test on chrome
browser, modify the following code snippet:
await playAudit({
url: page.url(),
page: await context.newPage(),
});
Run your script
Run your script using the following command:
node sample_test.js
On running the above command, the reports get generated in the lighthouse
folder of the root directory of your project.
View test results
View your tests on BrowserStack on the BrowserStack Automate dashboard. Check out viewing test results to learn more about the dashboard.
We're sorry to hear that. Please share your feedback so we can do better
Contact our Support team for immediate help while we work on improving our docs.
We're continuously improving our docs. We'd love to know what you liked
We're sorry to hear that. Please share your feedback so we can do better
Contact our Support team for immediate help while we work on improving our docs.
We're continuously improving our docs. We'd love to know what you liked
Thank you for your valuable feedback!