Skip to main content

使用 Next.js 设置 Cypress

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

¥Cypress is a test runner used for End-to-End (E2E) and Component Testing. This page will show you how to set up Cypress with Next.js and write your first tests.

警告:

¥Warning:

  • 对于组件测试,Cypress 目前不支持 Next.js 版本 14async 服务器组件。这些问题正在被跟踪。目前,组件测试适用于 Next.js 版本 13,我们建议对 async 服务器组件进行 E2E 测试。

    ¥For component testing, Cypress currently does not support Next.js version 14 and async Server Components. These issues are being tracked. For now, component testing works with Next.js version 13, and we recommend E2E testing for async Server Components.

  • Cypress 13.6.3 以下版本不支持 TypeScript 版本 5moduleResolution:"bundler"。不过,此问题已在 Cypress 13.6.3 及更高版本中得到解决。赛普拉斯 v13.6.3

    ¥Cypress versions below 13.6.3 do not support TypeScript version 5 with moduleResolution:"bundler". However, this issue has been resolved in Cypress version 13.6.3 and later. cypress v13.6.3

快速开始

¥Quickstart

你可以将 create-next-appwith-cypress 示例 结合使用来快速入门。

¥You can use create-next-app with the with-cypress example to quickly get started.

npx create-next-app@latest --example with-cypress with-cypress-app

手动设置

¥Manual setup

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

¥To manually set up Cypress, install cypress as a dev dependency:

npm install -D cypress
# or
yarn add -D cypress
# or
pnpm install -D cypress

将 Cypress open 命令添加到 package.json 脚本字段:

¥Add the Cypress open command to the package.json scripts field:

{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"cypress:open": "cypress open"
}
}

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

¥Run Cypress for the first time to open the Cypress testing suite:

npm run cypress:open

你可以选择配置端到端测试和/或组件测试。选择这些选项中的任何一个都会在你的项目中自动创建 cypress.config.js 文件和 cypress 文件夹。

¥You can choose to configure E2E Testing and/or Component Testing. Selecting any of these options will automatically create a cypress.config.js file and a cypress folder in your project.

创建你的第一个 Cypress E2E 测试

¥Creating your first Cypress E2E test

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

¥Ensure your cypress.config.js file has the following configuration:

import { defineConfig } from 'cypress'

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

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

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

¥Then, create two new Next.js files:

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>
)
}

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

¥Add a test to check your navigation is working correctly:

describe('Navigation', () => {
it('should navigate to the about page', () => {
// Start from the index page
cy.visit('http://localhost:3000/')

// Find a link with an href attribute containing "about" and click it
cy.get('a[href*="about"]').click()

// The new url should include "/about"
cy.url().should('include', '/about')

// The new page should contain an h1 with "About"
cy.get('h1').contains('About')
})
})

运行端到端测试

¥Running E2E Tests

Cypress 将模拟用户导航你的应用,这需要你的 Next.js 服务器正在运行。我们建议针对你的生产代码运行测试,以更接近你的应用的行为方式。

¥Cypress will simulate a user navigating your application, this requires your Next.js server to be running. We recommend running your tests against your production code to more closely resemble how your application will behave.

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

¥Run npm run build && npm run start to build your Next.js application, then run npm run cypress:open in another terminal window to start Cypress and run your E2E testing suite.

很高兴知道:

¥Good to know:

  • 你可以通过将 baseUrl: 'http://localhost:3000' 添加到 cypress.config.js 配置文件来使用 cy.visit("/") 代替 cy.visit("http://localhost:3000/")

    ¥You can use cy.visit("/") instead of cy.visit("http://localhost:3000/") by adding baseUrl: 'http://localhost:3000' to the cypress.config.js configuration file.

  • 或者,你可以安装 start-server-and-test 软件包以与 Cypress 结合运行 Next.js 生产服务器。安装后,将 "test": "start-server-and-test start http://localhost:3000 cypress" 添加到 package.json 脚本字段。请记住在新更改后重建你的应用。

    ¥Alternatively, you can install the start-server-and-test package to run the Next.js production server in conjunction with Cypress. After installation, add "test": "start-server-and-test start http://localhost:3000 cypress" to your package.json scripts field. Remember to rebuild your application after new changes.

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

¥Creating your first Cypress component test

组件测试构建并安装特定组件,而无需打包整个应用或启动服务器。

¥Component tests build and mount a specific component without having to bundle your whole application or start a server.

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

¥Select Component Testing in the Cypress app, then select Next.js as your front-end framework. A cypress/component folder will be created in your project, and a cypress.config.js file will be updated to enable component testing.

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

¥Ensure your cypress.config.js file has the following configuration:

import { defineConfig } from 'cypress'

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

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

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

¥Assuming the same components from the previous section, add a test to validate a component is rendering the expected output:

import Page from '../../app/page'

describe('<Page />', () => {
it('should render and display expected content', () => {
// Mount the React component for the Home page
cy.mount(<Page />)

// The new page should contain an h1 with "Home"
cy.get('h1').contains('Home')

// Validate that a link with the expected URL is present
// Following the link is better suited to an E2E test
cy.get('a[href="/about"]').should('be.visible')
})
})

很高兴知道:

¥Good to know:

  • Cypress 目前不支持 async 服务器组件的组件测试。我们建议使用 E2E 测试。

    ¥Cypress currently doesn't support component testing for async Server Components. We recommend using E2E testing.

  • 由于组件测试不需要 Next.js 服务器,因此依赖于可用服务器的 <Image /> 等功能可能无法开箱即用。

    ¥Since component tests do not require a Next.js server, features like <Image /> that rely on a server being available may not function out-of-the-box.

运行组件测试

¥Running Component Tests

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

¥Run npm run cypress:open in your terminal to start Cypress and run your component testing suite.

持续集成(CI)

¥Continuous Integration (CI)

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

¥In addition to interactive testing, you can also run Cypress headlessly using the cypress run command, which is better suited for CI environments:

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

你可以从以下资源了解有关赛普拉斯和持续集成的更多信息:

¥You can learn more about Cypress and Continuous Integration from these resources: