Playwright 环境安装和配置指南

1. 安装 Playwright

使用 npm 安装

bash 复制代码
# 安装 Playwright
npm install -D @playwright/test

# 安装浏览器
npx playwright install

使用 yarn 安装

bash 复制代码
# 安装 Playwright
yarn add -D @playwright/test

# 安装浏览器
yarn playwright install

2. 项目配置

基础配置文件 (playwright.config.js)

php 复制代码
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  // 测试目录
  testDir: './tests',
  
  // 并行运行测试
  workers: process.env.CI ? 1 : undefined,
  
  // 重试失败的测试
  retries: process.env.CI ? 2 : 0,
  
  // 超时设置
  timeout: 30000,
  
  // 报告配置
  reporter: [
    ['html'],
    ['list']
  ],
  webServer: {
    command: 'npm run dev',
    url: 'http://localhost:5173',
    reuseExistingServer: !process.env.CI,
  },
  // 项目配置
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },
  ],
  
  // 全局设置
  use: {
    // 基础 URL
    baseURL: 'http://localhost:5174',
    
    // 截图设置
    screenshot: 'only-on-failure',
    
    // 视频设置
    video: 'retain-on-failure',
    
    // 追踪设置
    trace: 'retain-on-failure',
    env: {
      NODE_ENV: process.env.NODE_ENV || 'development'
    }
  },
  globalSetup: async ({ playwright }) => {
    // 可以在这里添加全局的设置
  },
  globalTeardown: async ({ playwright }) => {
    // 可以在这里添加全局的清理
  },
});

package.json 配置

json 复制代码
{
  "scripts": {
    "test": "playwright test",
    "test:ui": "playwright test --ui",
    "test:debug": "playwright test --debug",
    "test:report": "playwright show-report"
  }
}

3. 目录结构

bash 复制代码
demo/
├── tests/                    # 测试文件目录
│   ├── home.spec.js         # 首页测试
│   ├── form.spec.js         # 表单页测试
│   ├── list.spec.js         # 列表页测试
│   └── playwright-guide.md  # 测试指南
├── playwright.config.js     # Playwright 配置
└── package.json            # 项目配置

4. 环境变量配置

.env 文件

ini 复制代码
# 开发环境
VITE_API_BASE_URL=http://localhost:3000
VITE_APP_TITLE=Demo App

# 测试环境
PLAYWRIGHT_BASE_URL=http://localhost:5173
PLAYWRIGHT_HEADLESS=true

在配置文件中使用环境变量

arduino 复制代码
// playwright.config.js
export default defineConfig({
  use: {
    baseURL: process.env.PLAYWRIGHT_BASE_URL || 'http://localhost:5173',
  },
});

5. 测试运行

运行所有测试

bash 复制代码
npm test

运行 UI 模式

arduino 复制代码
npm run test:ui

运行调试模式

arduino 复制代码
npm run test:debug

查看测试报告

arduino 复制代码
npm run test:report

6. 常见问题解决

浏览器安装问题

bash 复制代码
# 重新安装浏览器
npx playwright install

# 安装特定浏览器
npx playwright install chromium

权限问题

bash 复制代码
# Linux/Mac 系统
chmod +x node_modules/.bin/playwright

代理设置

php 复制代码
// playwright.config.js
export default defineConfig({
  use: {
    proxy: {
      server: 'http://myproxy.com:3128',
      username: 'user',
      password: 'pass'
    }
  }
});

7. CI/CD 集成

GitHub Actions 配置

yaml 复制代码
name: Playwright Tests
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v2
    - uses: actions/setup-node@v2
      with:
        node-version: 16
    - name: Install dependencies
      run: npm ci
    - name: Install Playwright Browsers
      run: npx playwright install --with-deps
    - name: Run Playwright tests
      run: npx playwright test
    - uses: actions/upload-artifact@v2
      if: always()
      with:
        name: playwright-report
        path: playwright-report/

8. 性能优化

配置优化

arduino 复制代码
// playwright.config.js
export default defineConfig({
  // 并行运行测试
  workers: process.env.CI ? 1 : undefined,
  
  // 设置超时时间
  timeout: 30000,
  
  // 设置重试次数
  retries: process.env.CI ? 2 : 0,
  
  // 设置全局等待时间
  expect: {
    timeout: 5000
  }
});

测试优化建议

  1. 使用 test.beforeEach() 进行测试准备
  2. 避免不必要的等待
  3. 使用适当的超时时间
  4. 合理使用并行测试
  5. 优化选择器性能

9. 调试技巧

使用 UI 模式

arduino 复制代码
npm run test:ui

使用调试模式

arduino 复制代码
npm run test:debug

使用断点

csharp 复制代码
// 在代码中添加断点
await page.pause();

查看追踪

bash 复制代码
# 运行测试并生成追踪
npx playwright test --trace on

# 查看追踪
npx playwright show-trace trace.zip
相关推荐
deli0078 小时前
锁过期了业务还没跑完:SETNX 分布式锁 1000 次并发实测
前端
不一样的少年_9 小时前
用了这 Skill,我觉得前端兄弟可以毕业了
前端·后端·agent
FRing039 小时前
vue2干货总结10(json-server、vant-ui、postcss插件、axios二次封装、图形验证码、toast轻提示)
开发语言·前端·vue.js·ui·json·vue2·postcss
梦想很大很大9 小时前
一句“你好”用了 5671 Token:我在 Workrun 中追查 Agent 隐性成本的过程
前端·人工智能·后端
SameX9 小时前
HarmonyOS ArkTS 做动画 FPS 自适应降级的滞后窗口做法
前端
用户97887605390489 小时前
Canvas 处理大图时如何不卡住主线程:一次浏览器端批量压缩的调度实践
前端
鶴哥只手遮天9 小时前
# 《Electron 45.2.3 内核解剖》第 6 章 Node.js 集成:两个事件循环的婚姻
前端·electron·开源
bai2739 小时前
别再手动刷后台了:用原生 CDP 给 4 个内容平台做登录态保活心跳
前端
工程小白菜10 小时前
AI 生成的代码谁来验收?从 Copilot 到 WorkBuddy 的三个实践
前端·ai编程
我不会起名字32210 小时前
仅 Web 主动 ping:30 秒读超时与各平台保活
前端·后端·websocket·go·即时通讯·im·故障排查