Playwright 安装与配置 #

系统要求 #

操作系统支持 #

操作系统 最低版本 备注
Windows Windows 10 支持 x64
macOS macOS 12 Monterey 支持 Intel 和 Apple Silicon
Linux Ubuntu 20.04+ 需要 glibc 2.31+

Node.js 版本 #

bash
# 检查 Node.js 版本
node --version

# 要求 Node.js 18+ 或 20+
# 推荐使用 LTS 版本

硬件要求 #

text
最低配置:
├── CPU: 双核处理器
├── 内存: 4 GB RAM
└── 磁盘: 1 GB 可用空间

推荐配置:
├── CPU: 四核或以上
├── 内存: 8 GB RAM 或以上
└── 磁盘: SSD,5 GB 可用空间

安装方式 #

方式一:快速开始(推荐新手) #

使用初始化工具快速创建项目:

bash
# 使用 npm
npm init playwright@latest

# 使用 yarn
yarn create playwright

# 使用 pnpm
pnpm create playwright

初始化过程中的选项:

text
Getting started with writing end-to-end tests with Playwright:
✔ Do you want to use TypeScript or JavaScript? · TypeScript
✔ Where to put your end-to-end tests? · tests
✔ Add a GitHub Actions workflow? · true
✔ Install Playwright browsers (can be done manually via 'npx playwright install')? · true

方式二:手动安装 #

在现有项目中添加 Playwright:

bash
# 安装 Playwright
npm install --save-dev @playwright/test

# 安装浏览器
npx playwright install

# 安装系统依赖(Linux)
npx playwright install-deps

方式三:仅安装特定浏览器 #

bash
# 仅安装 Chromium
npx playwright install chromium

# 仅安装 Firefox
npx playwright install firefox

# 仅安装 WebKit
npx playwright install webkit

# 安装多个浏览器
npx playwright install chromium firefox

项目结构 #

初始化后的目录结构 #

text
my-playwright-project/
├── node_modules/
├── tests/
│   └── example.spec.ts      # 示例测试文件
├── tests-examples/
│   └── demo-todo-app.spec.ts
├── playwright.config.ts      # 配置文件
├── package.json
├── package-lock.json
└── tsconfig.json             # TypeScript 配置

测试文件命名约定 #

text
tests/
├── auth.spec.ts              # 认证相关测试
├── cart.spec.ts              # 购物车测试
├── checkout.spec.ts          # 结账流程测试
├── api/
│   └── users.spec.ts         # API 测试
└── e2e/
    └── user-journey.spec.ts  # E2E 测试

配置文件详解 #

基础配置文件 #

typescript
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  // 测试目录
  testDir: './tests',
  
  // 完全并行运行测试
  fullyParallel: true,
  
  // CI 上失败时禁止 test.only
  forbidOnly: !!process.env.CI,
  
  // CI 上重试失败测试
  retries: process.env.CI ? 2 : 0,
  
  // CI 上限制并行 workers
  workers: process.env.CI ? 1 : undefined,
  
  // Reporter 配置
  reporter: 'html',
  
  // 所有测试的共享配置
  use: {
    // 基础 URL
    baseURL: 'http://localhost:3000',
    
    // 收集失败测试的追踪
    trace: 'on-first-retry',
    
    // 截图
    screenshot: 'only-on-failure',
    
    // 视频录制
    video: 'retain-on-failure',
  },

  // 配置项目(浏览器)
  projects: [
    {
      name: 'chromium',
      use: { ...devices['Desktop Chrome'] },
    },
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },
  ],

  // 运行测试前启动开发服务器
  webServer: {
    command: 'npm run start',
    url: 'http://localhost:3000',
    reuseExistingServer: !process.env.CI,
  },
});

配置项详解 #

testDir - 测试目录 #

typescript
export default defineConfig({
  testDir: './tests',           // 单个目录
  testDir: ['./tests', './e2e'], // 多个目录
});

timeout - 超时配置 #

typescript
export default defineConfig({
  // 单个测试超时(毫秒)
  timeout: 30000,
  
  // expect 断言超时
  expect: {
    timeout: 5000,
  },
  
  // 全局超时
  globalTimeout: 60000,
});

use - 测试选项 #

typescript
export default defineConfig({
  use: {
    // 基础 URL
    baseURL: 'http://localhost:3000',
    
    // 浏览器存储状态(登录状态)
    storageState: 'auth.json',
    
    // 视口大小
    viewport: { width: 1280, height: 720 },
    
    // 忽略 HTTPS 错误
    ignoreHTTPSErrors: true,
    
    // 用户代理
    userAgent: 'Custom User Agent',
    
    // 语言环境
    locale: 'zh-CN',
    
    // 时区
    timezoneId: 'Asia/Shanghai',
    
    // 权限
    permissions: ['geolocation'],
    
    // 地理位置
    geolocation: { latitude: 39.9042, longitude: 116.4074 },
    
    // 追踪
    trace: 'on', // 'on' | 'off' | 'on-first-retry' | 'retain-on-failure'
    
    // 截图
    screenshot: 'only-on-failure', // 'on' | 'off' | 'only-on-failure' | 'on-test-failure'
    
    // 视频
    video: 'retain-on-failure', // 'on' | 'off' | 'retain-on-failure' | 'on-first-retry'
    
    // 控制台日志
    actionTimeout: 10000,
    
    // 导航超时
    navigationTimeout: 30000,
  },
});

