1.在项目根目录下执行
javascript
npm init playwright@latest
2.下载浏览器内核
javascript
npx playwright install chromium
3.编写配置文件
javascript
import { defineConfig, devices } from '@playwright/test'
/**
* Read environment variables from file.
* https://github.com/motdotla/dotenv
*/
// import dotenv from 'dotenv';
// import path from 'path';
// dotenv.config({ path: path.resolve(__dirname, '.env') });
/**
* @see https://playwright.dev/docs/test-configuration
*/
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
baseURL: 'https://localhost:3434/#/',
// 失败时自动截图
screenshot: 'only-on-failure',
// 失败时自动录像
video: 'retain-on-failure',
trace: 'on-first-retry',
},
webServer: {
command: 'npm run dev', // 启动 Vite 开发服务器的命令
url: 'https://localhost:3434/#/', // 等待服务器就绪的 URL
reuseExistingServer: !process.env.CI, // CI 环境下每次重建,本地复用
timeout: 120 * 1000, // 启动超时时间
ignoreHTTPSErrors: true, // 忽略 HTTPS 错误
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
},
],
})
4.编写测试用例
javascript
import { test, expect } from '@playwright/test'
test.use({
ignoreHTTPSErrors: true,
})
test('自动化测试用例', async ({ page }) => {
await page.goto('https://localhost:3434/#/login')
await page.getByRole('textbox', { name: '请输入用户名' }).click()
await page.getByRole('textbox', { name: '请输入用户名' }).fill('pengchangbin')
await page.getByRole('textbox', { name: '请输入登录密码' }).click()
await page.getByRole('textbox', { name: '请输入登录密码' }).fill('Guide12345678+')
await page.getByRole('button', { name: '登录' }).click()
await page.getByText('角色管理').click()
await page.getByRole('button').filter({ hasText: /^$/ }).nth(3).click()
await page.getByRole('button', { name: '保存' }).click()
await page.getByText('文件中心').click()
await page.getByText('图片文件').click()
await page.getByRole('button', { name: '查询' }).click()
await page.getByText('事件中心').click()
await page.getByText('统计分析').click()
await page.getByText('温度统计').click()
const downloadPromise = page.waitForEvent('download')
await page.locator('.icon-download').click()
const download = await downloadPromise
await page.getByRole('button', { name: '查询' }).click()
await page.getByText('在线监测').click()
await page.getByText('视频监控').click()
await page.locator('.icon-pause').click()
await page.locator('.icon-play').click()
await page.getByRole('button', { name: '轮巡计划' }).click()
await page.getByText('添加').click()
await page.getByRole('button', { name: '关闭此对话框' }).click()
await page.getByRole('button').nth(4).click()
await page.getByRole('button', { name: '保存' }).click()
})
5.执行测试命令
javascript
npm run test:e2e:chromium
其他:可视化编写测试用例
javascript
npx playwright codegen http://localhost:5013