Jest 和 React Testing Library 经常一起用于单元测试和快照测试。本指南将向您展示如何将 Jest 与 Next.js 一起设置,并编写您的第一个测试。
须知: 由于
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/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({
// 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)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.js'],
}
// 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,包括:
transform。.css、.module.css 及其 scss 变体)、图像导入和 next/font。.env(及所有变体)加载到 process.env 中。node_modules 的测试解析和转换。.next 的测试解析。next.config.js 以获取启用 SWC 转换的标志。须知:要直接测试环境变量,请在单独的设置脚本中或在您的
jest.config.ts文件中手动加载它们。有关更多信息,请参阅 Test Environment Variables。
如果您弃用 Next.js Compiler 而改用 Babel,您需要手动配置 Jest,并除了上述包之外,额外安装 babel-jest 和 identity-obj-proxy。
以下是为 Next.js 配置 Jest 的推荐选项:
module.exports = {
collectCoverage: true,
// on node 14.x coverage provider v8 offers good speed and more or less good report
coverageProvider: 'v8',
collectCoverageFrom: [
'**/*.{js,jsx,ts,tsx}',
'!**/*.d.ts',
'!**/node_modules/**',
'!<rootDir>/out/**',
'!<rootDir>/.next/**',
'!<rootDir>/*.config.js',
'!<rootDir>/coverage/**',
],
moduleNameMapper: {
// Handle CSS imports (with CSS modules)
// https://jestjs.io/docs/webpack#mocking-css-modules
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
// Handle CSS imports (without CSS modules)
'^.+\\.(css|sass|scss)$': '<rootDir>/__mocks__/styleMock.js',
// Handle image imports
// https://jestjs.io/docs/webpack#handling-static-assets
'^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp|svg)$': `<rootDir>/__mocks__/fileMock.js`,
// Handle module aliases
'^@/components/(.*)$': '<rootDir>/components/$1',
// Handle @next/font
'@next/font/(.*)': `<rootDir>/__mocks__/nextFontMock.js`,
// Handle next/font
'next/font/(.*)': `<rootDir>/__mocks__/nextFontMock.js`,
// Disable server-only
'server-only': `<rootDir>/__mocks__/empty.js`,
},
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: ['<rootDir>/node_modules/', '<rootDir>/.next/'],
testEnvironment: 'jsdom',
transform: {
// Use babel-jest to transpile tests with the next/babel preset
// https://jestjs.io/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object
'^.+\\.(js|jsx|ts|tsx)$': ['babel-jest', { presets: ['next/babel'] }],
},
transformIgnorePatterns: [
'/node_modules/',
'^.+\\.module\\.(css|sass|scss)$',
],
}您可以在 Jest docs 中了解每个配置选项的更多信息。我们还建议查阅 next/jest configuration 以了解 Next.js 如何配置 Jest。
样式表和图像在测试中不使用,但导入它们可能会导致错误,因此需要进行模拟。
在 __mocks__ 目录中创建上述配置中引用的模拟文件 — fileMock.js 和 styleMock.js:
module.exports = 'test-file-stub'module.exports = {}有关处理静态资源的更多信息,请参阅 Jest Docs。
要处理字体,请在 __mocks__ 目录中创建 nextFontMock.js 文件,并添加以下配置:
module.exports = new Proxy(
{},
{
get: function getter() {
return () => ({
className: 'className',
variable: 'variable',
style: { fontFamily: 'fontFamily' },
})
},
}
)如果您的项目使用 Module Path Aliases,您需要通过将 jsconfig.json 文件中的 paths 选项与 jest.config.js 文件中的 moduleNameMapper 选项进行匹配来配置 Jest 以解析导入。例如:
{
"compilerOptions": {
"module": "esnext",
"moduleResolution": "bundler",
"baseUrl": "./",
"paths": {
"@/components/*": ["components/*"]
}
}
}moduleNameMapper: {
// ...
'^@/components/(.*)$': '<rootDir>/components/$1',
}@testing-library/jest-dom 包含一组方便的 自定义匹配器,例如 .toBeInTheDocument(),这使得编写测试变得更容易。您可以通过在 Jest 配置文件中添加以下选项来为每个测试导入自定义匹配器:
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts']setupFilesAfterEnv: ['<rootDir>/jest.setup.js']然后,在 jest.setup 中,添加以下导入:
import '@testing-library/jest-dom'import '@testing-library/jest-dom'须知:
extend-expect在v6.0中被移除,因此如果您使用的是版本 6 之前的@testing-library/jest-dom,则需要导入@testing-library/jest-dom/extend-expect。
如果您需要在每个测试运行前添加更多设置选项,可以将其添加到上述 jest.setup 文件中。
package.json最后,将一个 Jest test 脚本添加到您的 package.json 文件中:
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "jest",
"test:watch": "jest --watch"
}
}jest --watch 将在文件更改时重新运行测试。有关更多 Jest CLI 选项,请参阅 Jest Docs。
您的项目现在已准备好运行测试。在您项目的根目录中创建一个名为 __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()
})
})例如,我们可以添加一个测试来检查 <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 Home from '../pages/index'
it('renders homepage unchanged', () => {
const { container } = render(<Home />)
expect(container).toMatchSnapshot()
})须知:测试文件不应包含在 Pages Router 中,因为 Pages Router 中的任何文件都被视为路由。
import { render } from '@testing-library/react'
import Page from '../app/page'
it('renders homepage unchanged', () => {
const { container } = render(<Page />)
expect(container).toMatchSnapshot()
})然后,运行以下命令来运行您的测试:
npm run test
# or
yarn test
# or
pnpm test如需进一步阅读,您可能会发现以下资源很有帮助: