Menu

How to set up Playwright with Next.js

Playwright 是一个测试框架,它允许你使用单一 API 自动化测试 Chromium、Firefox 和 WebKit。你可以用它来编写端到端 (E2E) 测试。本指南将向你展示如何使用 Next.js 设置 Playwright 并编写你的第一个测试。

快速开始

最快的入门方式是使用 create-next-appwith-playwright 示例。这将创建一个已配置好 Playwright 的完整 Next.js 项目。

Terminal
npx create-next-app@latest --example with-playwright with-playwright-app

手动设置

要安装 Playwright,请运行以下命令:

Terminal
npm init playwright
# or
yarn create playwright
# or
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')
})

值得注意的是:如果你在 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 测试。

值得注意的是:或者,你可以使用 webServer 功能让 Playwright 启动开发服务器并等待它完全可用。

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

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

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