如何为 Next.js 设置 Jest
了解如何为 Next.js 设置 Jest,以进行单元测试和快照测试。
Jest 和 React Testing Library 经常一起用于单元测试和快照测试。本指南将向你展示如何为 Next.js 设置 Jest 并编写你的第一个测试。
须知:
由于
async服务器组件对 React 生态系统来说是新增的,Jest 目前还不支持它们。虽然你仍然可以为同步服务器组件和客户端组件运行单元测试,但我们建议对async组件使用端到端测试。
快速开始
你可以将 create-next-app 与 Next.js 的 with-jest 示例一起使用来快速开始:
pnpm
pnpm create next-app --example with-jest with-jest-app
npm
npx create-next-app@latest --example with-jest with-jest-app
yarn
yarn create next-app --example with-jest with-jest-app
bun
bun create next-app --example with-jest with-jest-app
手动设置
自 Next.js 12 发布以来,Next.js 现在内置了 Jest 配置。
要设置 Jest,请安装 jest 以及以下包作为开发依赖:
pnpm
pnpm add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
npm
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
yarn
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
bun
bun add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
运行以下命令生成一个基本的 Jest 配置文件:
pnpm
pnpm create jest@latest
npm
npm init jest@latest
yarn
yarn create jest@latest
bun
bun create jest@latest
这会引导你完成一系列提示,为你的项目设置 Jest,包括自动创建一个 jest.config.ts|js 文件。
更新你的配置文件以使用 next/jest。该转换器包含了让 Jest 与 Next.js 协同工作所需的所有配置选项:
TypeScript
import type { Config } from 'jest'
import nextJest from 'next/jest.js'
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
})
// Add any custom config to be passed to Jest
const config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)
JavaScript
const nextJest = require('next/jest')
/** @type {import('jest').Config} */
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
})
// Add any custom config to be passed to Jest
const config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
}
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(config)
在底层,next/jest 会自动为你配置 Jest,包括:
- 使用 Next.js Compiler 来设置
transform。 - 自动模拟样式表(
.css、.module.css及其 scss 变体)、图片导入和next/font。 - 将
.env(及所有变体)加载到process.env中。 - 在测试解析和转换中忽略
node_modules。 - 在测试解析中忽略
.next。 - 为启用 SWC 转换的标志加载
next.config.js。
须知:
要直接测试环境变量,请在单独的 setup 脚本或你的
jest.config.ts文件中手动加载它们。更多信息,请参阅 Test Environment Variables。
可选:处理绝对导入和模块路径别名
如果你的项目使用了 Module Path Aliases,你需要配置 Jest 来解析导入,方法是将 jsconfig.json 文件中的 paths 选项与 jest.config.js 文件中的 moduleNameMapper 选项进行匹配。例如:
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"baseUrl": "./",
"paths": {
"@/components/*": ["components/*"]
}
}
}
moduleNameMapper: {
// ...
'^@/components/(.*)$': '<rootDir>/components/$1',
}
可选:使用自定义匹配器扩展 Jest
@testing-library/jest-dom 包含一组便捷的 custom matchers,例如 .toBeInTheDocument(),使编写测试更加容易。你可以通过向 Jest 配置文件添加以下选项,为每个测试导入这些自定义匹配器:
TypeScript
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
JavaScript
setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
然后,在 jest.setup 中添加以下导入:
TypeScript
import '@testing-library/jest-dom'
JavaScript
import '@testing-library/jest-dom'
须知:
extend-expect已在v6.0中移除,因此如果你使用的是 6 版本之前的@testing-library/jest-dom,则需要改为导入@testing-library/jest-dom/extend-expect。
如果你需要在每个测试之前添加更多设置选项,可以将它们添加到上面的 jest.setup 文件中。
向 package.json 添加一个测试脚本
最后,向 package.json 文件中添加一个 Jest test 脚本:
{
"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 Page() {
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('renders a heading', () => {
render(<Page />)
const heading = screen.getByRole('heading', { level: 1 })
expect(heading).toBeInTheDocument()
})
})
(可选)添加一个快照测试,以跟踪组件中出现的任何意外变化:
import { render } from '@testing-library/react'
import Page from '../app/page'
it('renders homepage unchanged', () => {
const { container } = render(<Page />)
expect(container).toMatchSnapshot()
})
运行你的测试
然后,运行以下命令来运行你的测试:
pnpm
pnpm test
npm
npm run test
yarn
yarn test
bun
bun run test
更多资源
如需进一步阅读,以下资源可能会有所帮助:
- Next.js 与 Jest 示例
- Jest 文档
- React Testing Library 文档
- Testing Playground - 使用良好的测试实践来匹配元素。