各位前端er,你是否也曾为了优化网页性能,对着 Lighthouse 的报告抓耳挠腮?手动跑 Lighthouse 固然能发现问题,但效率实在感人。今天,我就来分享一下如何将 Playwright 和 Lighthouse 完美结合,让性能测试自动化,告别加班,拥抱高效!
目标读者:
- 对网页性能有较高要求的开发团队。
- 希望实现性能测试自动化的工程师。
- 熟悉 Playwright 和 Lighthouse 的基本使用。
核心价值:
- 自动化生成 Lighthouse 报告,节省时间,提高效率。
- 将性能测试融入 CI/CD 流程,尽早发现并解决性能问题。
- 定制化性能测试策略,满足不同场景下的需求。
前期准备:
Node.js 环境: 确保你的机器上已经安装了 Node.js (推荐 v16 或更高版本)。
Playwright 安装: 如果还没有安装 Playwright,可以通过 npm 或 yarn 进行安装:
npm install -D @playwright/test # 或者 yarn add -D @playwright/test
安装完成后,执行以下命令安装 Playwright 浏览器:
npx playwright install
Lighthouse 安装: 同样,使用 npm 或 yarn 安装 Lighthouse:
npm install -D lighthouse # 或者 yarn add -D lighthouse
集成步骤:
Step 1: 创建 Playwright 测试项目
如果还没有 Playwright 项目,可以创建一个新的项目。例如,创建一个名为 performance-test
的目录,并在其中初始化 Playwright:
mkdir performance-test
cd performance-test
npm init -y
npm install -D @playwright/test lighthouse
npx playwright install
Step 2: 编写 Playwright 测试用例
在项目根目录下创建一个名为 performance.spec.js
的文件,用于编写性能测试用例。
// performance.spec.js
const { test } = require('@playwright/test');
const lighthouse = require('lighthouse');
const chromeLauncher = require('chrome-launcher');
let chrome;
test.describe('Performance Tests', () => {
test.beforeAll(async () => {
chrome = await chromeLauncher.launch({ chromeFlags: ['--headless'] });
});
test.afterAll(async () => {
await chrome.kill();
});
test('should pass Lighthouse audit', async ({ page }) => {
const url = 'https://www.example.com'; // 替换成你要测试的网址
await page.goto(url);
const options = {
logLevel: 'info',
output: 'html',
onlyCategories: ['performance'], // 只关注性能指标
port: chrome.port,
};
const runnerResult = await lighthouse(url, options);
console.log('Report is done for', runnerResult.lhr.finalUrl);
console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100);
// 可以添加断言,例如:
// expect(runnerResult.lhr.categories.performance.score).toBeGreaterThan(0.9);
});
});
代码解析:
require('@playwright/test')
引入 Playwright 测试框架。require('lighthouse')
引入 Lighthouse 模块。require('chrome-launcher')
引入 Chrome Launcher,用于启动 Chrome 实例。test.beforeAll
在所有测试用例执行前启动 Chrome 实例。test.afterAll
在所有测试用例执行后关闭 Chrome 实例。test('should pass Lighthouse audit', ...)
定义一个测试用例,用于执行 Lighthouse 审计。page.goto(url)
使用 Playwright 打开需要测试的网页。lighthouse(url, options)
执行 Lighthouse 审计,并传入配置项。logLevel: 'info'
设置日志级别为 info。output: 'html'
设置报告输出格式为 HTML。onlyCategories: ['performance']
只关注性能指标。port: chrome.port
指定 Chrome 实例的端口。
runnerResult.lhr
包含 Lighthouse 审计结果。runnerResult.lhr.categories.performance.score
获取性能指标的得分。expect(...)
添加断言,用于判断性能得分是否符合预期。
Step 3: 配置 Playwright
你可能需要调整 playwright.config.js
文件,例如设置超时时间,指定报告输出目录等。
// playwright.config.js
const config = {
timeout: 60000, // 设置超时时间为 60 秒
reporter: [['html', { outputFolder: 'lighthouse-report' }]], // 指定 HTML 报告输出目录
};
module.exports = config;
Step 4: 运行测试
在项目根目录下执行以下命令运行测试:
npx playwright test
测试完成后,你将在 lighthouse-report
目录下找到生成的 HTML 报告。
进阶配置:
自定义 Lighthouse 配置:
你可以根据自己的需求,自定义 Lighthouse 的配置项。例如,修改
onlyCategories
选项,关注更多的指标;修改auditMode
选项,进行更深入的审计。const options = { logLevel: 'info', output: 'html', onlyCategories: ['performance', 'accessibility', 'best-practices', 'seo'], // 关注更多指标 // auditMode: true, // 开启审计模式,进行更深入的审计 port: chrome.port, };
集成到 CI/CD:
将 Playwright 和 Lighthouse 集成到 CI/CD 流程中,可以实现性能测试的自动化。每次代码提交或构建时,自动运行性能测试,并将结果报告发送到指定邮箱或 Slack 频道。
例如,在 GitHub Actions 中,可以添加以下步骤:
steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: 16 - name: Install dependencies run: npm install - name: Run Playwright tests run: npx playwright test - name: Upload Lighthouse report uses: actions/upload-artifact@v3 with: name: lighthouse-report path: lighthouse-report
使用不同的 Lighthouse 策略:
Lighthouse 提供了多种策略,例如
mobile
和desktop
。你可以根据需要选择不同的策略进行测试。const options = { logLevel: 'info', output: 'html', onlyCategories: ['performance'], port: chrome.port, // strategy: 'mobile', // 使用移动端策略 // strategy: 'desktop', // 使用桌面端策略 };
处理动态内容:
有些网页的内容是动态生成的,需要在页面加载完成后才能进行 Lighthouse 审计。可以使用 Playwright 的
waitForSelector
或waitForTimeout
等方法,等待页面加载完成后再执行 Lighthouse 审计。test('should pass Lighthouse audit', async ({ page }) => { const url = 'https://www.example.com'; await page.goto(url); await page.waitForSelector('#content-loaded'); // 等待特定元素加载完成 const options = { logLevel: 'info', output: 'html', onlyCategories: ['performance'], port: chrome.port, }; const runnerResult = await lighthouse(url, options); console.log('Report is done for', runnerResult.lhr.finalUrl); console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100); // 可以添加断言,例如: // expect(runnerResult.lhr.categories.performance.score).toBeGreaterThan(0.9); });
模拟不同的网络环境:
可以使用 Playwright 的
route
方法,模拟不同的网络环境,例如 3G、4G 等,以便更好地评估网页在不同网络环境下的性能表现。test('should pass Lighthouse audit with slow network', async ({ page, context }) => { const url = 'https://www.example.com'; await context.route('**/*', route => { route.continue({ mockResponse: { status: 200, headers: { 'Content-Type': 'text/html' }, body: '<html><body><h1>Mocked Response</h1></body></html>' } }); }); await page.goto(url); const options = { logLevel: 'info', output: 'html', onlyCategories: ['performance'], port: chrome.port, }; const runnerResult = await lighthouse(url, options); console.log('Report is done for', runnerResult.lhr.finalUrl); console.log('Performance score was', runnerResult.lhr.categories.performance.score * 100); // 可以添加断言,例如: // expect(runnerResult.lhr.categories.performance.score).toBeGreaterThan(0.9); });
常见问题与解决方案:
Lighthouse 报错:"Chrome protocol error: Runtime.executionContextCreated ... Protocol error (Runtime.executionContextCreated): Context with id was not found."
这个问题通常是由于 Chrome 实例启动失败导致的。可以尝试以下解决方案:
- 确保 Chrome Launcher 的版本与 Chrome 浏览器版本兼容。
- 尝试使用不同的 Chrome Flags,例如
--no-sandbox
。 - 检查 Chrome 浏览器是否被其他进程占用。
Lighthouse 报告中缺少某些指标:
这个问题可能是由于 Lighthouse 配置不正确导致的。可以尝试以下解决方案:
- 检查
onlyCategories
选项是否包含了所有需要关注的指标。 - 尝试开启
auditMode
选项,进行更深入的审计。
- 检查
性能测试结果不稳定:
性能测试结果可能会受到多种因素的影响,例如网络环境、服务器负载等。为了获得更准确的测试结果,可以尝试以下方法:
- 多次运行测试,取平均值。
- 在稳定的网络环境下进行测试。
- 避免在服务器负载高峰期进行测试。
总结:
通过将 Playwright 和 Lighthouse 集成,我们可以实现性能测试的自动化,提高开发效率,尽早发现并解决性能问题。希望本文能够帮助你更好地利用 Playwright 和 Lighthouse,打造更优秀的网页应用!记住,持续关注性能,才能让你的网站跑得更快,用户体验更佳!