Playwright

Microsoft が開発したクロスブラウザ E2E テストフレームワーク

テスト

Playwright とは

Playwright は、Microsoft が開発したクロスブラウザ E2E (End-to-End) テストフレームワークである。Chromium、Firefox、WebKit の 3 エンジンをサポートし、1 つのテストコードで全ブラウザをテストできる。2020 年にリリースされ、Cypress と並ぶ E2E テストの主要ツールだ。

基本的なテスト

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

test('ログインフロー', async ({ page }) => {
  await page.goto('https://example.com/login');

  await page.fill('[name="email"]', 'user@example.com');
  await page.fill('[name="password"]', 'password123');
  await page.click('button[type="submit"]');

  await expect(page).toHaveURL('/dashboard');
  await expect(page.locator('h1')).toHaveText('ダッシュボード');
});

Cypress との比較

観点 Playwright Cypress
ブラウザ Chromium, Firefox, WebKit Chromium, Firefox, WebKit (v13+)
言語 TypeScript, JavaScript, Python, Java, C# JavaScript, TypeScript
並列実行 ネイティブ対応 Cypress Cloud (有料)
マルチタブ 対応 非対応
iframe 対応 制限あり
ネットワークインターセプト 対応 対応
自動待機 対応 対応

強力な機能

自動待機 (Auto-waiting)

// Playwright は要素が表示されるまで自動的に待機する
await page.click('button#submit');  // ボタンが表示・有効になるまで待つ
await expect(page.locator('.result')).toBeVisible();  // 表示されるまで待つ

ネットワークインターセプト

// API レスポンスをモック
await page.route('**/api/users', route =>
  route.fulfill({ json: [{ id: '1', name: 'Alice' }] })
);

スクリーンショットとビデオ

// テスト失敗時に自動でスクリーンショットを保存
// playwright.config.ts
export default defineConfig({
  use: {
    screenshot: 'only-on-failure',
    video: 'retain-on-failure',
    trace: 'retain-on-failure',
  },
});

Codegen (テストコード自動生成)

npx playwright codegen https://example.com
# ブラウザが開き、操作を記録してテストコードを自動生成

CI での実行

# GitHub Actions
- name: Install Playwright
  run: npx playwright install --with-deps
- name: Run E2E tests
  run: npx playwright test
- uses: actions/upload-artifact@v4
  if: failure()
  with:
    name: playwright-report
    path: playwright-report/

さらに掘り下げるなら関連書籍が参考になる。

関連用語