NNext.js 中文网 GitHub

如何在 Next.js 中设置 Cypress

了解如何在 Next.js 中设置 Cypress 以进行端到端(E2E)测试和组件测试。

Cypress 是一个用于端到端(E2E)和组件测试的测试运行器。本页将向你展示如何在 Next.js 中设置 Cypress 并编写你的第一个测试。

警告:

  • 低于 13.6.3 的 Cypress 版本不支持使用 moduleResolution:"bundler" 的 TypeScript 5。不过,此问题已在 Cypress 13.6.3 及更高版本中解决。cypress v13.6.3

快速开始#

你可以使用 create-next-app 配合 with-cypress 示例快速上手。

bash · pnpm
pnpm create next-app --example with-cypress with-cypress-app
bash · npm
npx create-next-app@latest --example with-cypress with-cypress-app
bash · yarn
yarn create next-app --example with-cypress with-cypress-app
bash · bun
bun create next-app --example with-cypress with-cypress-app

手动设置#

要手动设置 Cypress,请将 cypress 安装为开发依赖:

bash · pnpm
pnpm add -D cypress
bash · npm
npm install -D cypress
bash · yarn
yarn add -D cypress
bash · bun
bun add -D cypress

将 Cypress 的 open 命令添加到 package.json 的 scripts 字段中:

package.json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "eslint",
    "cypress:open": "cypress open"
  }
}

首次运行 Cypress 以打开 Cypress 测试套件:

bash · pnpm
pnpm cypress:open
bash · npm
npm run cypress:open
bash · yarn
yarn cypress:open
bash · bun
bun run cypress:open

你可以选择配置 E2E Testing 和/或 Component Testing。选择其中任何一项都会在你的项目中自动创建一个 cypress.config.js 文件和一个 cypress 文件夹。

创建你的第一个 Cypress E2E 测试#

确保你的 cypress.config 文件具有以下配置:

cypress.config.ts
import { defineConfig } from 'cypress'

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {},
  },
})
cypress.config.js
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {},
  },
})

然后,创建两个新的 Next.js 文件:

app/page.js
import Link from 'next/link'

export default function Page() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}
app/about/page.js
import Link from 'next/link'

export default function Page() {
  return (
    <div>
      <h1>About</h1>
      <Link href="/">Home</Link>
    </div>
  )
}
pages/index.js
import Link from 'next/link'

export default function Home() {
  return (
    <div>
      <h1>Home</h1>
      <Link href="/about">About</Link>
    </div>
  )
}
pages/about.js
import Link from 'next/link'

export default function About() {
  return (
    <div>
      <h1>About</h1>
      <Link href="/">Home</Link>
    </div>
  )
}

添加一个测试来检查你的导航是否正常工作:

cypress/e2e/app.cy.js
describe('Navigation', () => {
  it('should navigate to the about page', () => {
    // 从索引页面开始
    cy.visit('http://localhost:3000/')

    // 找到 href 属性包含 "about" 的链接并点击它
    cy.get('a[href*="about"]').click()

    // 新的 url 应包含 "/about"
    cy.url().should('include', '/about')

    // 新页面应包含带有 "About" 的 h1
    cy.get('h1').filter(':visible').contains('About')
  })
})

测试由 Cache Components 保留的路由#

使用 Cache Components 时,客户端导航后先前的页面会隐藏在 DOM 中。诸如 cy.get() 之类的查询仍可能匹配这些元素。在交互或断言其数量之前,请使用 .filter(':visible') 缩小匹配范围。有关更多详细信息,请参阅测试保留的 UI。

运行 E2E 测试#

Cypress 将模拟用户浏览你的应用程序,这需要你的 Next.js 服务器正在运行。我们建议针对生产代码运行测试,以更贴近应用程序的实际行为。

运行 npm run build && npm run start 来构建你的 Next.js 应用程序,然后在另一个终端窗口中运行 npm run cypress:open 以启动 Cypress 并运行你的 E2E 测试套件。

小知识:

  • 通过在 cypress.config.js 配置文件中添加 baseUrl: 'http://localhost:3000',你可以使用 cy.visit("/") 代替 cy.visit("http://localhost:3000/")。
  • 或者,你可以安装 start-server-and-test 包,将 Next.js 生产服务器与 Cypress 一起运行。安装后,将 "test": "start-server-and-test start http://localhost:3000 cypress" 添加到 package.json 的 scripts 字段中。请记住在做出新更改后重新构建应用程序。

创建你的第一个 Cypress 组件测试#

组件测试会构建并挂载特定组件,而无需打包整个应用程序或启动服务器。

在 Cypress 应用中选择 Component Testing,然后选择 Next.js 作为你的前端框架。你的项目中将创建一个 cypress/component 文件夹,并且 cypress.config.js 文件将被更新以启用 Component Testing。

确保你的 cypress.config 文件具有以下配置:

cypress.config.ts
import { defineConfig } from 'cypress'

export default defineConfig({
  component: {
    devServer: {
      framework: 'next',
      bundler: 'webpack',
    },
  },
})
cypress.config.js
const { defineConfig } = require('cypress')

module.exports = defineConfig({
  component: {
    devServer: {
      framework: 'next',
      bundler: 'webpack',
    },
  },
})

假设使用上一节中的相同组件,添加一个测试来验证组件是否渲染了预期的输出:

cypress/component/about.cy.tsx
import Page from '../../app/page'

describe('<Page />', () => {
  it('should render and display expected content', () => {
    // 挂载 Home 页面的 React 组件
    cy.mount(<Page />)

    // 新页面应包含带有 "Home" 的 h1
    cy.get('h1').contains('Home')

    // 验证存在具有预期 URL 的链接
    // 点击链接更适合放在 E2E 测试中
    cy.get('a[href="/about"]').should('be.visible')
  })
})
cypress/component/about.cy.js
import AboutPage from '../../pages/about'

describe('<AboutPage />', () => {
  it('should render and display expected content', () => {
    // 挂载 About 页面的 React 组件
    cy.mount(<AboutPage />)

    // 新页面应包含带有 "About page" 的 h1
    cy.get('h1').contains('About')

    // 验证存在具有预期 URL 的链接
    // *点击*链接更适合放在 E2E 测试中
    cy.get('a[href="/"]').should('be.visible')
  })
})

小知识:

  • Cypress 目前不支持对 async Server Components 进行组件测试。我们建议使用 E2E 测试。
  • 由于组件测试不需要 Next.js 服务器,像 <Image /> 这样依赖服务器可用的功能可能无法开箱即用。

运行组件测试#

在终端中运行 npm run cypress:open 以启动 Cypress 并运行你的组件测试套件。

持续集成(CI)#

除了交互式测试之外,你还可以使用 cypress run 命令以无头模式运行 Cypress,这更适合 CI 环境:

package.json
{
  "scripts": {
    //...
    "e2e": "start-server-and-test dev http://localhost:3000 \"cypress open --e2e\"",
    "e2e:headless": "start-server-and-test dev http://localhost:3000 \"cypress run --e2e\"",
    "component": "cypress open --component",
    "component:headless": "cypress run --component"
  }
}

你可以从以下资源了解更多关于 Cypress 和持续集成的信息:

Next.js 中文网