3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

📌 記事の内容

  • Playwright を使って E2E(エンドツーエンド)テスト を実行するための環境構築手順
  • Google検索のテスト をサンプルに Playwright で自動テストの実行をしてみる

✅ 1. Playwright 環境構築

1-1. Node.js のインストール

  1. Node.js公式サイト から LTS版 をダウンロード
  2. インストール後、バージョン確認v18.x.xv16.x.x などが表示されればOK
    node -v
    npm -v
    

1-2. Playwright のインストール

① プロジェクトフォルダを作成

mkdir my-playwright-project
cd my-playwright-project
npm init -y

② Playwright をインストール

npm install -D @playwright/test
npx playwright install

✅ 2. プロジェクトを初期化

通常は以下のコマンドでPlaywrightの設定を自動生成できる:

npx playwright init

✅ これが動けば、そのまま進める!

❌ もし init が動かない場合は、以下の手動設定を行う。


🔹 npx playwright init が動かない場合の手動設定

2-1. playwright.config.ts を手動作成

① 設定ファイルを作成

New-Item -Path . -Name "playwright.config.ts" -ItemType "file"

② ファイルを開いて以下を記述

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

export default defineConfig({
  testDir: 'tests',
  timeout: 60000,
  use: {
    headless: true, // 👈 ブラウザを開かずに実行
    screenshot: 'on', // スクリーンショットを保存
    video: 'retain-on-failure', // 失敗時に動画を保存
  },
});

2-2. tests/ フォルダとテストファイルを作成

tests/ フォルダを作成

mkdir tests

example.spec.ts を作成

New-Item -Path tests -Name "example.spec.ts" -ItemType "file"

📌 tests/example.spec.ts に記述

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

test('Google検索テスト', async ({ page }) => {
  await page.goto('https://www.google.com');

  // 🔹 検索ボックスをクリック
  await page.getByRole('combobox', { name: '検索' }).click();

  // 🔹 検索ワードを入力
  await page.fill('textarea[name="q"]', 'Playwright');

  // 🔹 Enterキーを押して検索
  await page.press('textarea[name="q"]', 'Enter');

  // 🔹 検索結果のタイトルを確認
  await page.waitForTimeout(2000);
  await expect(page).toHaveTitle(/Playwright/);
});

✅ 3. Playwright のテストを実行

npx playwright test

成功例

 1 passed (4.1s)

スクリーンショット & 動画の確認

  • test-results/ フォルダ内の 画像(.png)や動画(.webm) を確認
  • 失敗時のスクリーンショットが自動保存される

✅ 4. Playwright のデバッグ

4-1. headless: false でブラウザを開く

playwright.config.ts を修正して、ブラウザを表示しながらテスト実行

export default defineConfig({
  use: {
    headless: false, // 👈 ここを false にする
  },
});

その後、再度実行:

npx playwright test

4-2. npx playwright codegen で正しいセレクターを取得

もし getByRoleinput[name="q"] で要素が見つからない場合は、以下を実行

npx playwright codegen https://www.google.com
  • 自動で ブラウザ + コード生成ツール が起動
  • 検索ボックスをクリックすると、適切な セレクター を取得可能
  • 取得したセレクターを example.spec.ts に反映

🎯 5. その他

🔹 スクリーンショットを手動で撮る

await page.screenshot({ path: 'screenshot.png' });

🔹 複数のブラウザでテスト

npx playwright test --browser=firefox

📝 chromium, firefox, webkit に対応

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?