Playwright 第3章:项目结构与配置

合理的项目结构和配置文件是 Playwright 自动化项目的基础。本章详细介绍 playwright.config.ts 的配置选项、测试目录组织方式以及多浏览器配置策略。

playwright.config.ts 配置详解

Playwright Test 使用 playwright.config.ts 作为核心配置文件。使用 npm init playwright@latest 初始化时会自动生成。

基础配置模板

import { defineConfig } from '@playwright/test';

export default defineConfig({
  // 测试文件匹配规则
  testDir: './tests',
  testMatch: '**/*.spec.ts',

  // 测试超时
  timeout: 30000,
  expect: {
    timeout: 5000,
  },

  // 重试策略
  retries: process.env.CI ? 2 : 0,

  // 并行执行
  fullyParallel: true,
  workers: process.env.CI ? 4 : undefined,

  // 报告器
  reporter: [
    ['html'],
    ['list'],
    ['json', { outputFile: 'test-results.json' }],
  ],

  // 全局设置
  globalSetup: './global-setup.ts',
  globalTeardown: './global-teardown.ts',

  // 共享配置
  use: {
    baseURL: 'http://localhost:3000',
    headless: true,
    viewport: { width: 1280, height: 720 },
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
    trace: 'on-first-retry',
  },
});

配置项详解

配置项类型默认值说明
testDirstring'./tests'测试文件目录
testMatchstring/RegExp`**/*.@(spectest).*''
timeoutnumber30000每个测试的超时时间(ms)
retriesnumber0失败重试次数
workersnumber1并行 worker 数量
reporterarray/string'list'测试报告格式
globalSetupstring-全局安装脚本
globalTeardownstring-全局拆卸脚本

测试目录组织

推荐的目录结构

my-playwright-project/
├── playwright.config.ts     # Playwright 配置
├── global-setup.ts          # 全局安装
├── global-teardown.ts       # 全局拆卸
├── tests/
│   ├── login.spec.ts        # 登录测试
│   ├── search.spec.ts       # 搜索测试
│   └── checkout.spec.ts     # 结算测试
├── pages/                   # Page Object 模型
│   ├── LoginPage.ts
│   ├── SearchPage.ts
│   └── CheckoutPage.ts
├── fixtures/                # 自定义 Fixture
│   └── auth-fixture.ts
├── data/                    # 测试数据
│   ├── users.json
│   └── products.json
├── utils/                   # 工具函数
│   └── helpers.ts
└── test-results/            # 测试结果输出
    ├── report/
    └── screenshots/

测试文件命名规范

// 推荐的命名方式
login.spec.ts
search.feature.spec.ts
api.health.check.spec.ts

// 按功能模块组织
tests/
├── auth/
│   ├── login.spec.ts
│   └── register.spec.ts
├── products/
│   ├── list.spec.ts
│   └── detail.spec.ts
└── checkout/
    └── payment.spec.ts

多浏览器配置

Playwright 支持同时为多个浏览器运行测试。

projects 配置

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  projects: [
    {
      name: 'chromium',
      use: {
        ...devices['Desktop Chrome'],
        viewport: { width: 1920, height: 1080 },
      },
    },
    {
      name: 'firefox',
      use: {
        ...devices['Desktop Firefox'],
      },
    },
    {
      name: 'webkit',
      use: {
        ...devices['Desktop Safari'],
      },
    },
    {
      name: 'mobile-chrome',
      use: {
        ...devices['Pixel 5'],
      },
    },
    {
      name: 'mobile-safari',
      use: {
        ...devices['iPhone 14'],
      },
    },
  ],
});

内置设备描述

Playwright 内置了大量设备描述,覆盖主流移动设备:

import { devices } from '@playwright/test';

// 常用设备
devices['iPhone 14']
devices['Pixel 5']
devices['Galaxy S8']
devices['iPad Pro 11']
devices['Surface Duo']

// 自定义设备配置
const customDevice = {
  userAgent: 'Mozilla/5.0 (Custom)',
  viewport: { width: 1440, height: 900 },
  deviceScaleFactor: 2,
  isMobile: false,
  hasTouch: false,
  defaultBrowserType: 'chromium',
};

WebServer 配置

Playwright 支持在测试前自动启动 Web 服务器:

export default defineConfig({
  webServer: {
    command: 'npm run start',
    url: 'http://localhost:3000',
    reuseExistingServer: !process.env.CI,
    timeout: 120000,
    cwd: './my-app',
    env: {
      NODE_ENV: 'test',
    },
  },
});

环境变量与配置文件分离

根据运行环境加载不同配置:

// playwright.config.ts
import { defineConfig } from '@playwright/test';
import * as dotenv from 'dotenv';

// 加载环境变量
dotenv.config({ path: `./env/.env.${process.env.ENV || 'dev'}` });

export default defineConfig({
  use: {
    baseURL: process.env.BASE_URL || 'http://localhost:3000',
    extraHTTPHeaders: {
      'Authorization': `Bearer ${process.env.API_TOKEN}`,
    },
  },
});

注意:上例中的模板变量 ${} 是在 JavaScript 运行时执行的,不是 bash 中的变量,因此不需要转义。

总结

合理配置 playwright.config.ts 是 Playwright 项目的基石。通过 projects 配置实现多浏览器测试,通过 webServer 自动管理测试服务,结合环境变量实现灵活的环境切换。推荐将测试文件按功能模块组织,并使用 Page Object 模式提高代码复用性。