projects - 浏览器项目配置 #

typescript
export default defineConfig({
  projects: [
    // Desktop Chrome
    {
      name: 'chromium',
      use: { 
        ...devices['Desktop Chrome'],
        // 自定义配置
        viewport: { width: 1920, height: 1080 },
      },
    },
    
    // Desktop Firefox
    {
      name: 'firefox',
      use: { ...devices['Desktop Firefox'] },
    },
    
    // Desktop Safari
    {
      name: 'webkit',
      use: { ...devices['Desktop Safari'] },
    },
    
    // Mobile Chrome
    {
      name: 'Mobile Chrome',
      use: { ...devices['Pixel 5'] },
    },
    
    // Mobile Safari
    {
      name: 'Mobile Safari',
      use: { ...devices['iPhone 12'] },
    },
    
    // Tablet
    {
      name: 'iPad',
      use: { ...devices['iPad Pro'] },
    },
    
    // 品牌浏览器
    {
      name: 'Google Chrome',
      use: {
        channel: 'chrome', // 使用安装的 Chrome
      },
    },
    {
      name: 'Microsoft Edge',
      use: {
        channel: 'msedge', // 使用安装的 Edge
      },
    },
  ],
});

webServer - 开发服务器 #

typescript
export default defineConfig({
  webServer: {
    // 启动命令
    command: 'npm run start',
    
    // 等待的 URL
    url: 'http://localhost:3000',
    
    // 重用已有服务器
    reuseExistingServer: true,
    
    // 超时时间
    timeout: 120000,
    
    // 重启次数
    retries: 3,
    
    // 输出目录
    cwd: './app',
    
    // 环境变量
    env: {
      NODE_ENV: 'test',
    },
  },
});

reporter - 报告器配置 #

typescript
export default defineConfig({
  reporter: [
    // 控制台报告
    ['list'],
    
    // HTML 报告
    ['html', { 
      outputFolder: 'playwright-report',
      open: 'never', // 'always' | 'never' | 'on-failure'
    }],
    
    // JSON 报告
    ['json', { outputFile: 'results.json' }],
    
    // JUnit 报告
    ['junit', { outputFile: 'junit.xml' }],
    
    // GitHub 报告
    ['github'],
  ],
});

环境变量配置 #

使用 .env 文件 #

bash
# .env
BASE_URL=https://staging.example.com
USERNAME=testuser
PASSWORD=testpass
typescript
// playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: {
    baseURL: process.env.BASE_URL,
  },
});

在测试中使用 #

typescript
import { test, expect } from '@playwright/test';

test('使用环境变量', async ({ page }) => {
  const username = process.env.USERNAME;
  const password = process.env.PASSWORD;
  
  await page.fill('#username', username);
  await page.fill('#password', password);
});

TypeScript 配置 #

tsconfig.json 配置 #

json
{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "moduleResolution": "node",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "resolveJsonModule": true,
    "types": ["node", "@playwright/test"]
  },
  "include": ["tests/**/*.ts"],
  "exclude": ["node_modules"]
}

package.json 脚本 #

常用脚本配置 #

json
{
  "scripts": {
    "test": "playwright test",
    "test:ui": "playwright test --ui",
    "test:headed": "playwright test --headed",
    "test:debug": "playwright test --debug",
    "test:chromium": "playwright test --project=chromium",
    "test:firefox": "playwright test --project=firefox",
    "test:webkit": "playwright test --project=webkit",
    "test:report": "playwright show-report",
    "test:codegen": "playwright codegen",
    "test:trace": "playwright show-trace",
    "lint": "eslint tests/**/*.ts"
  }
}

验证安装 #

运行示例测试 #

bash
# 运行所有测试
npx playwright test

# 运行特定文件
npx playwright test example.spec.ts

# 运行特定浏览器
npx playwright test --project=chromium

# 显示浏览器运行
npx playwright test --headed

查看测试报告 #

bash
# 打开 HTML 报告
npx playwright show-report

# 指定报告目录
npx playwright show-report ./my-report

常见问题解决 #

浏览器安装失败 #

bash
# 清理缓存重新安装
npx playwright uninstall --all
npx playwright install

# 手动指定安装目录
PLAYWRIGHT_BROWSERS_PATH=0 npx playwright install

Linux 系统依赖 #

bash
# 安装系统依赖
npx playwright install-deps

# 或手动安装(Ubuntu/Debian)
sudo apt-get install -y \
  libnss3 libatk1.0-0 libatk-bridge2.0-0 \
  libcups2 libdrm2 libxkbcommon0 libxcomposite1 \
  libxdamage1 libxfixes3 libxrandr2 libgbm1 \
  libasound2 libpango-1
最后更新:2026-03-28