如何在 Next.js 中設定 Playwright

Playwright 是一個測試框架,可讓您透過單一 API 自動化 Chromium、Firefox 和 WebKit。您可以用它來編寫 端對端測試 (E2E)。本指南將展示如何在 Next.js 中設定 Playwright 並撰寫您的第一個測試。

快速開始

最快速的方式是使用 create-next-app 搭配 with-playwright 範例。這將建立一個已配置 Playwright 的 Next.js 專案。

終端機
npx create-next-app@latest --example with-playwright with-playwright-app

手動設定

要安裝 Playwright,請執行以下指令:

終端機
npm init playwright
# 或
yarn create playwright
# 或
pnpm create playwright

這將引導您完成一系列提示,為您的專案設定和配置 Playwright,包括新增 playwright.config.ts 檔案。請參考 Playwright 安裝指南 以獲取逐步指南。

建立您的第一個 Playwright E2E 測試

建立兩個新的 Next.js 頁面:

app/page.tsx
import Link from 'next/link'

export default function Page() {
  return (
    <div>
      <h1>首頁</h1>
      <Link href="/about">關於</Link>
    </div>
  )
}
app/about/page.tsx
import Link from 'next/link'

export default function Page() {
  return (
    <div>
      <h1>關於</h1>
      <Link href="/">首頁</Link>
    </div>
  )
}

接著,新增一個測試來驗證您的導航是否正常運作:

tests/example.spec.ts
import { test, expect } from '@playwright/test'

test('應導航至關於頁面', async ({ page }) => {
  // 從首頁開始 (baseURL 透過 playwright.config.ts 中的 webServer 設定)
  await page.goto('http://localhost:3000/')
  // 找到文字為 '關於' 的元素並點擊
  await page.click('text=關於')
  // 新網址應為 "/about" (baseURL 會在此處使用)
  await expect(page).toHaveURL('http://localhost:3000/about')
  // 新頁面應包含一個 h1 標題為 "關於"
  await expect(page.locator('h1')).toContainText('關於')
})

須知:您可以使用 page.goto("/") 取代 page.goto("http://localhost:3000/"),只要在 playwright.config.ts 設定檔案 中新增 "baseURL": "http://localhost:3000"

執行您的 Playwright 測試

Playwright 會模擬使用者透過三種瀏覽器 (Chromium、Firefox 和 Webkit) 瀏覽您的應用程式,這需要您的 Next.js 伺服器正在執行。我們建議針對生產環境程式碼執行測試,以更貼近應用程式的實際行為。

執行 npm run buildnpm run start,然後在另一個終端視窗中執行 npx playwright test 來執行 Playwright 測試。

須知:或者,您可以使用 webServer 功能讓 Playwright 啟動開發伺服器並等待其完全就緒。

在持續整合 (CI) 環境執行 Playwright

Playwright 預設會在 無頭模式 下執行測試。要安裝所有 Playwright 相依套件,請執行 npx playwright install-deps

您可以從以下資源了解更多關於 Playwright 與持續整合的資訊:

On this page