How to set up Jest with Next.js
Jest 和 React Testing Library 经常一起用于单元测试和快照测试。本指南将向你展示如何在 Next.js 中设置 Jest 并编写你的第一个测试。
值得注意的是: 由于
async
服务器组件是 React 生态系统的新功能,Jest 目前不支持它们。虽然你仍然可以为同步的服务器和客户端组件运行单元测试,但我们建议为async
组件使用端到端测试。
快速开始
你可以使用带有 Next.js with-jest 示例的 create-next-app
来快速开始:
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/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 配置文件:
npm init jest@latest
# or
yarn create jest@latest
# or
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'],
}
// 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(使用 Babel)
如果你选择不使用 Next.js 编译器而使用 Babel,你将需要手动配置 Jest 并安装 babel-jest
和 identity-obj-proxy
,除了上面的包之外。
以下是为 Next.js 配置 Jest 的推荐选项:
module.exports = {
collectCoverage: true,
// 在 node 14.x 上,覆盖率提供程序 v8 提供了良好的速度和相对不错的报告
coverageProvider: 'v8',
collectCoverageFrom: [
'**/*.{js,jsx,ts,tsx}',
'!**/*.d.ts',
'!**/node_modules/**',
'!<rootDir>/out/**',
'!<rootDir>/.next/**',
'!<rootDir>/*.config.js',
'!<rootDir>/coverage/**',
],
moduleNameMapper: {
// https://jestjs.io/docs/webpack#mocking-css-modules
// 处理 CSS 导入(使用 CSS 模块)
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
// 处理 CSS 导入(不使用 CSS 模块)
'^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',
// https://jestjs.io/docs/webpack#handling-static-assets
// 处理图像导入
'^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$': `<rootDir>/__mocks__/fileMock.js`,
// 处理模块别名
'^@/components/(.*)$': '<rootDir>/components/$1',
// 处理 @next/font
'@next/font/(.*)': `<rootDir>/__mocks__/nextFontMock.js`,
// 处理 next/font
'next/font/(.*)': `<rootDir>/__mocks__/nextFontMock.js`,
// 禁用 server-only
'server-only': `<rootDir>/__mocks__/empty.js`,
},
// 在运行每个测试之前添加更多设置选项
// setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
testEnvironment: 'jsdom',
transform: {
// https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
// 使用 babel-jest 通过 next/babel 预设转译测试
'^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
},
transformIgnorePatterns: [
'/node_modules/',
'^.+\\.module\\.(css|sass|scss)$',
],
}
你可以在 Jest 文档中了解更多关于每个配置选项的信息。我们还建议查看 next/jest
配置,了解 Next.js 如何配置 Jest。
处理样式表和图像导入
测试中不会使用样式表和图像,但导入它们可能会导致错误,因此需要对它们进行模拟。
在 __mocks__
目录中创建上面配置中引用的模拟文件 —— fileMock.js
和 styleMock.js
:
module.exports = 'test-file-stub'
module.exports = {}
有关处理静态资源的更多信息,请参阅 Jest 文档。
处理字体
要处理字体,请在 __mocks__
目录中创建 nextFontMock.js
文件,并添加以下配置:
module.exports = new Proxy(
{},
{
get: function getter() {
return () => ({
className: 'className',
variable: 'variable',
style: { fontFamily: 'fontFamily' },
})
},
}
)
可选:处理绝对导入和模块路径别名
如果你的项目使用模块路径别名,你需要配置 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
包含一组方便的自定义匹配器,如 .toBeInTheDocument()
,使编写测试变得更容易。你可以通过在 Jest 配置文件中添加以下选项,为每个测试导入自定义匹配器:
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']
然后,在 jest.setup
中添加以下导入:
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__
的文件夹。
例如,我们可以添加一个测试来检查 <Home />
组件是否成功渲染了一个标题:
export default function Home() {
return <h1>Home</h1>
}
import '@testing-library/jest-dom'
import { render, screen } from '@testing-library/react'
import Home from '../pages/index'
describe('Home', () => {
it('renders a heading', () => {
render(<Home />)
const heading = screen.getByRole('heading', { level: 1 })
expect(heading).toBeInTheDocument()
})
})
可选地,添加一个快照测试来跟踪组件中的任何意外更改:
import { render } from '@testing-library/react'
import Home from '../pages/index'
it('renders homepage unchanged', () => {
const { container } = render(<Home />)
expect(container).toMatchSnapshot()
})
值得注意的是:测试文件不应包含在 Pages Router 内,因为 Pages Router 内的任何文件都被视为路由。
运行你的测试
然后,运行以下命令来运行你的测试:
npm run test
# or
yarn test
# or
pnpm test
额外资源
如需进一步阅读,你可能会发现这些资源很有帮助:
- Next.js with Jest 示例
- Jest 文档
- React Testing Library 文档
- Testing Playground - 使用良好的测试实践来匹配元素。