Vitest
Vite 和 React 测试库经常一起用于单元测试。本指南将向您展示如何在 Next.js 中设置 Vitest 并编写您的第一个测试。
您需要知道: 由于
async服务器组件是 React 生态系统中的新特性,Vitest 目前不支持它们。虽然您仍可以对同步的服务器和客户端组件运行单元测试,但我们建议对async组件使用E2E 测试。
快速开始
您可以使用 Next.js 的 with-vitest示例,通过create-next-app快速开始:
npx create-next-app@latest --example with-vitest with-vitest-app
手动设置
要手动设置 Vitest,请安装vitest以及以下开发依赖包:
npm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
# or
yarn add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
# or
pnpm install -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
# or
bun add -D vitest @vitejs/plugin-react jsdom @testing-library/react @testing-library/dom
在项目根目录下创建一个vitest.config.ts|js 文件,并添加以下选项:
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
},
});
import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
test: {
environment: "jsdom",
},
});
更多有关 Vitest 配置的信息,请参考 Vitest 配置文档。
然后, 将test 脚本添加到 package.json文件中:
{
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"test": "vitest"
}
}
当您运行npm run test时,Vitest 默认会监听项目中的更改。
创建您的第一个 Vitest 单元测试
通过创建一个测试,检查<Page />组件是否成功渲染标题以确保一切正常:
import Link from "next/link";
export default function Page() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
);
}
import Link from "next/link";
export default function Page() {
return (
<div>
<h1>Home</h1>
<Link href="/about">About</Link>
</div>
);
}
import { expect, test } from "vitest";
import { render, screen } from "@testing-library/react";
import Page from "../app/page";
test("Page", () => {
render(<Page />);
expect(screen.getByRole("heading", { level: 1, name: "Home" })).toBeDefined();
});
import { expect, test } from "vitest";
import { render, screen } from "@testing-library/react";
import Page from "../app/page";
test("Page", () => {
render(<Page />);
expect(screen.getByRole("heading", { level: 1, name: "Home" })).toBeDefined();
});
您需要知道: 上述示例使用了常见的
__tests__目录规范,但测试文件也可以与app路由一起存放。
运行您的测试
然后,运行以下命令来执行您的测试:
npm run test
# or
yarn test
# or
pnpm test
# or
bun test
额外资源
您可能会发现以下资源很有帮助: