在 Next.js 中配置 Jest
Jest 和 React Testing Library 常被搭配用于单元测试和快照测试。本指南将展示如何在 Next.js 中配置 Jest 并编写首个测试。
须知: 由于
async
服务端组件是 React 生态的新特性,Jest 目前暂不支持。虽然仍可为同步的服务端和客户端组件运行单元测试,但我们建议对async
组件使用端到端测试。
快速开始
使用 create-next-app
配合 Next.js 官方 with-jest 示例快速创建项目:
npx create-next-app@latest --example with-jest with-jest-app
手动配置
自 Next.js 12 起,Next.js 已内置 Jest 配置支持。
安装 jest
及以下开发依赖项来配置 Jest:
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
# 或
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
# 或
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/jest-dom
运行以下命令生成基础 Jest 配置文件:
npm init jest@latest
# 或
yarn create jest@latest
# 或
pnpm create jest@latest
该命令将通过交互式引导完成 Jest 配置,包括自动创建 jest.config.ts|js
文件。
更新配置文件以使用 next/jest
。此转换器包含所有必要的配置选项使 Jest 适配 Next.js:
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'],
}
// 通过此方式导出确保 next/jest 能异步加载 Next.js 配置
export default createJestConfig(config)
const nextJest = require('next/jest')
/** @type {import('jest').Config} */
const createJestConfig = nextJest({
// 提供 Next.js 应用路径以在测试环境中加载 next.config.js 和 .env 文件
dir: './',
})
// 添加需传递给 Jest 的自定义配置
const config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// 在每次测试前添加更多设置选项
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
// 通过此方式导出确保 next/jest 能异步加载 Next.js 配置
module.exports = createJestConfig(config)
在底层,next/jest
自动完成以下配置:
- 使用 Next.js 编译器 设置
transform
- 自动模拟样式表 (
.css
,.module.css
及其 scss 变体)、图片导入和next/font
- 将
.env
(及其所有变体) 加载到process.env
- 从测试解析和转换中忽略
node_modules
- 从测试解析中忽略
.next
- 加载
next.config.js
以启用 SWC 转换的标记
须知:如需直接测试环境变量,需在单独的安装脚本或
jest.config.ts
中手动加载。详见测试环境变量。
可选:处理绝对路径导入和模块别名
如果项目使用模块路径别名,需通过配置 Jest 的 moduleNameMapper
选项来匹配 jsconfig.json
中的路径设置:
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"baseUrl": "./",
"paths": {
"@/components/*": ["components/*"]
}
}
}
moduleNameMapper: {
// ...
'^@/components/(.*)$': '<rootDir>/components/$1',
}
可选:使用自定义匹配器扩展 Jest
@testing-library/jest-dom
提供了一系列便捷的自定义匹配器,如 .toBeInTheDocument()
可简化测试编写。通过在 Jest 配置中添加以下选项为所有测试导入这些匹配器:
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
然后在 jest.setup.ts
中添加以下导入:
import '@testing-library/jest-dom'
import '@testing-library/jest-dom'
须知:
v6.0
移除了extend-expect
,若使用 6.0 之前版本的@testing-library/jest-dom
,需导入@testing-library/jest-dom/extend-expect
。
如需在每个测试前添加更多设置选项,可将其添加到上述 jest.setup.js
文件中。
在 package.json
中添加测试脚本
最后,在 package.json
中添加 Jest 测试脚本:
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest",
"test:watch": "jest --watch"
}
}
jest --watch
会在文件变更时重新运行测试。更多 Jest CLI 选项请参考 Jest 文档。
创建首个测试
项目现已准备好运行测试。在项目根目录创建 __tests__
文件夹。
例如,添加测试来验证 <Page />
组件是否能成功渲染标题:
import Link from 'next/link'
export default function Home() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
)
}
import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
import Page from '../app/page'
describe('Page', () => {
it('渲染标题', () => {
render(<Page />)
const heading = screen.getByRole('heading', { level: 1 })
expect(heading).toBeInTheDocument()
})
})
可选添加快照测试来追踪组件的意外变更:
import { render } from '@testing-library/react'
import Page from '../app/page'
it('主页渲染无异常', () => {
const { container } = render(<Page />)
expect(container).toMatchSnapshot()
})
运行测试
执行以下命令运行测试:
npm run test
# 或
yarn test
# 或
pnpm test
扩展资源
以下资源可能对你有帮助: