Playwright 是一个测试框架,它允许您使用单一 API 自动化控制 Chromium、Firefox 和 WebKit 浏览器。您可以使用它来编写端到端 (E2E) 测试。本指南将向您展示如何将 Playwright 与 Next.js 一起设置,并编写您的第一个测试。
最快的入门方法是使用 create-next-app 和 with-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 安装指南 以获取分步说明。
创建两个新的 Next.js 页面:
import Link from 'next/link'
export default function Page() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}import Link from 'next/link'
export default function Page() {
return (
<div>
<h1>About</h1>
<Link href="/">Home</Link>
</div>
)
}import Link from 'next/link'
export default function Home() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}import Link from 'next/link'
export default function About() {
return (
<div>
<h1>About</h1>
<Link href="/">Home</Link>
</div>
)
}然后,添加一个测试来验证您的导航是否正常工作:
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('http://localhost: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('http://localhost:3000/about')
// The new page should contain an h1 with "About"
await expect(page.locator('h1')).toContainText('About')
})须知:您可以将
page.goto("/")替代page.goto("http://localhost:3000/"),如果您将"baseURL": "http://localhost:3000"添加到playwright.config.ts配置文件 中。
Playwright 将使用三种浏览器:Chromium、Firefox 和 WebKit 模拟用户导航您的应用程序,这需要您的 Next.js 服务器正在运行。我们建议针对您的生产代码运行测试,以便更接近地模拟您的应用程序的行为方式。
运行 npm run build 和 npm run start,然后在另一个终端窗口中运行 npx playwright test 来执行 Playwright 测试。
须知:此外,您可以使用
webServer功能让 Playwright 启动开发服务器并等待其完全可用。
Playwright 默认将在 无头模式 下运行您的测试。要安装所有 Playwright 依赖项,请运行 npx playwright install-deps。
您可以从以下资源了解更多关于 Playwright 和持续集成的信息: