使用 Next.js 設定 Playwright (Setting up Playwright with Next.js)
Playwright 是一個測試框架,可讓您使用單一 API 自動化 Chromium、Firefox 和 WebKit。您可以使用它來編寫端對端 (E2E) 測試。本指南將向您展示如何使用 Next.js 設定 Playwright 並編寫您的第一個測試。
快速入門
開始使用的最快方法是使用內建 Playwright 範例的 create-next-app
with-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 端對端測試
建立兩個新的 Next.js 頁面
import Link from 'next/link'
export default function Home() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}
import Link from 'next/link'
export default function About() {
return (
<div>
<h1>About</h1>
<Link href="/">Home</Link>
</div>
)
}
然後,新增一個測試來驗證您的導航是否正常運作
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 build
和 npm run start
,然後在另一個終端機視窗中執行 npx playwright test
來執行 Playwright 測試。
注意事項:或者,您可以使用
webServer
功能,讓 Playwright 啟動開發伺服器並等待它完全可用。
在持續整合 (CI) 上執行 Playwright
Playwright 預設會以無頭模式 執行您的測試。要安裝所有 Playwright dependencies,請執行 npx playwright install-deps
。
您可以從這些資源中了解更多關於 Playwright 和持續整合的資訊
這對您有幫助嗎?