コンテンツへスキップ

Next.jsでのPlaywrightの設定

Playwrightは、単一のAPIを使用してChromium、Firefox、およびWebKitを自動化できるテストフレームワークです。これを使用して、**エンドツーエンド(E2E)**テストを作成できます。このガイドでは、Next.jsでPlaywrightを設定し、最初のテストを作成する方法を示します。

クイックスタート

開始する最も速い方法は、with-playwrightの例を使用してcreate-next-appを使うことです。これにより、Playwrightが構成されたNext.jsプロジェクトが作成されます。

ターミナル
npx create-next-app@latest --example with-playwright with-playwright-app

手動設定

Playwrightをインストールするには、次のコマンドを実行します。

ターミナル
npm init playwright
# or
yarn create playwright
# or
pnpm create playwright

これにより、`playwright.config.ts`ファイルを追加するなど、プロジェクトのPlaywrightを設定するためのプロンプトが表示されます。ステップバイステップガイドについては、Playwrightインストールガイドを参照してください。

最初のPlaywright E2Eテストの作成

2つの新しいNext.jsページを作成します

pages/index.ts
import Link from 'next/link'
 
export default function Home() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}
pages/about.ts
import Link from 'next/link'
 
export default function About() {
  return (
    <div>
      <h1>About</h1>
      <Link href="/">Home</Link>
    </div>
  )
}

次に、ナビゲーションが正しく機能していることを検証するテストを追加します

tests/example.spec.ts
import { test, expect } from '@playwright/test'
 
test('should navigate to the about page', async ({ page }) => {
  // Start from the index page (the baseURL is set via the webServer in the playwright.config.ts)
  await page.goto('http://localhost:3000/')
  // Find an element with the text 'About' and click on it
  await page.click('text=About')
  // The new URL should be "/about" (baseURL is used there)
  await expect(page).toHaveURL('http://localhost:3000/about')
  // The new page should contain an h1 with "About"
  await expect(page.locator('h1')).toContainText('About')
})

知っておくと良い点:

`playwright.config.ts`の設定ファイルに` "baseURL": "http://localhost:3000"`を追加する場合、`page.goto("http://localhost:3000/")`の代わりに`page.goto("/")`を使用できます。

Playwrightテストの実行

Playwrightは、Chromium、Firefox、WebKitの3つのブラウザを使用して、アプリケーションをナビゲートするユーザーをシミュレートします。これには、Next.jsサーバーが実行されている必要があります。アプリケーションの動作をより正確に反映するために、本番コードに対してテストを実行することをお勧めします。

`npm run build`と`npm run start`を実行し、別のターミナルウィンドウで`npx playwright test`を実行して、Playwrightテストを実行します。

**知っておくと良い点**: 代わりに、`webServer`機能を使用して、Playwrightが開発サーバーを起動し、完全に利用可能になるまで待機するようにすることができます。

継続的インテグレーション(CI)でのPlaywrightの実行

Playwrightはデフォルトでテストをヘッドレスモードで実行します。Playwrightのすべての依存関係をインストールするには、npx playwright install-depsを実行します。

Playwrightと継続的インテグレーションに関する詳細は、以下のリソースをご覧ください。