跳到内容

如何使用 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/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 配合工作所需的所有配置选项。

jest.config.ts
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)

在底层,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文件中的paths选项与jest.config.js文件中的moduleNameMapper选项匹配来解析导入。例如:

tsconfig.json 或 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添加测试脚本

最后,向您的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 文档

创建你的第一个测试

您的项目现在已准备好运行测试。在您项目的根目录中创建一个名为__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()
})

运行你的测试

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

终端
npm run test
# or
yarn test
# or
pnpm test

其他资源

如需进一步阅读,您可能会发现这些资源很有帮助