在 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('關於')
})

須知

如果您在 playwright.config.ts 設定檔 中新增 "baseURL": "http://localhost:3000",就可以使用 page.goto("/") 替代 page.goto("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