跳到内容
指南测试Playwright

如何在 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 端到端测试

创建两个新的 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://: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://:3000/about')
  // The new page should contain an h1 with "About"
  await expect(page.locator('h1')).toContainText('About')
})

须知:如果你将 "baseURL": "https://:3000" 添加到 playwright.config.ts 配置文件中,你可以使用 page.goto("/") 而不是 page.goto("https://: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 和持续集成的更多信息