React 组件测试使用测试库
中等 约 50 分钟
你将构建什么
小 React app 使用计数器组件 and todo 列表组件, tested 使用 React 测试库 using 用户-centric 查询 and interactions.
学习目标
- 设置 React 测试库 使用 Jest
- 测试组件渲染使用 getByRole and getByText
- 测试用户 interactions 使用 userEvent
- 测试异步组件 behavior
- Follow 测试库 philosophy 的测试如 用户
前置要求
- 基础 React knowledge (组件, 状态, 事件)
- 已完成项目 1 or equivalent Jest experience
- 节点.js and npm 安装
步骤
- 1
设置 React 测试环境
安装 dependencies:
npm 安装 --保存-dev @测试-库/react @测试-库/jest-DOM @测试-库/用户-事件.代码// jest.setup.js import '@testing-library/jest-dom';预期结果
测试库 包是 安装.
- 2
创建计数器组件
创建简单计数器组件使用 increment and decrement buttons.
代码function Counter() { const [count, setCount] = React.useState(0); return ( <div> <span role="display">{count}</span> <button onClick={() => setCount(c => c + 1)}>Increment</button> <button onClick={() => setCount(c => c - 1)}>Decrement</button> </div> ); }预期结果
计数器组件是 创建.
- 3
测试计数器组件
编写测试那个 interact 使用组件如 真实用户会 — 点击 buttons and 检查 display.
代码import { render, screen } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import Counter from './Counter'; test('increments counter', async () => { render(<Counter />); expect(screen.getByRole('display')).toHaveTextContent('0'); await userEvent.click(screen.getByText('Increment')); expect(screen.getByRole('display')).toHaveTextContent('1'); });预期结果
计数器测试通过.
- 4
创建 and 测试 Todo 组件
创建 TodoList 组件那个添加项. 测试添加项 通过输入 and button.
代码test('adds a todo item', async () => { render(<TodoList />); const input = screen.getByRole('textbox'); const button = screen.getByText('Add'); await userEvent.type(input, 'Buy milk'); await userEvent.click(button); expect(screen.getByText('Buy milk')).toBeInTheDocument(); });预期结果
Todo 测试通过 — 项 appears 之后添加.
- 5
添加边界测试用例
为测试套件添加边界值用例:空数组、零值、最大值、null/undefined。边界用例是最容易出错的地方,必须显式覆盖。
代码describe("boundary cases", () => { it("handles empty array", () => { expect(func([])).toEqual([]); }); it("handles zero", () => { expect(func(0)).toBe(0); }); it("handles null", () => { expect(() => func(null)).toThrow(); }); it("handles max value", () => { expect(func(Number.MAX_SAFE_INTEGER)).toBeDefined(); }); });预期结果
所有边界用例通过,无未捕获异常。
自己动手试试
你学到了什么
你学习到 测试 React 组件方式用户 interact 使用它们: querying 通过 role and 文本, using userEvent for realistic interactions, and asserting on 可见输出. 这个方法创建 robust 测试那个 survive refactoring.
相关资源
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。