playwright-testing
Playwrightを使ったE2Eテストを支援するスキルです。Page Objectsパターンの実装、クロスブラウザ対応、CI/CDパイプラインへの組み込みまで、テスト設計から自動化環境の構築を一貫してサポートします。
description の原文を見る
E2E testing with Playwright - Page Objects, cross-browser, CI/CD
SKILL.md 本文
Playwright E2E テスティングスキル
Web アプリケーションの Playwright による包括的なエンドツーエンドテスト - クロスブラウザ対応、高速、信頼性の高い。
参考資料: Playwright Best Practices | Playwright Docs | Better Stack Guide
セットアップ
インストール
# 新規プロジェクト
npm init playwright@latest
# 既存プロジェクト
npm install -D @playwright/test
npx playwright install
設定
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: [
['html'],
['list'],
process.env.CI ? ['github'] : ['line'],
],
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry',
screenshot: 'only-on-failure',
video: 'retain-on-failure',
},
projects: [
// 認証セットアップ - すべてのテストの前に一度実行
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
dependencies: ['setup'],
},
{
name: 'firefox',
use: { ...devices['Desktop Firefox'] },
dependencies: ['setup'],
},
{
name: 'webkit',
use: { ...devices['Desktop Safari'] },
dependencies: ['setup'],
},
// モバイルビューポート
{
name: 'mobile-chrome',
use: { ...devices['Pixel 5'] },
dependencies: ['setup'],
},
{
name: 'mobile-safari',
use: { ...devices['iPhone 12'] },
dependencies: ['setup'],
},
],
// テスト実行前に開発サーバーを起動
webServer: {
command: 'npm run dev',
url: 'http://localhost:3000',
reuseExistingServer: !process.env.CI,
timeout: 120 * 1000,
},
});
プロジェクト構成
project/
├── e2e/
│ ├── fixtures/
│ │ ├── auth.fixture.ts # 認証フィクスチャ
│ │ └── test.fixture.ts # フィクスチャ付き拡張テスト
│ ├── pages/
│ │ ├── base.page.ts # ベースページオブジェクト
│ │ ├── login.page.ts # ログインページオブジェクト
│ │ ├── dashboard.page.ts # ダッシュボードページオブジェクト
│ │ └── index.ts # すべてのページをエクスポート
│ ├── tests/
│ │ ├── auth.spec.ts # 認証テスト
│ │ ├── dashboard.spec.ts # ダッシュボードテスト
│ │ └── checkout.spec.ts # チェックアウトフロータスト
│ ├── utils/
│ │ ├── helpers.ts # テストヘルパー
│ │ └── test-data.ts # テストデータファクトリ
│ └── auth.setup.ts # グローバル認証セットアップ
├── playwright.config.ts
└── .auth/ # 保存済み認証状態 (gitignored)
ロケーターの戦略(優先順位順)
ユーザーがページとやり取りする方法を反映したロケーターを使用します:
// ✅ 最良: ロールベース(アクセス可能、堅牢)
page.getByRole('button', { name: 'Submit' })
page.getByRole('textbox', { name: 'Email' })
page.getByRole('link', { name: 'Sign up' })
page.getByRole('heading', { name: 'Welcome' })
// ✅ 良好: ユーザーに見える文字列
page.getByLabel('Email address')
page.getByPlaceholder('Enter your email')
page.getByText('Welcome back')
page.getByTitle('Profile settings')
// ✅ 良好: テスト ID(安定、明示的)
page.getByTestId('submit-button')
page.getByTestId('user-avatar')
// ⚠️ 避ける: CSS セレクタ(脆い)
page.locator('.btn-primary')
page.locator('#submit')
// ❌ 絶対禁止: XPath(非常に脆い)
page.locator('//div[@class="container"]/button[1]')
ロケーターのチェーン
// 特定のセクションに絞り込む
const form = page.getByRole('form', { name: 'Login' });
await form.getByRole('textbox', { name: 'Email' }).fill('user@example.com');
await form.getByRole('button', { name: 'Submit' }).click();
// リスト内でフィルタリング
const productCard = page.getByTestId('product-card')
.filter({ hasText: 'Pro Plan' });
await productCard.getByRole('button', { name: 'Buy' }).click();
ページオブジェクトモデル
ベースページ
// e2e/pages/base.page.ts
import { Page, Locator } from '@playwright/test';
export abstract class BasePage {
constructor(protected page: Page) {}
async navigate(path: string = '/') {
await this.page.goto(path);
}
async waitForPageLoad() {
await this.page.waitForLoadState('networkidle');
}
// 共通要素
get header() {
return this.page.getByRole('banner');
}
get footer() {
return this.page.getByRole('contentinfo');
}
// 共通アクション
async clickNavLink(name: string) {
await this.header.getByRole('link', { name }).click();
}
}
ページの実装
// e2e/pages/login.page.ts
import { Page, expect } from '@playwright/test';
import { BasePage } from './base.page';
export class LoginPage extends BasePage {
readonly emailInput: Locator;
readonly passwordInput: Locator;
readonly submitButton: Locator;
readonly errorMessage: Locator;
constructor(page: Page) {
super(page);
this.emailInput = page.getByLabel('Email');
this.passwordInput = page.getByLabel('Password');
this.submitButton = page.getByRole('button', { name: 'Sign in' });
this.errorMessage = page.getByRole('alert');
}
async goto() {
await this.navigate('/login');
}
async login(email: string, password: string) {
await this.emailInput.fill(email);
await this.passwordInput.fill(password);
await this.submitButton.click();
}
async expectError(message: string) {
await expect(this.errorMessage).toContainText(message);
}
async expectLoggedIn() {
await expect(this.page).toHaveURL(/.*dashboard/);
}
}
// e2e/pages/dashboard.page.ts
import { Page, Locator, expect } from '@playwright/test';
import { BasePage } from './base.page';
export class DashboardPage extends BasePage {
readonly welcomeHeading: Locator;
readonly userMenu: Locator;
readonly logoutButton: Locator;
constructor(page: Page) {
super(page);
this.welcomeHeading = page.getByRole('heading', { name: /welcome/i });
this.userMenu = page.getByTestId('user-menu');
this.logoutButton = page.getByRole('button', { name: 'Logout' });
}
async goto() {
await this.navigate('/dashboard');
}
async logout() {
await this.userMenu.click();
await this.logoutButton.click();
}
async expectWelcome(name: string) {
await expect(this.welcomeHeading).toContainText(name);
}
}
すべてのページをエクスポート
// e2e/pages/index.ts
export { BasePage } from './base.page';
export { LoginPage } from './login.page';
export { DashboardPage } from './dashboard.page';
認証
グローバル認証セットアップ
// e2e/auth.setup.ts
import { test as setup, expect } from '@playwright/test';
import path from 'path';
const authFile = path.join(__dirname, '../.auth/user.json');
setup('authenticate', async ({ page }) => {
// ログインページに移動
await page.goto('/login');
// テスト用認証情報でログイン
await page.getByLabel('Email').fill(process.env.TEST_USER_EMAIL!);
await page.getByLabel('Password').fill(process.env.TEST_USER_PASSWORD!);
await page.getByRole('button', { name: 'Sign in' }).click();
// 認証完了を待つ
await expect(page).toHaveURL(/.*dashboard/);
// 再利用用に認証状態を保存
await page.context().storageState({ path: authFile });
});
テストで認証を使用する
// playwright.config.ts
export default defineConfig({
projects: [
{ name: 'setup', testMatch: /.*\.setup\.ts/ },
{
name: 'chromium',
use: {
...devices['Desktop Chrome'],
storageState: '.auth/user.json',
},
dependencies: ['setup'],
},
],
});
認証なしでテストする
// e2e/tests/public.spec.ts
import { test } from '@playwright/test';
// 認証をスキップするようにオーバーライド
test.use({ storageState: { cookies: [], origins: [] } });
test('homepage loads for anonymous users', async ({ page }) => {
await page.goto('/');
await expect(page.getByRole('heading', { name: 'Welcome' })).toBeVisible();
});
テストの作成
基本的なテスト構造
// e2e/tests/auth.spec.ts
import { test, expect } from '@playwright/test';
import { LoginPage } from '../pages';
test.describe('Authentication', () => {
test.beforeEach(async ({ page }) => {
// ログインテスト用に保存された認証をスキップ
await page.context().clearCookies();
});
test('successful login redirects to dashboard', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login('user@example.com', 'password123');
await loginPage.expectLoggedIn();
});
test('invalid credentials show error', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login('wrong@example.com', 'wrongpass');
await loginPage.expectError('Invalid email or password');
});
test('empty form shows validation errors', async ({ page }) => {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.submitButton.click();
await expect(page.getByText('Email is required')).toBeVisible();
await expect(page.getByText('Password is required')).toBeVisible();
});
});
ユーザーフローテスト
// e2e/tests/checkout.spec.ts
import { test, expect } from '@playwright/test';
test.describe('Checkout Flow', () => {
test('complete purchase flow', async ({ page }) => {
// 1. 商品を閲覧
await page.goto('/products');
await page.getByTestId('product-card')
.filter({ hasText: 'Pro Plan' })
.getByRole('button', { name: 'Add to cart' })
.click();
// 2. カートを表示
await page.getByRole('link', { name: 'Cart' }).click();
await expect(page.getByText('Pro Plan')).toBeVisible();
await expect(page.getByTestId('cart-total')).toContainText('$29.99');
// 3. チェックアウト
await page.getByRole('button', { name: 'Checkout' }).click();
// 4. 支払い情報を入力(Stripe テストカード使用)
const stripeFrame = page.frameLocator('iframe[name*="stripe"]');
await stripeFrame.getByPlaceholder('Card number').fill('4242424242424242');
await stripeFrame.getByPlaceholder('MM / YY').fill('12/30');
await stripeFrame.getByPlaceholder('CVC').fill('123');
// 5. 購入を完了
await page.getByRole('button', { name: 'Pay now' }).click();
// 6. 成功を確認
await expect(page).toHaveURL(/.*success/);
await expect(page.getByRole('heading', { name: 'Thank you' })).toBeVisible();
});
});
アサーション
Web ファースト アサーション(自動待機)
// ✅ これらは自動的に待機と再試行を行う
await expect(page.getByRole('button')).toBeVisible();
await expect(page.getByRole('button')).toBeEnabled();
await expect(page.getByRole('button')).toHaveText('Submit');
await expect(page).toHaveURL('/dashboard');
await expect(page).toHaveTitle(/Dashboard/);
// ❌ 手動で待機することは避ける
await page.waitForTimeout(3000); // 絶対禁止
ソフトアサーション
// アサーションが失敗してもテストを続行
await expect.soft(page.getByTestId('price')).toHaveText('$29.99');
await expect.soft(page.getByTestId('stock')).toHaveText('In Stock');
// 最後にソフトアサーションが失敗したら失敗
一般的なアサーション
// 可視性
await expect(locator).toBeVisible();
await expect(locator).toBeHidden();
await expect(locator).toBeAttached();
// テキスト内容
await expect(locator).toHaveText('exact text');
await expect(locator).toContainText('partial');
await expect(locator).toHaveValue('input value');
// 状態
await expect(locator).toBeEnabled();
await expect(locator).toBeDisabled();
await expect(locator).toBeChecked();
await expect(locator).toBeFocused();
// 数
await expect(locator).toHaveCount(5);
// ページ
await expect(page).toHaveURL('/dashboard');
await expect(page).toHaveTitle('Dashboard | App');
await expect(page).toHaveScreenshot('dashboard.png');
モッキング ネットワーク
API レスポンスをモック
test('shows error when API fails', async ({ page }) => {
// API をエラー返却にモック
await page.route('**/api/users', (route) => {
route.fulfill({
status: 500,
body: JSON.stringify({ error: 'Server error' }),
});
});
await page.goto('/users');
await expect(page.getByText('Failed to load users')).toBeVisible();
});
test('displays user data from API', async ({ page }) => {
// 成功レスポンスをモック
await page.route('**/api/users', (route) => {
route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify([
{ id: 1, name: 'John Doe', email: 'john@example.com' },
{ id: 2, name: 'Jane Doe', email: 'jane@example.com' },
]),
});
});
await page.goto('/users');
await expect(page.getByText('John Doe')).toBeVisible();
await expect(page.getByText('Jane Doe')).toBeVisible();
});
API 呼び出しを待つ
test('submits form and shows success', async ({ page }) => {
await page.goto('/contact');
// フォームに入力
await page.getByLabel('Name').fill('John');
await page.getByLabel('Email').fill('john@example.com');
await page.getByLabel('Message').fill('Hello!');
// 送信時の API 呼び出しを待つ
const responsePromise = page.waitForResponse('**/api/contact');
await page.getByRole('button', { name: 'Send' }).click();
const response = await responsePromise;
expect(response.status()).toBe(200);
await expect(page.getByText('Message sent!')).toBeVisible();
});
ビジュアルテスト
// ページ全体のスクリーンショット
await expect(page).toHaveScreenshot('homepage.png');
// 要素のスクリーンショット
await expect(page.getByTestId('chart')).toHaveScreenshot('chart.png');
// オプション付き
await expect(page).toHaveScreenshot('dashboard.png', {
maxDiffPixels: 100,
mask: [page.getByTestId('timestamp')], // 動的なコンテンツを無視
});
CI/CD 統合
GitHub Actions
# .github/workflows/e2e.yml
name: E2E Tests
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Install Playwright browsers
run: npx playwright install --with-deps chromium
- name: Run E2E tests
run: npx playwright test --project=chromium
env:
BASE_URL: ${{ secrets.STAGING_URL }}
TEST_USER_EMAIL: ${{ secrets.TEST_USER_EMAIL }}
TEST_USER_PASSWORD: ${{ secrets.TEST_USER_PASSWORD }}
- uses: actions/upload-artifact@v4
if: failure()
with:
name: playwright-report
path: playwright-report/
retention-days: 7
特定のテストを実行
# すべてのテストを実行
npx playwright test
# 特定のファイルを実行
npx playwright test e2e/tests/auth.spec.ts
# タグ付きテストを実行
npx playwright test --grep @critical
# ヘッドモードで実行(デバッグ)
npx playwright test --headed
# 特定のブラウザを実行
npx playwright test --project=chromium
# デバッグモード
npx playwright test --debug
# HTML レポートを表示
npx playwright show-report
テストデータ
ファクトリ
// e2e/utils/test-data.ts
import { faker } from '@faker-js/faker';
export const createUser = (overrides = {}) => ({
email: faker.internet.email(),
password: faker.internet.password({ length: 12 }),
name: faker.person.fullName(),
...overrides,
});
export const createProduct = (overrides = {}) => ({
name: faker.commerce.productName(),
price: faker.commerce.price({ min: 10, max: 100 }),
description: faker.commerce.productDescription(),
...overrides,
});
環境変数
# .env.test
BASE_URL=http://localhost:3000
TEST_USER_EMAIL=test@example.com
TEST_USER_PASSWORD=testpassword123
デバッグ
トレースビューアー
// 設定で失敗時に有効化
use: {
trace: 'on-first-retry',
}
// トレースを表示
npx playwright show-trace trace.zip
デバッグモード
# テストをステップ実行
npx playwright test --debug
# 特定の場所で一時停止
await page.pause(); // テストコード内
VS Code 拡張
「Playwright Test for VS Code」をインストールして以下を実現:
- エディタからテストを実行
- ブレークポイントでデバッグ
- ロケーターを視覚的に選択
- ウォッチモード
デッドリンク検出(必須)
すべてのプロジェクトに、デッドリンク検出テストを含める必要があります。 すべてのデプロイ時に実行してください。
リンク検証テスト
// e2e/tests/links.spec.ts
import { test, expect } from '@playwright/test';
const PAGES_TO_CHECK = ['/', '/about', '/pricing', '/blog', '/contact'];
test.describe('Dead Link Detection', () => {
for (const pagePath of PAGES_TO_CHECK) {
test(`no dead links on ${pagePath}`, async ({ page, request }) => {
await page.goto(pagePath);
// ページ上のすべてのリンクを取得
const links = await page.locator('a[href]').all();
const hrefs = await Promise.all(
links.map(link => link.getAttribute('href'))
);
// 内部と絶対的な外部リンクにフィルタリング
const uniqueLinks = [...new Set(hrefs.filter(Boolean))] as string[];
for (const href of uniqueLinks) {
// mailto、tel、アンカーリンクをスキップ
if (href.startsWith('mailto:') || href.startsWith('tel:') || href.startsWith('#')) {
continue;
}
// 完全な URL を構築
const url = href.startsWith('http') ? href : new URL(href, page.url()).href;
// リンクステータスをチェック
const response = await request.get(url, {
timeout: 10000,
ignoreHTTPSErrors: true,
});
expect(
response.ok(),
`Dead link found on ${pagePath}: ${href} returned ${response.status()}`
).toBeTruthy();
}
});
}
});
包括的なリンククローラー
// e2e/tests/site-links.spec.ts
import { test, expect, Page, APIRequestContext } from '@playwright/test';
interface LinkResult {
url: string;
status: number;
foundOn: string;
}
async function checkAllLinks(
page: Page,
request: APIRequestContext,
startUrl: string
): Promise<LinkResult[]> {
const visited = new Set<string>();
const results: LinkResult[] = [];
const toVisit = [startUrl];
const baseUrl = new URL(startUrl).origin;
while (toVisit.length > 0) {
const currentUrl = toVisit.pop()!;
if (visited.has(currentUrl)) continue;
visited.add(currentUrl);
try {
await page.goto(currentUrl);
const links = await page.locator('a[href]').all();
for (const link of links) {
const href = await link.getAttribute('href');
if (!href || href.startsWith('#') || href.startsWith('mailto:') || href.startsWith('tel:')) {
continue;
}
const fullUrl = href.startsWith('http') ? href : new URL(href, currentUrl).href;
// リンクをチェック
const response = await request.get(fullUrl, {
timeout: 10000,
ignoreHTTPSErrors: true,
});
results.push({
url: fullUrl,
status: response.status(),
foundOn: currentUrl,
});
// 内部リンクをキューに追加
if (fullUrl.startsWith(baseUrl) && !visited.has(fullUrl)) {
toVisit.push(fullUrl);
}
}
} catch (error) {
results.push({
url: currentUrl,
status: 0,
foundOn: 'navigation',
});
}
}
return results;
}
test('no dead links on entire site', async ({ page, request, baseURL }) => {
const results = await checkAllLinks(page, request, baseURL!);
const deadLinks = results.filter(r => r.status >= 400 || r.status === 0);
if (deadLinks.length > 0) {
console.error('Dead links found:');
deadLinks.forEach(link => {
console.error(` ${link.url} (${link.status}) - found on ${link.foundOn}`);
});
}
expect(deadLinks, `Found ${deadLinks.length} dead links`).toHaveLength(0);
});
画像リンク検証
// e2e/tests/images.spec.ts
import { test, expect } from '@playwright/test';
test('no broken images on homepage', async ({ page, request }) => {
await page.goto('/');
const images = await page.locator('img[src]').all();
for (const img of images) {
const src = await img.getAttribute('src');
if (!src) continue;
const url = src.startsWith('http') ? src : new URL(src, page.url()).href;
// データ URL をスキップ
if (url.startsWith('data:')) continue;
const response = await request.get(url);
expect(
response.ok(),
`Broken image: ${src}`
).toBeTruthy();
// 実際に画像であることを確認
const contentType = response.headers()['content-type'];
expect(
contentType?.startsWith('image/'),
`${src} is not an image (${contentType})`
).toBeTruthy();
}
});
リンク確認の CI 統合
# .github/workflows/link-check.yml
name: Link Check
on:
schedule:
- cron: '0 6 * * 1' # 毎週月曜日
push:
branches: [main]
jobs:
link-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm ci
- run: npx playwright install chromium
- run: npx playwright test e2e/tests/links.spec.ts --project=chromium
env:
BASE_URL: ${{ secrets.PRODUCTION_URL }}
アンチパターン
- ハードコードされた待機 - 自動待機アサーションの代わりに使用する
- CSS/XPath セレクタ - ロール/テキスト/testid ロケーターを使用する
- サードパーティサイトのテスト - 外部依存をモックする
- テスト間での状態共有 - 各テストは独立している必要がある
- await を逃す - ESLint ルール
no-floating-promisesを使用する - 時間ベースの不安定なテスト - 日付/時刻をモックする
- 実装の詳細のテスト - ユーザーに見える動作をテストする
- 巨大なテストファイル - フィーチャー/ページごとに分割する
クイックリファレンス
# インストール
npm init playwright@latest
# テストを実行
npx playwright test
npx playwright test --headed
npx playwright test --project=chromium
npx playwright test --grep @smoke
# デバッグ
npx playwright test --debug
npx playwright show-report
npx playwright show-trace trace.zip
# テスト生成
npx playwright codegen localhost:3000
package.json スクリプト
{
"scripts": {
"test:e2e": "playwright test",
"test:e2e:headed": "playwright test --headed",
"test:e2e:debug": "playwright test --debug",
"test:e2e:report": "playwright show-report",
"test:e2e:codegen": "playwright codegen"
}
}
ライセンス: MIT(寛容ライセンスのため全文を引用しています) · 原本リポジトリ
詳細情報
- 作者
- alinaqi
- ライセンス
- MIT
- 最終更新
- 不明
Source: https://github.com/alinaqi/claude-bootstrap / ライセンス: MIT
関連スキル
superpowers-streamer-cli
SuperPowers デスクトップストリーマーの npm パッケージをインストール、ログイン、実行、トラブルシューティングできます。ユーザーが npm から `superpowers-ai` をセットアップしたい場合、メールまたは電話でサインインもしくはアカウント作成を行いたい場合、ストリーマーを起動したい場合、表示されたコントロールリンクを開きたい場合、後で停止したい場合、またはソースコードへのアクセスなしに npm やランタイムの一般的な問題から復旧したい場合に使用します。
catc-client-ops
Catalyst Centerのクライアント操作・監視機能 - 有線・無線クライアントのリスト表示・フィルタリング、MACアドレスによる詳細なクライアント検索、クライアント数分析、時間軸での分析、SSIDおよび周波数帯によるフィルタリング、無線トラブルシューティング機能を提供します。MACアドレスやIPアドレスでのクライアント検索、サイト別やSSID別のクライアント数集計、無線周波数帯の分布分析、Wi-Fi信号の問題調査が必要な場合に活用できます。
ci-cd-and-automation
CI/CDパイプラインの設定を自動化します。ビルドおよびデプロイメントパイプラインの構築または変更時に使用できます。品質ゲートの自動化、CI内のテストランナー設定、またはデプロイメント戦略の確立が必要な場合に活用します。
shipping-and-launch
本番環境へのリリース準備を行います。本番環境へのデプロイ準備が必要な場合、リリース前チェックリストが必要な場合、監視機能の設定を行う場合、段階的なロールアウトを計画する場合、またはロールバック戦略が必要な場合に使用します。
linear-release-setup
Linear Releaseに向けたCI/CD設定を生成します。リリース追跡の設定、LinearのCIパイプライン構築、またはLinearリリースとのデプロイメント連携を実施する際に利用できます。GitHub Actions、GitLab CI、CircleCIなど複数のプラットフォームに対応しています。
tracking-application-response-times
API エンドポイント、データベースクエリ、サービスコール全体にわたるアプリケーションのレスポンスタイムを追跡・最適化できます。パフォーマンス監視やボトルネック特定の際に活用してください。「レスポンスタイムを追跡する」「API パフォーマンスを監視する」「遅延を分析する」といった表現で呼び出せます。