关注我的GitHub新项目!
Playwright是一个强大的浏览器自动化库,用于快速、可靠且跨浏览器的测试。它支持Chromium、Firefox和WebKit,是自动化Web交互、测试应用程序和提升UI可靠性的理想工具。本指南涵盖以下内容:
Playwright是一个Node.js库,用于浏览器自动化。它允许您控制浏览器,与页面元素交互,截取屏幕截图,录制视频以及执行UI测试。主要功能:
Playwright需要Node.js 14或更高版本。
使用npm安装:
npm init playwright@latest
此命令会设置Playwright,包括浏览器、测试框架和示例。
手动安装Playwright:
npm install @playwright/test npx playwright install
此命令会安装Chromium、Firefox和WebKit浏览器。
让我们创建一个简单的Playwright测试,检查网页是否正确加载。
示例:打开一个网页并检查标题
创建一个测试文件:
const { test, expect } = require('@playwright/test'); test('检查网站标题', async ({ page }) => { await page.goto('https://example.com'); const title = await page.title(); expect(title).toBe('Example Domain'); });
运行测试:
npx playwright test
Playwright默认在无头模式下运行测试。添加--headed参数可在浏览器UI中查看测试运行过程。
许多Web应用程序需要身份验证才能访问受保护的区域。Playwright可以轻松地存储和重用身份验证会话。
示例:持久登录
test('登录并保存会话', async ({ browser }) => { const context = await browser.newContext(); const page = await context.newPage(); await page.goto('https://example.com/login'); await page.fill('input[name="username"]', 'testuser'); await page.fill('input[name="password"]', 'password123'); await page.click('button[type="submit"]'); // 保存身份验证状态 await context.storageState({ path: 'auth.json' }); });
这会将身份验证状态存储在auth.json文件中,以便后续测试重用该会话。
在其他测试中使用保存的会话:
test.use({ storageState: 'auth.json' }); test('访问仪表盘', async ({ page }) => { await page.goto('https://example.com/dashboard'); await expect(page).toHaveText('Welcome, testuser'); });
这避免了每次测试运行都需要登录,从而加快测试速度。
Playwright允许模拟API响应,使测试独立于实际服务器数据。
模拟API响应:
test('模拟API响应', async ({ page }) => { await page.route('https://api.example.com/user', async (route) => { await route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ id: 1, name: '模拟用户' }), }); }); await page.goto('https://example.com/profile'); await expect(page.locator('.username')).toHaveText('模拟用户'); });
这确保了测试即使后端出现故障也能正常运行,并且可以用于测试边缘情况和错误处理。
Playwright支持自动截取屏幕截图和录制视频以进行调试。
截取屏幕截图:
await page.screenshot({ path: 'screenshot.png' });
录制视频:
在playwright.config.js中启用视频录制:
module.exports = { use: { video: 'on' } };
视频将存储在测试结果文件夹中。
Playwright可以同时运行多个测试,从而加快测试速度。
启用并行执行:
修改playwright.config.js:
module.exports = { use: { headless: true }, workers: 4 // 在4个并行进程中运行测试 };
Playwright会自动在多个浏览器实例中分配测试。
Playwright支持设备模拟,用于测试移动浏览器。
模拟iPhone:
const { devices } = require('@playwright/test'); test.use({ ...devices['iPhone 12'] }); test('移动测试', async ({ page }) => { await page.goto('https://example.com'); await page.screenshot({ path: 'mobile.png' }); });
devices['iPhone 12']模拟iPhone的屏幕尺寸和用户代理。
测试地理位置(GPS):
test('测试位置', async ({ page, context }) => { await context.grantPermissions(['geolocation']); await page.setGeolocation({ latitude: 37.7749, longitude: -122.4194 }); // 旧金山 });
这模拟了基于地理位置的应用程序的用户位置。
Playwright可以直接测试API端点。
示例:测试REST API:
test('API测试', async ({ request }) => { const response = await request.get('https://jsonplaceholder.typicode.com/posts/1'); expect(response.status()).toBe(200); const data = await response.json(); expect(data.id).toBe(1); });
request.get()获取API数据,expect(response.status()).toBe(200)确保请求成功。
如果测试失败,调试可以帮助您找到问题。
使用playwright.inspect():
await playwright.inspect();
这会打开Playwright调试器,暂停测试执行。
在有头模式下运行:
npx playwright test --headed
这会打开一个可见的浏览器窗口。
使用slowMo减慢执行速度:
const { chromium } = require('playwright'); const browser = await chromium.launch({ headless: false, slowMo: 1000 });
这会减慢交互速度,以便更好地调试。
Playwright与GitHub Actions、Jenkins和CircleCI等CI/CD系统集成。
GitHub Actions示例:
创建一个.github/workflows/playwright.yml文件:
name: Playwright Tests on: [push] jobs: test: runs-on: ubuntu-latest steps: - name: Checkout Repo uses: actions/checkout@v2 - name: Install Dependencies run: npm install - name: Install Browsers run: npx playwright install - name: Run Tests run: npx playwright test
这会在GitHub Actions上运行测试。
Playwright提供了一套全面的功能,用于浏览器自动化、测试和调试。无论您是测试UI组件、API响应还是移动布局,Playwright都能通过其强大的API简化自动化过程。
下一步:
Playwright 亮点总结:
自动控制浏览器(Chromium、Firefox、WebKit)。 支持UI测试、API测试、移动模拟和地理位置测试。 并行运行测试,提高速度。 截取屏幕截图和录制视频进行调试。 使用网络模拟在无需实际服务器调用的情况下测试API。 处理身份验证,使用保存的会话。 与CI/CD集成以进行自动化测试。
您是否使用过Playwright?在评论中分享您的经验!
以上就是剧作家:浏览器自动化和测试指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号