Playwright Fixtures とパラメータ化

この章では、Playwright の Fixture メカニズム、カスタム Fixture の作成方法、パラメータ化テストのテクニックを紹介します。


Fixture とは

Fixture(フィクスチャ)は、Playwright のテスト関数パラメータに対する依存性注入のメカニズムです。

各テストはパラメータを分割代入して必要な Fixture(例:{ page })、Playwright が作成とクリーンアップを担当します。

例

// page と context は組み込み Fixture
test('組み込み Fixture を使用', async ({ page, context }) => {
  // Playwright が page と context を自動的に作成
  // テスト終了後に自動クリーンアップ
  await page.goto('https://www.example.com/');
});

組み込み Fixture 早見表

Fixture型説明
pagePage独立したブラウザタブ
contextBrowserContextブラウザコンテキスト
browserBrowserブラウザインスタンス
browserNamestring現在のブラウザ名
requestAPIRequestContextHTTP リクエストクライアント

カスタム Fixture

を使用してtest.extend()カスタム Fixture を作成すると、追加の依存関係を注入したり、組み込み Fixture をオーバーライドしたりできます。

例

// ファイルパス:tests/fixtures.ts
import { test as base, expect } from '@playwright/test';

// カスタム Fixture の型を定義
type MyFixtures = {
  todoPage: { goto: () => Promise<void>; addTodo: (text: string) => Promise<void> };
  authenticatedPage: any;
};

export const test = base.extend<MyFixtures>({
  // カスタム Fixture:Todo ページオブジェクト
  todoPage: async ({ page }, use) => {
    // 作成
    const todoPage = {
      goto: async () => {
        await page.goto('https://demo.playwright.dev/todomvc');
      },
      addTodo: async (text: string) => {
        await page.getByPlaceholder('What needs to be done?').fill(text);
        await page.keyboard.press('Enter');
      },
    };
    // テストに注入
    await use(todoPage);
    // クリーンアップロジック(必要な場合)
  },

  // カスタム Fixture:認証済みページ
  authenticatedPage: async ({ browser }, use) => {
    const context = await browser.newContext({
      storageState: 'playwright/.auth/user.json',
    });
    const page = await context.newPage();
    await use(page);
    await context.close();
  },
});

export { expect };

カスタム Fixture の使用

例

// ファイルパス:tests/todo.spec.ts
import { test, expect } from './fixtures';

test('Todo を追加', async ({ todoPage }) => {
  await todoPage.goto();
  await todoPage.addTodo('Playwright を学ぶ');
  await todoPage.addTodo('Fixtures をマスターする');
  // 検証...
});

Fixture のスコープ

Fixture には3つのスコープがあり、scopeオプションで制御されます。

スコープ值ライフサイクル
テストレベル(デフォルト)scope: 'test'各テストごとに1回作成
Worker レベルscope: 'worker'各 Worker プロセスで1回作成され、同じ Worker 内のすべてのテストで共有

例

// Worker レベル Fixture(同じ Worker 内のすべてのテストで共有)
const test = base.extend({
  sharedResource: [async ({}, use) => {
    const resource = await createExpensiveResource();
    await use(resource);
    await resource.dispose();
  }, { scope: 'worker' }],  // 配列構文に注意
});

Worker レベル Fixture は同じ Worker プロセス内の複数のテスト間で共有され、データベース接続など作成コストの高いリソースに適しています。


組み込み Fixture のオーバーライド

組み込み Fixture をオーバーライドして、デフォルトの動作を変更できます。

例

const test = base.extend({
  // 組み込みの page fixture をオーバーライドし、デフォルトのビューポートを変更
  page: async ({ baseURL, page }, use) => {
    await page.setViewportSize({ width: 1920, height: 1080 });
    await use(page);
  },

  // storageState をオーバーライド
  storageState: 'playwright/.auth/admin.json',
});

Fixture の自動クリーンアップ

Fixture のクリーンアップロジックはuse()の呼び出しの後に実行され、afterEachの効果に似ています。

例

const test = base.extend({
  tempUser: async ({ request }, use) => {
    // 一時ユーザーを作成
    const resp = await request.post('/api/users', {
      data: { name: 'temp_' + Date.now() },
    });
    const user = await resp.json();

    // テストに注入
    await use(user);

    // 自動クリーンアップ:一時ユーザーを削除
    await request.delete(`/api/users/${user.id}`);
  },
});

パラメータ化テスト

Playwright には組み込みのパラメータ化メカニズムはありませんが、ループを使用してテストを動的に生成できます。

例

// データ駆動テスト
const testCases = [
  { username: 'admin', password: 'admin123', expected: 'ダッシュボード' },
  { username: 'user',  password: 'user123',  expected: '個人センター' },
  { username: 'guest', password: 'guest123', expected: 'ビジターページ' },
];

for (const { username, password, expected } of testCases) {
  test(`ユーザー ${username}ログイン後に $ が表示される{expected}`, async ({ page }) => {
    await page.goto('/login');
    await page.getByLabel('ユーザー名').fill(username);
    await page.getByLabel('パスワード').fill(password);
    await page.getByRole('button', { name: 'ログイン' }).click();
    await expect(page.getByText(expected)).toBeVisible();
  });
}

テストアノテーション(Annotations)

アノテーションはテストにメタデータを追加するために使用され、レポーターで表示およびフィルタリングできます。

例

test('アノテーション付きテスト', async ({ page }) => {
  // アノテーションを追加(テスト関数の本体内)
  test.info().annotations.push({
    type: 'issue',
    description: 'https://github.com/サンプル/bug/123',
  });
  test.info().annotations.push({
    type: 'description',
    description: 'このテストはログインフローのすべての分岐をカバーしています',
  });

  // テストロジック...
});

// Tag を使用(テスト名内)
test('クイックスモークテスト @smoke @critical', async ({ page }) => {
  // npx playwright test --grep "@smoke" でこのテストのみを実行できます
});
その他の拡張