跳到内容

使用 Next.js 设置 Playwright

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

快速开始

最快的入门方法是使用带有 with-playwright 示例create-next-app。这将创建一个配置了 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 页面

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('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')
})

须知:如果您将 "baseURL": "https://127.0.0.1:3000" 添加到 playwright.config.ts 配置文件,则可以使用 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 和持续集成的更多信息