跳到主要內容

使用 Next.js 設定 Playwright

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

快速開始

最快開始使用的方式是使用 create-next-appwith-playwright 範例。這將建立一個已配置 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,包括新增 playwright.config.ts 檔案。請參閱Playwright 安裝指南 以取得逐步指南。

建立您的第一個 Playwright E2E 測試

建立兩個新的 Next.js 頁面

app/page.tsx
import Link from 'next/link'
 
export default function Page() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}
app/about/page.tsx
import Link from 'next/link'
 
export default function Page() {
  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('https://127.0.0.1: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('https://127.0.0.1:3000/about')
  // The new page should contain an h1 with "About"
  await expect(page.locator('h1')).toContainText('About')
})

小知識:如果您將 "baseURL": "https://127.0.0.1:3000" 新增至 playwright.config.ts 設定檔,則可以使用 page.goto("/") 而非 page.goto("https://127.0.0.1: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 和持續整合的資訊