跳到内容

使用 Next.js 设置 Playwright

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

快速开始

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

终端
npx create-next-app@latest --example with-playwright with-playwright-app

手动设置

要安装 Playwright,运行以下命令

终端
npm init playwright
# or
yarn create playwright
# or
pnpm create playwright

这将引导你完成一系列提示,以设置和配置你的项目的 Playwright,包括添加一个 playwright.config.ts 文件。请参考 Playwright 安装指南 获取分步指南。

创建你的第一个 Playwright E2E 测试

创建两个新的 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 }) => {
  // Start from the index page (the baseURL is set via the webServer in the playwright.config.ts)
  await page.goto('https://127.0.0.1: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('https://127.0.0.1:3000/about')
  // The new page should contain an h1 with "About"
  await expect(page.locator('h1')).toContainText('About')
})

小贴士:如果你在 playwright.config.ts 配置文件 中添加了 "baseURL": "https://127.0.0.1:3000",你可以使用 page.goto("/") 而不是 page.goto("https://127.0.0.1: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 和持续集成的知识