添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Zenn
🕌

Playwright を使用した E2E テスト (feat. Cypress)

に公開

こんにちは、クラウドエース フロントエンドディビジョン所属の金です。
本記事では End to End テスト (E2E テスト) のツールの一つである Playwright について基本的な機能を中心にご紹介します。

E2E (エンドツーエンド) テストとは? | CircleCI

  • はじめてのクロスブラウザーテスト - ウェブ開発を学ぶ | MDN

    Playwright 公式ドキュメント の原文より:

    Playwright framework is an open-source, Nodejs-based automation framework for end-to-end testing. It was developed and maintained by Microsoft. Its main goal is to run across the major browser engines – Chromium, Webkit, and Firefox.

  • Cypress
  • Selenium
  • Installation | Playwright

    インストールは、以下のように作業ディレクトリ配下で実施します。

    $ # npm を使う場合
    $ npm init playwright@latest
    $ # yarn を使う場合
    $ yarn create playwright
    $ # pnpm を使う場合
    $ pnpm create playwright
    

    インストール後、以下のようなファイルが作成されます。

    playwright.config.ts
    tests/
     example.spec.ts
    

    テスト実行コマンド

    $ # ディレクトリ配下の全てにテストを実行するコマンド
    $ npx playwright test
    $ # UI modeでテストを実行するコマンド
    $ npx playwright test --ui
    

    Locators | Playwright

    ほとんどのテストは、ページへの URL 移動から始まります。
    その後、以下のようなメソッドを使用してページやフレームでアクションを実行する要素ロケータが返されます。

  • CI GitHub Actions | Playwright

    設定ファイルは、以下のように YAML 形式で記述します。

    name: Playwright Tests  #タイトル名を作成
      # 指定したブランチで PR & PUSH イベントが発生したら 自動で実行
      push:
        branches: [ main, master ]
      pull_request:
        branches: [ main, master ]
    jobs:
      test:
        timeout-minutes: 60
        # 実行環境設定
        runs-on: ubuntu-latest
        steps:
        - uses: actions/checkout@v3
        - uses: actions/setup-node@v3
          with:
            node-version: 18
        # npm package インストール
        - name: Install dependencies
          run: npm ci
          # 以下のように env ファイルを指定できる(下の process.env.CI の例を参考)
          env:
            CI: true
        # Playwright E2E test で使う Browser を設定
        - name: Install Playwright Browsers
          run: npx playwright install --with-deps
        # Playwright E2E test 実行
        - name: Run Playwright tests
          run: npx playwright test
        - uses: actions/upload-artifact@v3
          if: always()
          with:
            name: playwright-report
            path: playwright-report/
            retention-days: 30
    

    playwright.config.ts ファイルに以下のように設定することでテスト実行の分岐処理も可能です。
    process.env.CI の例

     /* Run your local dev server before starting the tests */
      webServer: process.env.CI
            { // web server
              command: 'npm run dev',
              port: 3000,
            { // proxy server
              command: 'cd proxy-server && npm run dev',
              port: 8080,
        : undefined,
    
  •