在 Next.js 中配置 Playwright

Playwright 是一个测试框架,允许您通过单一 API 自动化操作 Chromium、Firefox 和 WebKit 浏览器。您可以用它编写端到端测试 (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 端到端测试

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

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

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

export default function About() {
  return (
    <div>
      <h1>关于</h1>
      <Link href="/">首页</Link>
    </div>
  )
}

然后添加测试用例来验证导航功能是否正常工作:

tests/example.spec.ts
import { test, expect } from '@playwright/test'

test('应能跳转至关于页面', async ({ page }) => {
  // 从首页开始 (baseURL 已在 playwright.config.ts 的 webServer 中设置)
  await page.goto('http://localhost:3000/')
  // 找到包含'关于'文本的元素并点击
  await page.click('text=关于')
  // 新 URL 应为 "/about" (baseURL 会在此处使用)
  await expect(page).toHaveURL('http://localhost:3000/about')
  // 新页面应包含"关于"标题
  await expect(page.locator('h1')).toContainText('关于')
})

须知:

如果您在 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