Skip to main content

使用 Playwright 配置 Next.js

Playwright 是一个测试框架,可以使用单一 API 自动化 Chromium、Firefox 和 WebKit。 您可以使用它来编写端到端(End-to-End,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>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('http://localhost: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('http://localhost:3000/about')
// The new page should contain an h1 with "About"
await expect(page.locator('h1')).toContainText('About')
})
note

如果在 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 测试。

note

您还可以使用 webServer 功能让 Playwright 启动开发服务器,并等待其完全可用。

在持续集成(CI)上运行 Playwright

Playwright 默认会在无头模式下运行您的测试。 要安装所有 Playwright 依赖项,请运行 npx playwright install-deps

您可以从以下资源了解有关 Playwright 和持续集成的更多信息: