跳到內容
指南測試Playwright

如何使用 Next.js 設定 Playwright

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

快速入門

最快的入門方法是使用 create-next-appwith-playwright 示例。這將建立一個完整的 Next.js 專案,並配置好 Playwright。

終端
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 頁面

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

須知:如果你在 playwright.config.ts 配置檔案中新增 "baseURL": "https://:3000",則可以使用 page.goto("/") 而不是 page.goto("https://: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 和持續整合的資訊