Skip to main content

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 页面:

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 { 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");
});

您需要知道:

如果在playwright.config.ts配置文件中添加了"baseURL": "http://localhost:3000",您可以使用page.goto("/")而不是page.goto("http://localhost:3000/")

运行您的 Playwright 测试

laywright 将模拟用户在您的应用中使用三个浏览器导航: 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 和持续集成的信息: