跳到主要内容

如何使用 Next.js 设置 Jest

Jest 和 React Testing Library 经常一起用于单元测试快照测试。本指南将向你展示如何使用 Next.js 设置 Jest 并编写你的第一个测试。

需要了解: 由于 async 服务器组件对 React 生态系统来说是新的,Jest 目前不支持它们。虽然你仍然可以为同步服务器和客户端组件运行单元测试,但我们建议对 async 组件使用E2E 测试

快速开始

你可以使用 create-next-app 和 Next.js with-jest 示例快速开始:

Terminal
npx create-next-app@latest --example with-jest with-jest-app

手动设置

Next.js 12 发布以来,Next.js 现在具有 Jest 的内置配置。

要设置 Jest,将 jest 和以下包安装为开发依赖:

Terminal
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
# or
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
# or
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest

通过运行以下命令生成基本的 Jest 配置文件:

Terminal
npm init jest@latest
# or
yarn create jest@latest
# or
pnpm create jest@latest

这将带你通过一系列提示来为你的项目设置 Jest,包括自动创建 jest.config.ts|js 文件。

更新你的配置文件以使用 next/jest。此转换器具有 Jest 与 Next.js 一起工作所需的所有配置选项:

jest.config.ts
import type { Config } from 'jest'
import nextJest from 'next/jest.js'

const createJestConfig = nextJest({
// 提供 Next.js 应用的路径,以加载测试环境中的 next.config.js 和 .env 文件
dir: './',
})

// 添加任何要传递给 Jest 的自定义配置
const config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// 在每个测试运行前添加更多设置选项
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}

// createJestConfig 以这种方式导出,以确保 next/jest 可以加载 Next.js 配置,因为它是异步的
export default createJestConfig(config)

在底层,next/jest 正在自动为你配置 Jest,包括:

  • 使用 Next.js 编译器设置 transform
  • 自动模拟样式表(.css.module.css 及其 scss 变体)、图像导入和 next/font
  • .env(及所有变体)加载到 process.env 中。
  • 从测试解析和转换中忽略 node_modules
  • 从测试解析中忽略 .next
  • 加载 next.config.js 以获取启用 SWC 转换的标志。

需要了解:要直接测试环境变量,在单独的设置脚本或 jest.config.ts 文件中手动加载它们。有关更多信息,请参阅测试环境变量

可选:处理绝对导入和模块路径别名

如果你的项目使用模块路径别名,你需要配置 Jest 来解析导入,方法是将 jsconfig.json 文件中的路径选项与 jest.config.js 文件中的 moduleNameMapper 选项匹配。例如:

tsconfig.json or jsconfig.json
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"baseUrl": "./",
"paths": {
"@/components/*": ["components/*"]
}
}
}
jest.config.js
moduleNameMapper: {
// ...
'^@/components/(.*)$': '<rootDir>/components/$1',
}

可选:使用自定义匹配器扩展 Jest

@testing-library/jest-dom 包含一组方便的自定义匹配器,如 .toBeInTheDocument(),使编写测试更容易。你可以通过将以下选项添加到 Jest 配置文件来为每个测试导入自定义匹配器:

jest.config.ts
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']

然后,在 jest.setup 内添加以下导入:

jest.setup.ts
import '@testing-library/jest-dom'

需要了解: extend-expectv6.0 中被移除,所以如果你在版本 6 之前使用 @testing-library/jest-dom,你需要导入 @testing-library/jest-dom/extend-expect 代替。

如果你需要在每个测试之前添加更多设置选项,可以将它们添加到上面的 jest.setup 文件中。

package.json 中添加测试脚本

最后,将 Jest test 脚本添加到你的 package.json 文件中:

package.json
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest",
"test:watch": "jest --watch"
}
}

jest --watch 将在文件更改时重新运行测试。有关更多 Jest CLI 选项,请参阅 Jest 文档

创建你的第一个测试

你的项目现在已准备好运行测试。在项目根目录中创建一个名为 __tests__ 的文件夹。

例如,我们可以添加一个测试来检查 <Page /> 组件是否成功渲染标题:

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

export default function Page() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}
__tests__/page.test.jsx
import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
import Page from '../app/page'

describe('Page', () => {
it('renders a heading', () => {
render(<Page />)

const heading = screen.getByRole('heading', { level: 1 })

expect(heading).toBeInTheDocument()
})
})

可选地,添加快照测试来跟踪组件中的任何意外更改:

__tests__/snapshot.js
import { render } from '@testing-library/react'
import Page from '../app/page'

it('renders homepage unchanged', () => {
const { container } = render(<Page />)
expect(container).toMatchSnapshot()
})

运行你的测试

然后,运行以下命令来运行你的测试:

Terminal
npm run test
# or
yarn test
# or
pnpm test

其他资源

对于进一步阅读,你可能会发现这些资源有帮助: