0Pricing
Next.js 15 Fullstack (App Router + Server Actions) · 课时

组件单元测试

使用 React Testing Library 和 Jest 等测试库,为 React 组件编写有效的单元测试

组件单元测试 是 CoddyKit 上的免费 Next.js 15 Fullstack (App Router + Server Actions) 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Next.js 15 Fullstack (App Router + Server Actions) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Intro to Unit Testing

Welcome to unit testing for React components! Unit testing helps ensure that the smallest, independent parts of your code — your components — work exactly as intended.

  • What is a unit test? It's a test for a 'unit' of code, often a single function or component.
  • Why test components? To catch bugs early, prevent regressions, and ensure your UI behaves predictably.
  • We'll focus on isolating components and testing their specific functionality.

Jest: The Test Runner

Jest is a popular JavaScript testing framework developed by Facebook. It's often used with React because it's fast, feature-rich, and includes everything you need for testing.

  • Test Runner: Executes your tests and reports results.
  • Assertion Library: Provides functions like expect to check if values meet certain conditions.
  • Mocking Library: Helps isolate code by replacing dependencies with 'mock' versions.

React Testing Library (RTL)

While Jest runs the tests, React Testing Library (RTL) helps you test React components in a way that mimics how users interact with them.

  • User-centric: RTL encourages testing actual user behavior, not internal implementation details.
  • Accessibility: Its querying methods (like getByRole) promote good accessibility practices.
  • It provides utilities to render components, query the DOM, and simulate user events.

Setting Up Your Test Environment

Next.js projects often come with Jest and RTL already configured or easily added. Here's what you'll typically use:

  • jest: The core test runner.
  • @testing-library/react: The main library for testing React components.
  • @testing-library/jest-dom: Provides custom Jest matchers for better DOM assertions (e.g., .toBeInTheDocument()).

These libraries work together to create a powerful testing setup.

Our First Component to Test

Let's create a simple MyButton component. It will display some text and execute a function when clicked. This is a common pattern for interactive UI elements.

We'll save this as components/MyButton.js:

import React from 'react';

function MyButton({ text, onClick }) {
  return (
    <button onClick={onClick}>
      {text}
    </button>
  );
}

export default MyButton;

Basic Test Structure & Render

Test files typically live alongside the component (e.g., components/MyButton.test.js). We use describe to group related tests and test (or it) for individual test cases.

First, let's just render our button and ensure it appears. We'll use render from RTL.

import { render, screen } from '@testing-library/react';
import MyButton from './MyButton';

describe('MyButton', () => {
  test('renders with the correct text', () => {
    render(<MyButton text="Click Me" onClick={() => {}} />);
    const buttonElement = screen.getByText(/Click Me/i);
    expect(buttonElement).toBeInTheDocument();
  });
});

Querying Elements with RTL

RTL provides various 'query' methods to find elements in the rendered component. It's best to use queries that resemble how a user would find elements, prioritizing accessibility.

  • getByRole: Finds elements by their ARIA role (e.g., 'button', 'heading'). Highly recommended!
  • getByText: Finds elements containing specific text.
  • getByLabelText: Finds elements associated with a label.

We used getByText in the previous example, which is great for text content.

Simulating Interaction & Assertions

Now, let's test if our button's onClick handler is called when clicked. We use fireEvent from RTL to simulate user events and jest.fn() to create a 'mock' function.

jest.fn() lets us track if the function was called, how many times, and with what arguments. .toHaveBeenCalledTimes() is a jest-dom matcher.

import { render, screen, fireEvent } from '@testing-library/react';
import MyButton from './MyButton';

describe('MyButton', () => {
  test('calls onClick handler when clicked', () => {
    const handleClick = jest.fn(); // Create a mock function
    render(<MyButton text="Submit" onClick={handleClick} />);
    
    const buttonElement = screen.getByRole('button', { name: /Submit/i });
    fireEvent.click(buttonElement); // Simulate a click
    
    expect(handleClick).toHaveBeenCalledTimes(1); // Assert it was called once
  });
});

Quick Check on Testing

You have a component called Greeting that displays 'Hello, [name]!'.

// components/Greeting.js

function Greeting({ name }) {
  return <h1>Hello, {name}!</h1>;
}
export default Greeting;

Which test snippet correctly asserts that 'Hello, Alice!' is rendered?

Recap: Unit Testing Components

Great job! You've taken your first steps into unit testing React components using Jest and React Testing Library.

  • Jest is your test runner and assertion framework.
  • React Testing Library helps you test components from a user's perspective.
  • You learned to render components, query for elements, simulate user interactions, and make assertions about component behavior.

Keep practicing to build robust and reliable Next.js applications!

常见问题解答

「组件单元测试」课时是免费的吗?

是的 — 「组件单元测试」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Next.js 15 Fullstack (App Router + Server Actions) 课程的其余内容,请升级到 CoddyKit PRO。 Next.js 15 Fullstack (App Router + Server Actions) 课程共包含 4 节课。

「组件单元测试」这节课中我会学到什么?

使用 React Testing Library 和 Jest 等测试库,为 React 组件编写有效的单元测试 你通过在浏览器中直接运行的动手代码来练习 Next.js 15 Fullstack (App Router + Server Actions),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Next.js 15 Fullstack (App Router + Server Actions) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Next.js 15 Fullstack (App Router + Server Actions) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。

「组件单元测试」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Next.js 15 Fullstack (App Router + Server Actions) 课中编写并运行代码吗?

能。每节 Next.js 15 Fullstack (App Router + Server Actions) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 组件单元测试
  2. 页面集成测试
  3. 使用 Playwright/Cypress 进行端到端测试
  4. 模拟与测试 API 路由
← 返回 Next.js 15 Fullstack (App Router + Server Actions)