Skip to main content

Jest

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

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

快速开始

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

通过运行下列命令生成一个基本的 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.ts'],
};

// 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,包括:

  • Next.js 编译器设置transform
  • 自动 mock 样式表(如 .css, .module.css 以及它们的 scss variants)、图像导入和 next/font
  • .env (和所有 variants)加载到process.env
  • 忽略node_modules中的测试解析和转换
  • 忽略.next目录中的测试解析
  • 加载 next.config.js以启用 SWC 转换的标志

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

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

如果您的项目使用了模块路径别名, 则需要配置Jest来解析这些导入,将jsconfig.json文件中的路径选项与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"];
setupFilesAfterEnv: ["<rootDir>/jest.setup.js"];

Then, inside jest.setup.ts, add the following import:

import "@testing-library/jest-dom";
import "@testing-library/jest-dom";

您需要知道:extend-expectv6.0中被移除, 如果您使用的是 version 6 之前的@testing-library/jest-dom, 您需要导入@testing-library/jest-dom/extend-expect

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

将测试脚本添加到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 />组件是否成功渲染标题:

import Link from "next/link";

export default function Home() {
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 Page from "../app/page";

it("renders homepage unchanged", () => {
const { container } = render(<Page />);
expect(container).toMatchSnapshot();
});

运行您的测试

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

npm run test
# or
yarn test
# or
pnpm test

额外资源

您可能会发现以下资源对进一步阅读有所帮助: