单元测试与集成测试
使用 Jest 和 React Testing Library 为 React 组件和 Next.js 函数编写有效的单元测试与集成测试。
单元测试与集成测试 是 CoddyKit 上的免费 Next.js 15 Fullstack Web Apps 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack Web Apps 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why We Test Our Code
Welcome! In modern web development, especially with complex applications built with Next.js, ensuring your code works as expected is crucial. This is where testing comes in.
- Reliability: Tests prevent bugs and regressions.
- Maintainability: Well-tested code is easier to refactor and update.
- Confidence: You can deploy new features with greater assurance.
We'll focus on Unit Tests (small, isolated parts) and Integration Tests (how parts work together).
Setting Up Jest & RTL
Jest is a popular JavaScript testing framework, and React Testing Library (RTL) is a set of utilities for testing React components. Together, they form a powerful duo for Next.js apps.
First, install the necessary packages:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom jest-environment-jsdomYour First Unit Test (Function)
A unit test checks a small, isolated piece of code, like a single function. Let's create a simple utility function and then write a test for it.
Here's our utility:
// utils/math.js
function add(a, b) {
return a + b;
}
// This block makes the file directly runnable via Node.js
if (typeof require !== 'undefined' && require.main === module) {
console.log("Running add(5, 3):", add(5, 3)); // Expected: 8
console.log("Running add(10, -2):", add(10, -2)); // Expected: 8
}Testing the 'add' Function
Now, let's write a test for our add function. Jest uses describe to group tests and test (or it) for individual test cases. expect is used for assertions.
Save this in utils/math.test.js:
// utils/math.test.js
import { add } from './math';
describe('add function', () => {
test('should correctly add two positive numbers', () => {
expect(add(1, 2)).toBe(3);
});
test('should handle negative numbers', () => {
expect(add(5, -3)).toBe(2);
});
});
// To run tests: npx jestIntroducing React Testing Library
React Testing Library (RTL) encourages testing components in a way that mimics how users interact with them. Instead of checking internal state, you query the DOM for elements a user would see or interact with.
render: Mounts a React component into a virtual DOM.screen: Provides methods to query the rendered DOM (e.g.,getByText,getByRole).@testing-library/jest-dom: Adds custom matchers liketoBeInTheDocument.
Testing a Simple React Component
Let's test a basic button component. We'll ensure it renders with the correct text.
First, the component (components/Button.jsx):
// components/Button.jsx
export default function Button({ label, onClick }) {
return (
<button onClick={onClick}>
{label}
</button>
);
}Testing Component Rendering
Now, the test for our Button component. We use render to put it on the screen and screen.getByText to find it, then toBeInTheDocument to confirm its presence.
Save this as components/Button.test.jsx:
// components/Button.test.jsx
import { render, screen } from '@testing-library/react';
import Button from './Button';
describe('Button component', () => {
test('renders with the correct label', () => {
render(<Button label="Click Me" />);
const buttonElement = screen.getByText(/Click Me/i);
expect(buttonElement).toBeInTheDocument();
});
});Simulating User Interactions
Beyond just rendering, we need to test how components respond to user actions. RTL's fireEvent (or userEvent for more realistic interactions) helps simulate clicks, input changes, etc.
We can check if a function passed via props is called.
// components/Button.test.jsx (continued)
import { render, screen, fireEvent } from '@testing-library/react';
import Button from './Button';
describe('Button component interactions', () => {
test('calls the onClick handler when clicked', () => {
const handleClick = jest.fn(); // Jest mock function
render(<Button label="Click Me" onClick={handleClick} />);
const buttonElement = screen.getByText(/Click Me/i);
fireEvent.click(buttonElement);
expect(handleClick).toHaveBeenCalledTimes(1);
});
});Integration: Testing Route Handlers
Next.js Route Handlers (API routes in the App Router) are server-side functions. We can test them by directly importing and calling their HTTP methods (like GET, POST) and mocking Next.js's request/response objects.
Here's an example:
// app/api/hello/route.js
import { NextResponse } from 'next/server';
export async function GET() {
return NextResponse.json({ message: 'Hello from API!' }, { status: 200 });
}
// app/api/hello/route.test.js
import { GET } from './route';
describe('GET /api/hello', () => {
test('should return a greeting message with status 200', async () => {
// No need to mock NextRequest/NextResponse directly for simple cases
// as NextResponse.json returns a standard Response object.
const response = await GET();
const json = await response.json();
expect(response.status).toBe(200);
expect(json.message).toBe('Hello from API!');
});
});Best Practices for Effective Tests
To write useful and maintainable tests:
- Test user behavior: Focus on what the user sees and does, not internal component state.
- Keep tests focused: Each test should ideally check one thing.
- Make tests fast: Slow tests discourage running them often.
- Readability: Write clear tests that are easy to understand.
- Mock dependencies: Use
jest.mock()orjest.fn()to isolate units and prevent external factors from affecting tests.
Quick Check
Which of the following statements about testing in Next.js with Jest and React Testing Library is TRUE?
Recap: Unit & Integration Testing
Great job! You've learned the fundamentals of unit and integration testing in Next.js:
- Jest is your testing framework.
- React Testing Library helps test components like a user would.
- Unit tests verify small, isolated code units.
- Integration tests check how different parts (like components and APIs) work together.
- You can test functions, React components, and Next.js Route Handlers.
- Best practices include focusing on user behavior and mocking dependencies.
Next up, we'll explore End-to-End testing for full application flows!
常见问题解答
「单元测试与集成测试」课时是免费的吗?
是的 — 「单元测试与集成测试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack Web Apps 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack Web Apps 课程共包含 4 节课。
「单元测试与集成测试」这节课中我会学到什么?
使用 Jest 和 React Testing Library 为 React 组件和 Next.js 函数编写有效的单元测试与集成测试。 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack Web Apps,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Next.js 15 Fullstack Web Apps 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack Web Apps 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「单元测试与集成测试」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Next.js 15 Fullstack Web Apps 课中编写并运行代码吗?
能。每节 Next.js 15 Fullstack Web Apps 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。