NNext.js 中文网 GitHub

如何在 Next.js 中设置 Jest

了解如何在 Next.js 中设置 Jest 以进行单元测试和快照测试。

Jest 和 React Testing Library 经常一起用于单元测试和快照测试。本指南将向你展示如何在 Next.js 中设置 Jest 并编写第一个测试。

小知识: 由于 async Server Components 在 React 生态中较新,Jest 目前不支持它们。虽然你仍然可以为同步的 Server 和 Client Components 运行单元测试,但我们建议对 async 组件使用 E2E 测试。

快速开始#

你可以使用 create-next-app 配合 Next.js 的 with-jest 示例快速上手:

bash · pnpm
pnpm create next-app --example with-jest with-jest-app
bash · npm
npx create-next-app@latest --example with-jest with-jest-app
bash · yarn
yarn create next-app --example with-jest with-jest-app
bash · bun
bun create next-app --example with-jest with-jest-app

手动设置#

自 Next.js 12 发布以来,Next.js 已内置对 Jest 的配置。

要设置 Jest,请将 jest 及以下包安装为开发依赖:

bash · pnpm
pnpm add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
bash · npm
npm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
bash · yarn
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest
bash · bun
bun add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node @types/jest

运行以下命令生成一份基础的 Jest 配置文件:

bash · pnpm
pnpm create jest@latest
bash · npm
npm init jest@latest
bash · yarn
yarn create jest@latest
bash · bun
bun 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({
  // 提供你的 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)
jest.config.js
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'],
}

// 以这种方式导出 createJestConfig,是为了确保 next/jest 能够加载异步的 Next.js 配置
module.exports = createJestConfig(config)

在底层,next/jest 会自动为你配置 Jest,包括:

  • 使用 Next.js Compiler 设置 transform。
  • 自动 mock 样式表(.css、.module.css 及其 scss 变体)、图片导入和 next/font。
  • 将 .env(及其所有变体)加载到 process.env。
  • 在测试解析和转换时忽略 node_modules。
  • 在测试解析时忽略 .next。
  • 加载 next.config.js 以获取启用 SWC 转换的标志。

小知识:要直接测试环境变量,请在单独的设置脚本或 jest.config.ts 文件中手动加载它们。更多信息请参阅测试环境变量。

设置 Jest(使用 Babel)#

如果你选择不使用 Next.js Compiler 而改用 Babel,则需要手动配置 Jest,并在上述包之外额外安装 babel-jest 和 identity-obj-proxy。

以下是为 Next.js 配置 Jest 的推荐选项:

jest.config.js
module.exports = {
  collectCoverage: true,
  // 在 node 14.x 上,coverage provider v8 速度不错,报告也大致可用
  coverageProvider: 'v8',
  collectCoverageFrom: [
    '**/*.{js,jsx,ts,tsx}',
    '!**/*.d.ts',
    '!**/node_modules/**',
    '!<rootDir>/out/**',
    '!<rootDir>/.next/**',
    '!<rootDir>/*.config.js',
    '!<rootDir>/coverage/**',
  ],
  moduleNameMapper: {
    // 处理 CSS 导入(使用 CSS modules)
    // https://jestjs.io/docs/webpack#mocking-css-modules
    '^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',

    // 处理 CSS 导入(不使用 CSS modules)
    '^.+\\.(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: {
    // 使用 babel-jest 配合 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 文档中了解每个配置选项的更多信息。我们还建议查看 next/jest 配置,了解 Next.js 如何配置 Jest。

处理样式表和图片导入#

样式表和图片在测试中并未使用,但导入它们可能会引发错误,因此需要对它们进行 mock。

在 __mocks__ 目录中创建上面配置中引用的 mock 文件 —— fileMock.js 和 styleMock.js:

__mocks__/fileMock.js
module.exports = 'test-file-stub'
__mocks__/styleMock.js
module.exports = {}

有关处理静态资源的更多信息,请参阅 Jest 文档。

处理字体#

要处理字体,请在 __mocks__ 目录中创建 nextFontMock.js 文件,并添加以下配置:

__mocks__/nextFontMock.js
module.exports = new Proxy(
  {},
  {
    get: function getter() {
      return () => ({
        className: 'className',
        variable: 'variable',
        style: { fontFamily: 'fontFamily' },
      })
    },
  }
)

可选:处理绝对导入和模块路径别名#

如果你的项目使用了模块路径别名,则需要通过将 jsconfig.json 文件中的 paths 选项与 jest.config.js 文件中的 moduleNameMapper 选项相匹配,来配置 Jest 解析这些导入。例如:

tsconfig.json or 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.config.js
setupFilesAfterEnv: ['<rootDir>/jest.setup.js']

然后,在 jest.setup 中添加以下导入:

jest.setup.ts
import '@testing-library/jest-dom'
jest.setup.js
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 脚本:

package.json
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "test": "jest",
    "test:watch": "jest --watch"
  }
}

jest --watch 会在文件更改时重新运行测试。更多 Jest CLI 选项请参阅 Jest 文档。

创建第一个测试#

现在你的项目已准备好运行测试。在项目根目录创建一个名为 __tests__ 的文件夹。

例如,我们可以添加一个测试,检查 <Home /> 组件是否成功渲染了标题:

jsx
export default function Home() {
  return <h1>Home</h1>
}
__tests__/index.test.js
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 /> 组件是否成功渲染了标题:

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 Home from '../pages/index'

it('renders homepage unchanged', () => {
  const { container } = render(<Home />)
  expect(container).toMatchSnapshot()
})

小知识:测试文件不应放在 Pages Router 内,因为 Pages Router 内的任何文件都会被视为路由。

__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()
})

运行测试#

然后,运行以下命令来执行测试:

bash · pnpm
pnpm test
bash · npm
npm run test
bash · yarn
yarn test
bash · bun
bun run test

其他资源#

如需进一步阅读,你可能会发现以下资源很有帮助:

Next.js 中文网