2
2

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】Next.js App Router で Playwright を利用する

Posted at

はじめに

この記事では、Next.js App Router で Playwright を利用する手順を記載します。

開発環境

開発環境は以下の通りです。

  • Windows 11
  • VSCode
  • Next.js 14.2.7
  • React 18.3.1
  • TypeScript 5.5.4
  • Playwright 1.46.1

インストール

まずは Playwright をインストールします。

npm init playwright@latest

インストール開始後、いくつか質問されます。今回は以下のように回答します。

image.png

インストールが完了すると、テスト設定ファイルやテストサンプルファイルが作成されます。

image.png

テスト実行1

この時点で一度テストの動作確認をします。
以下のコマンドを実行します。

npx playwright test

成功すると、以下のように表示されます。

image.png

表示に従って、レポートを確認するコマンドを実行します。

npx playwright show-report

ブラウザ上でレポートを確認できます。

Playwright-Test-Report-Google-Chrome-2024-09-01-17-06-05.gif

テスト対象のコードを実装

次は実装したコードのテストをするため、まずはテスト対象のコードを実装します。

Home と About の2画面作成し、お互いの画面を移動できるコードを実装します。

app/page.tsx
import Link from "next/link";

export default function Home() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  );
}

app/about/page.tsx
import Link from "next/link";

export default function About() {
  return (
    <div>
      <h1>About</h1>
      <Link href="/">Home</Link>
    </div>
  );
}

ローカルサーバーを起動します。

npm run dev

Create-Next-App-Google-Chrome-2024-09-02-08-14-57.gif

テストコードを実装

先ほど実装したコードのテストコードを実装します。

Home 画面のテストでは、以下の内容を確認します。

  • タイトルが「Home」
  • 「About」リンクをクリックすると、About 画面に遷移
__tets__/e2e/page.spec.ts
import test, { expect } from "@playwright/test";

test("Home page should work as expected", async ({ page }) => {
  // Start from Home page
  await page.goto("http://localhost:3000/");
  // Find page title
  await expect(page.locator("h1")).toContainText("Home");
  // Find an element with the text 'About' and click on it
  await page.click("text=About");
  // The new URL should be "/about"
  await expect(page).toHaveURL("http://localhost:3000/about");
});

テスト実行2

実装したテストを実行します。

npx playwright test

image.png

レポートを確認します。

npx playwright show-report

今回実装したテストが成功したことを確認できます。

Playwright-Test-Report-Google-Chrome-2024-09-02-09-15-10.gif

テスト実行時、ローカルサーバーは起動しておく必要があります。

image.png

参考

2
2
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
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?