跳到内容

设置 Next.js 的 Jest

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

须知: 由于 async 服务端组件是 React 生态系统的新特性,Jest 目前不支持它们。虽然你仍然可以为同步服务端和客户端组件运行单元测试,但我们建议为 async 组件使用 E2E 测试

快速开始

你可以使用带有 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
# or
yarn add -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node
# or
pnpm install -D jest jest-environment-jsdom @testing-library/react @testing-library/dom @testing-library/jest-dom ts-node

通过运行以下命令生成基本的 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 (使用 Babel)

如果你选择不使用 Next.js 编译器 而使用 Babel,则除了上述包之外,你还需要手动配置 Jest 并安装 babel-jestidentity-obj-proxy

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

jest.config.js
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://jest.node.org.cn/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://jest.node.org.cn/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://jest.node.org.cn/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。

处理样式表和图像导入

样式表和图像在测试中不使用,但导入它们可能会导致错误,因此需要模拟它们。

__mocks__ 目录中创建上面配置中引用的模拟文件 - fileMock.jsstyleMock.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' },
      })
    },
  }
)

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

如果你的项目使用模块路径别名,你将需要配置 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-expect 已在 v6.0 中移除,因此如果你使用的是版本 6 之前的 @testing-library/jest-dom,则需要导入 @testing-library/jest-dom/extend-expect

如果你需要在每个测试之前添加更多设置选项,你可以将它们添加到上面的 jest.setup 文件中。

package.json 中添加测试脚本

最后,将 Jest test 脚本添加到你的 package.json 文件中

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 /> 组件是否成功渲染标题

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

可选地,添加快照测试以跟踪组件中任何意外的更改

__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 中的任何文件都被视为路由。

运行你的测试

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

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

额外资源

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