如何为 Next.js 设置 Playwright
了解如何为 Next.js 设置 Playwright 以进行端到端(E2E)测试。
Playwright 是一个测试框架,让你通过单一 API 自动化 Chromium、Firefox 和 WebKit。你可以使用它编写端到端(E2E)测试。本指南将向你展示如何为 Next.js 设置 Playwright 并编写你的第一个测试。
快速开始
最快的入门方式是使用 create-next-app 和 with-playwright 示例。这会创建一个已配置好 Playwright 的 Next.js 项目。
pnpm
pnpm create next-app --example with-playwright with-playwright-app
npm
npx create-next-app@latest --example with-playwright with-playwright-app
yarn
yarn create next-app --example with-playwright with-playwright-app
bun
bun create next-app --example with-playwright with-playwright-app
手动设置
要安装 Playwright,请运行以下命令:
pnpm
pnpm create playwright
npm
npm init playwright
yarn
yarn create playwright
bun
bun create playwright
这会引导你完成一系列提示,以便为你的项目设置和配置 Playwright,包括添加 playwright.config.ts 文件。请参阅 Playwright 安装指南 获取分步指南。
创建你的第一个 Playwright E2E 测试
创建两个新的 Next.js 页面:
import Link from 'next/link'
export default function Page() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}
import Link from 'next/link'
export default function Page() {
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('http://localhost:3000/')
// Find an element with the text 'About' and click on it
await page.getByRole('link', { name: 'About' }).click()
// 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.getByRole('heading', { level: 1 })).toContainText('About')
})
须知:
如果你将
"baseURL": "http://localhost:3000"添加到playwright.config.ts配置文件 中,你可以使用page.goto("/")代替page.goto("http://localhost:3000/")。
测试即时导航
如果你使用的是缓存组件,@next/playwright 中的 instant() 辅助函数让你可以断言导航后立即可见的内容,即在任何动态内容流式渲染之前。有关设置和示例,请参阅即时导航指南和 instant API 参考。
测试由缓存组件保留的路由
使用 Cache Components 时,客户端导航后之前的页面仍会保留在 DOM 中并处于隐藏状态。测试定位器可能同时匹配可见路由和隐藏路由中的元素。请使用能感知可见性的定位器。有关示例和定位器行为,请参阅 测试保留的 UI。
运行 Playwright 测试
Playwright 会使用三种浏览器(Chromium、Firefox 和 WebKit)模拟用户浏览你的应用,这需要你的 Next.js 服务器正在运行。我们建议针对生产代码运行测试,以更接近应用的实际行为。
运行 npm run build 和 npm run start,然后在另一个终端窗口中运行 npx playwright test 以执行 Playwright 测试。
须知:
或者,你可以使用
webServer功能,让 Playwright 启动开发服务器并等待其完全可用。
在持续集成(CI)中运行 Playwright
默认情况下,Playwright 会在无头模式下运行测试。要安装所有 Playwright 依赖项,请运行 npx playwright install-deps。
你可以通过以下资源进一步了解 Playwright 和持续集成:
进一步了解如何测试即时导航。
- 即时导航:了解如何组织你的应用以预取和预渲染更多内容,从而实现即时页面加载和客户端导航。