Playwright 扩展工具 #

VS Code 插件 #

Playwright Test for VS Code #

官方提供的 VS Code 插件,提供完整的测试开发体验。

安装方式:

  1. 打开 VS Code
  2. 搜索 “Playwright Test for VS Code”
  3. 点击安装

主要功能:

text
┌─────────────────────────────────────────────────────────────┐
│                  VS Code 插件功能                             │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  📁 测试资源管理器                                           │
│  ├── 显示所有测试文件                                        │
│  ├── 运行/调试测试                                           │
│  └── 查看测试结果                                            │
│                                                             │
│  🔍 代码补全                                                 │
│  ├── Locator 建议                                            │
│  ├── 方法补全                                                │
│  └── 参数提示                                                │
│                                                             │
│  🐛 调试支持                                                 │
│  ├── 断点调试                                                │
│  ├── 变量查看                                                │
│  └── 调用堆栈                                                │
│                                                             │
│  📸 Trace Viewer                                             │
│  ├── 查看测试追踪                                            │
│  ├── 时间线浏览                                              │
│  └── 快照查看                                                │
│                                                             │
└─────────────────────────────────────────────────────────────┘

配置选项:

json
// .vscode/settings.json
{
  "playwright.env": {
    "BASE_URL": "http://localhost:3000"
  },
  "playwright.project": "chromium",
  "playwright.showTrace": true,
  "playwright.reuseBrowser": true,
  "playwright.runGlobalSetup": true
}

代码生成 #

在 VS Code 中直接使用 Codegen:

  1. 打开命令面板(Cmd+Shift+P)
  2. 输入 “Playwright: Record new test”
  3. 选择浏览器和目标 URL
  4. 进行操作,代码自动生成

测试报告器 #

HTML 报告器 #

内置的 HTML 报告器,提供丰富的测试结果展示:

typescript
// playwright.config.ts
export default defineConfig({
  reporter: [
    ['html', {
      outputFolder: 'playwright-report',
      open: 'never', // 'always' | 'never' | 'on-failure'
      host: 'localhost',
      port: 9323,
    }],
  ],
});

Allure 报告器 #

流行的测试报告框架:

bash
# 安装
npm install -D @playwright/test allure-playwright

# 配置
typescript
// playwright.config.ts
export default defineConfig({
  reporter: [
    ['allure-playwright'],
  ],
});
bash
# 生成报告
npx allure generate allure-results --clean -o allure-report
npx allure open allure-report

自定义报告器 #

创建自定义报告器:

typescript
// my-reporter.ts
import { Reporter, TestCase, TestResult } from '@playwright/test/reporter';

class MyReporter implements Reporter {
  onBegin(config, suite) {
    console.log(`开始运行 ${suite.allTests().length} 个测试`);
  }
  
  onTestBegin(test: TestCase) {
    console.log(`开始测试: ${test.title}`);
  }
  
  onTestEnd(test: TestCase, result: TestResult) {
    const status = result.status;
    const duration = result.duration;
    console.log(`测试结束: ${test.title} - ${status} (${duration}ms)`);
  }
  
  onEnd(result) {
    console.log(`测试完成: ${result.status}`);
  }
  
  onError(error) {
    console.error(`错误: ${error.message}`);
  }
}

export default MyReporter;
typescript
// playwright.config.ts
export default defineConfig({
  reporter: [['./my-reporter.ts']],
});

第三方库 #

Playwright-extra #

扩展 Playwright 功能:

bash
npm install playwright-extra
typescript
import { chromium } from 'playwright-extra';
import StealthPlugin from 'puppeteer-extra-plugin-stealth';

chromium.use(StealthPlugin());

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto('https://example.com');

Axe-core 集成 #

无障碍测试:

bash
npm install -D @axe-core/playwright
typescript
import { test, expect } from '@playwright/test';
import { injectAxe, checkA11y } from '@axe-core/playwright';

test('无障碍测试', async ({ page }) => {
  await page.goto('/');
  await injectAxe(page);
  await checkA11y(page, null, {
    detailedReport: true,
  });
});

Mailosaur #

邮件测试:

bash
npm install mailosaur
typescript
import { test, expect } from '@playwright/test';
import Mailosaur from 'mailosaur';

const mailosaur = new Mailosaur('API_KEY');

test('邮件测试', async ({ page }) => {
  await page.goto('/register');
  await page.fill('#email', 'test@abc123.mailosaur.net');
  await page.click('button[type="submit"]');
  
  // 等待邮件
  const email = await mailosaur.messages.get('abc123', {
    sentTo: 'test@abc123.mailosaur.net',
  });
  
  expect(email.subject).toContain('Welcome');
});

Faker.js #

测试数据生成:

bash
npm install -D @faker-js/faker
typescript
import { test, expect } from '@playwright/test';
import { faker } from '@faker-js/faker';

test('使用假数据', async ({ page }) => {
  const user = {
    name: faker.person.fullName(),
    email: faker.internet.email(),
    phone: faker.phone.number(),
    address: faker.location.streetAddress(),
  };
  
  await page.goto('/register');
  await page.fill('#name', user.name);
  await page.fill('#email', user.email);
  await page.fill('#phone', user.phone);
  await page.fill('#address', user.address);
});

云服务集成 #

Playwright Cloud #

Microsoft 官方云测试服务:

typescript
// playwright.config.ts
export default defineConfig({
  reporter: [
    ['@azure/playwright-reporter'],
  ],
});

BrowserStack #

typescript
// playwright.config.ts
export default defineConfig({
  projects: [
    {
      name: 'browserstack',
      use: {
        connectOptions: {
          wsEndpoint: 'wss://cdp.browserstack.com/playwright?caps=...',
        },
      },
    },
  ],
});

Sauce Labs #

typescript
// playwright.config.ts
export default defineConfig({
  projects: [
    {
      name: 'saucelabs',
      use: {
        connectOptions: {
          wsEndpoint: 'wss://ondemand.saucelabs.com/...',
        },
      },
    },
  ],
});

测试工具 #

Playwright Test Generator #

自动生成测试代码:

bash
npx playwright codegen https://example.com

Playwright Inspector #

调试工具:

bash
npx playwright test --debug

Trace Viewer #

测试追踪查看器:

bash
npx playwright show-trace trace.zip

实用工具 #

Playwright CLI #

bash
# 运行测试
npx playwright test

# 运行特定测试
npx playwright test login.spec.ts

# UI 模式
npx playwright test --ui

# 生成代码
npx playwright codegen

# 查看报告
npx playwright show-report

# 安装浏览器
npx playwright install

# 检查系统依赖
npx playwright install-deps

Playwright Docker 镜像 #

dockerfile
FROM mcr.microsoft.com/playwright:v1.40.0-jammy

WORKDIR /app

COPY package*.json ./
RUN npm ci

COPY . .

RUN npx playwright install

CMD ["npx", "playwright", "test"]

Playwright Docker Compose #

yaml
version: '3'
services:
  playwright:
    image: mcr.microsoft.com/playwright:v1.40.0-jammy
    volumes:
      - .:/app
    working_dir: /app
    command: npx playwright test

社区资源 #

官方资源 #

示例项目 #

学习资源 #

扩展开发 #

创建自定义夹具 #

typescript
// fixtures/custom.ts
import { test as base } from '@playwright/test';

type CustomFixtures = {
  customHelper: CustomHelper;
};

class CustomHelper {
  constructor(private page: Page) {}
  
  async doSomething() {
    // 自定义逻辑
  }
}

export const test = base.extend<CustomFixtures>({
  customHelper: async ({ page }, use) => {
    const helper = new CustomHelper(page);
    await use(helper);
  },
});

创建自定义匹配器 #

typescript
// matchers/custom.ts
import { expect } from '@playwright/test';

expect.extend({
  async toBeWithinRange(received: number, floor: number, ceiling: number) {
    const pass = received >= floor && received <= ceiling;
    return {
      message: () => `expected ${received} ${pass ? 'not ' : ''}to be within range ${floor} - ${ceiling}`,
      pass,
    };
  },
});

// 使用
test('自定义匹配器', async ({ page }) => {
  const count = await page.locator('.item').count();
  expect(count).toBeWithinRange(1, 10);
});

最佳实践 #

1. 选择合适的报告器 #

typescript
// 开发环境
export default defineConfig({
  reporter: [['list']],
});

// CI 环境
export default defineConfig({
  reporter: [
    ['github'],
    ['html'],
    ['junit', { outputFile: 'junit.xml' }],
  ],
});

2. 使用云服务扩展能力 #

typescript
// 本地开发
export default defineConfig({
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
  ],
});

// CI/云服务
export default defineConfig({
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { 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 12'] } },
  ],
});

3. 集成到开发工作流 #

json
// package.json
{
  "scripts": {
    "test": "playwright test",
    "test:ui": "playwright test --ui",
    "test:debug": "playwright test --debug",
    "test:codegen": "playwright codegen",
    "test:report": "playwright show-report"
  }
}

总结 #

Playwright 拥有丰富的生态系统,可以根据项目需求选择合适的工具和库。建议:

  1. 使用 VS Code 插件提高开发效率
  2. 选择合适的报告器展示测试结果
  3. 利用云服务扩展测试能力
  4. 参与社区获取最新信息

现在你已经完成了 Playwright 文档的学习,可以开始实践了!

最后更新:2026-03-28