在 Next.js 中配置 Playwright

Last updated

Playwright 是一个测试框架,允许使用同一套 API 自动操作 Chromium、Firefox 和 WebKit。可以用它编写端到端测试。本指南介绍如何在 Next.js 中配置 Playwright,并编写第一批测试。

快速开始

最快的入门方式是通过 create-next-app 使用 with-playwright 示例,它会创建一个已经配置好 Playwright 的 Next.js 项目。

Terminal
pnpm create next-app --example with-playwright with-playwright-app

手动配置

执行以下命令安装 Playwright:

Terminal
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('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 测试

Playwright 会使用 Chromium、Firefox 和 WebKit 三种浏览器模拟用户浏览应用,因此需要保持 Next.js 服务器运行。建议对生产构建运行测试,使测试环境更接近应用实际运行时的行为。

先运行 npm run build 和 npm run start,再在另一个终端窗口执行 npx playwright test,运行 Playwright 测试。

提示:也可以使用 webServer 功能,让 Playwright 自动启动开发服务器,并等待它完全可用。

在持续集成环境中运行 Playwright

Playwright 默认以无头模式运行测试。若要安装全部 Playwright 依赖项,可以执行 npx playwright install-deps。

以下资源介绍了 Playwright 与持续集成的更多用法:

  • Next.js 与 Playwright 示例
  • 在你的 CI 服务上运行 Playwright
  • Playwright Discord 社区

原文:How to set up Playwright with Next.js。作者/来源:Next.js 文档团队。本文依据所列原文整理为中文,代码、命令与配置示例保留原文。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容