如何在 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 create next-app --example with-playwright with-playwright-appnpx create-next-app@latest --example with-playwright with-playwright-appyarn create next-app --example with-playwright with-playwright-appbun create next-app --example with-playwright with-playwright-app手动设置#
要安装 Playwright,请运行以下命令:
pnpm create playwrightnpm init playwrightyarn create playwrightbun 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 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 }) => {
// 从索引页开始(baseURL 通过 playwright.config.ts 中的 webServer 设置)
await page.goto('http://localhost:3000/')
// 找到文本为 'About' 的元素并点击它
await page.getByRole('link', { name: 'About' }).click()
// 新的 URL 应为 "/about"(此处使用了 baseURL)
await expect(page).toHaveURL('http://localhost:3000/about')
// 新页面应包含带有 "About" 的 h1
await expect(page.getByRole('heading', { level: 1 })).toContainText('About')
})小知识:如果你在
playwright.config.ts配置文件中添加"baseURL": "http://localhost:3000",就可以使用page.goto("/")代替page.goto("http://localhost:3000/")。
测试由 Cache Components 保留的路由#
使用 Cache Components 时,客户端导航后先前的页面会继续隐藏在 DOM 中。测试定位器(locator)可能会匹配可见路由和隐藏路由中的元素。请使用感知可见性的定位器。有关示例和定位器行为,请参阅测试保留的 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 和持续集成的信息:
测试即时导航#
如果你使用 Cache Components,@next/playwright 中的 instant() 辅助函数可让你在导航后立即断言哪些内容可见(在动态内容流式进入之前)。该辅助函数处于实验阶段。
小知识: 该回调测试的是你可以在 Navigation Inspector 中通过导航时暂停(Pause on navigations)检查的同一 UI。当回调结束时,
instant()会解除暂停,就像点击继续(Resume)一样。
安装辅助函数#
按上述步骤设置 Playwright 后,安装 @next/playwright:
pnpm add -D @next/playwrightnpm install -D @next/playwrightyarn add -D @next/playwrightbun add -D @next/playwright启用 Cache Components 后,你可以在 next dev 中直接使用该辅助函数,无需额外配置。对于 next build 和 next start,请按照生产构建中的说明启用测试 API。
初始页面加载#
在初始页面加载或重新加载时,instant() 可让你在动态服务端内容保持暂停的状态下测试路由的静态外壳(shell):
import { expect, test } from '@playwright/test'
import { instant } from '@next/playwright'
test('shows the initial shell', async ({ page, baseURL }) => {
await instant(
page,
async () => {
await page.goto('/dashboard')
await expect(
page.getByRole('heading', { name: 'Dashboard' })
).toBeVisible()
},
{ baseURL }
)
})传入 Playwright 配置的 baseURL,以便辅助函数能在 page.goto() 之前设置暂停。在回调内部,对静态内容和加载状态进行断言。instant() 返回后,动态内容可以流式进入,你就可以对完成的页面进行断言。
客户端导航#
在客户端导航中,instant() 可让你测试目标页面的预获取 UI。在回调内部点击一个链接:
import { expect, test } from '@playwright/test'
import { instant } from '@next/playwright'
test('shows the dashboard shell', async ({ page }) => {
await page.goto('/')
await instant(page, async () => {
await page.getByRole('link', { name: 'Dashboard' }).click()
await page.waitForURL((url) => url.pathname === '/dashboard')
await expect(page.getByRole('heading', { name: 'Dashboard' })).toBeVisible()
})
})预获取的 UI 可能包含比初始静态外壳更多的内容,具体取决于链接的预获取配置。如果页面的所有内容都已缓存或被预获取,你可以在回调内对整个页面进行断言。在 instant() 返回后检查任何剩余的动态内容。
在对目标页面的 UI 进行断言之前,请先等待目标 URL。否则,在导航完成之前,共享的选择器可能会匹配到源页面。如果动态内容暂停时目标页面无法出现,URL 等待将超时,测试会失败。
Cache Components 可以将先前的页面隐藏保留在 DOM 中。请使用默认排除隐藏元素的 getByRole,或使用 .filter({ visible: true }) 过滤其他定位器。请参阅测试保留的 UI。
生产构建#
启用 Cache Components 后,测试 API 在 next dev 中会自动可用。要测试生产构建,请仅为测试服务器启用 experimental.exposeTestingApiInProductionBuild:
import type { NextConfig } from 'next'
const exposeTestingApi = process.env.EXPOSE_TESTING_API === '1'
const nextConfig: NextConfig = {
cacheComponents: true,
experimental: {
exposeTestingApiInProductionBuild: exposeTestingApi,
},
}
export default nextConfigconst exposeTestingApi = process.env.EXPOSE_TESTING_API === '1'
/** @type {import('next').NextConfig} */
const nextConfig = {
cacheComponents: true,
experimental: {
exposeTestingApiInProductionBuild: exposeTestingApi,
},
}
module.exports = nextConfig在构建和启动测试服务器时设置 EXPOSE_TESTING_API=1。
EXPOSE_TESTING_API=1 pnpm build
EXPOSE_TESTING_API=1 pnpm start在面向用户的生产部署中请保持此选项为禁用状态。
参数#
function instant<T>(
page: Page,
callback: () => Promise<T>,
options?: { baseURL?: string }
): Promise<T>| 参数 | 描述 |
|---|---|
page | 要导航和检查的 Playwright 页面。 |
callback | 一个包含导航操作和断言的异步函数。动态服务端内容会一直保持暂停,直到它执行完毕。 |
options.baseURL | 应用程序的 URL。在首次页面加载前必需。页面加载后默认为 page.url()。 |
返回的 Promise 会以回调的结果兑现,或以回调的错误拒绝。当回调结束时(包括断言失败时),辅助函数都会解除暂停。
限制#
- 这些测试假定缓存已预热,并检查在动态服务端内容到达之前可以渲染哪些 UI。它们不测量冷缓存加载时间或预获取延迟。
- 暂停作用于浏览器上下文。在同一上下文中嵌套或并发调用
instant()会抛出错误。并发测试请使用独立的上下文。 - 暂停会阻止动态服务端内容,但允许 hydration(水合)继续进行。当断言运行时,不需要该内容的 Client Component 可能已经可见。
- 暂停使用一个作用域为主机名(而非端口)的 cookie。请勿在同一个浏览器上下文中将其用于同一主机名下的不同应用程序。
搜索参数更新#
仅更改搜索参数会更新现有页面。如果该更新在某个未被预获取的数据上挂起(suspend),React 可以保持先前内容可见,而不显示回退内容。
instant() 会一直保留该数据直到回调结束。因此,即使在普通导航正常工作的情况下,在回调内等待更新后的 URL 或内容也可能超时。如果保留内容是预期的体验,请在暂停状态下测试待处理反馈,并在不暂停的情况下测试完成的更新。当所需内容已经可用时,搜索参数更新仍然可以是即时的。