跳至內容

使用 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,包括新增一個 playwright.config.ts 檔案。請參考 Playwright 安裝指南 以取得逐步指南。

建立您的第一個 Playwright 端對端測試

建立兩個新的 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')
})

注意事項:

如果您在 playwright.config.ts 設定檔 中新增 "baseURL": "https://127.0.0.1:3000",則可以使用 page.goto("/") 來代替 page.goto("https://127.0.0.1:3000/")

執行 Playwright 測試

Playwright 會使用三種瀏覽器:Chromium、Firefox 和 Webkit 來模擬使用者操作您的應用程式,這需要您的 Next.js 伺服器正在運行。我們建議您針對您的 production code 執行測試,以便更準確地模擬您的應用程式行為。

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

注意事項:或者,您可以使用 webServer 功能,讓 Playwright 啟動開發伺服器並等待其完全可用。

在持續整合 (CI) 上執行 Playwright

Playwright 預設會以 無頭模式 執行您的測試。要安裝所有 Playwright dependencies,請執行 npx playwright install-deps

您可以從以下資源進一步了解 Playwright 和持續整合