如何在 Next.js 中设置 Playwright

Playwright 是一个测试框架,允许您通过单一 API 自动化操作 Chromium、Firefox 和 WebKit 浏览器。您可以用它编写端到端测试 (E2E Testing)。本指南将展示如何在 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 端到端测试

创建两个新的 Next.js 页面:

pages/index.ts
import Link from 'next/link'

export default function Home() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}
pages/about.ts
import Link from 'next/link'

export default function About() {
  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 }) => {
  // 从首页开始(baseURL 已在 playwright.config.ts 中通过 webServer 设置)
  await page.goto('http://localhost:3000/')
  // 找到包含文本 'About' 的元素并点击
  await page.click('text=About')
  // 新 URL 应为 "/about"(使用了 baseURL)
  await expect(page).toHaveURL('http://localhost:3000/about')
  // 新页面应包含带有 "About" 文本的 h1 元素
  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 和持续集成的资源:

On this page