0Pricing
Frontend Academy · 课时

@testing-library/react:render 与 userEvent

在模拟 DOM 中渲染组件,按角色和标签文本查询,使用 userEvent 触发用户交互,并断言可见输出。

@testing-library/react:render 与 userEvent 是 CoddyKit 上的免费 Frontend Academy 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Frontend Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Frontend Academy 课程共包含 4 节课。

Testing Library 理念

@testing-library 鼓励编写贴近用户与界面交互方式的测试。按角色、标签和文本查询,而不是按 CSS 类名或组件内部结构等实现细节查询。

安装 Testing Library

安装 React 版 Testing Library 和用于模拟用户交互的 userEvent 包。

npm install -D @testing-library/react @testing-library/user-event @testing-library/jest-dom

render()——挂载组件

render(<Component />) 会将组件挂载到模拟的 DOM 中。它会返回用于查找元素的查询函数。

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

test('renders button with label', () => {
  render(<Button label="Submit" onClick={() => {}} />);
  expect(screen.getByRole('button', { name: 'Submit' })).toBeInTheDocument();
});

查询元素

建议按以下顺序选择查询方式:getByRole(可访问)、getByLabelText、getByPlaceholderText、getByText、getByDisplayValue。测试元素不存在时使用 queryBy*。对于异步出现的元素,使用 findBy*。

// Prefer (accessible):
screen.getByRole('button', { name: /submit/i });
screen.getByLabelText('Email');

// For text content:
screen.getByText('Welcome!');

// Existence check:
expect(screen.queryByText('Error')).not.toBeInTheDocument();

// Async appearance:
await screen.findByText('Data loaded');

userEvent——模拟用户操作

userEvent 会模拟真实的用户交互:输入、点击和键盘导航。它比旧版的 fireEvent 更贴近真实情况。

import userEvent from '@testing-library/user-event';

test('typing in input', async () => {
  const user = userEvent.setup();
  render(<SearchInput />);

  const input = screen.getByRole('textbox', { name: /search/i });
  await user.type(input, 'react hooks');

  expect(input).toHaveValue('react hooks');
});

测试表单提交

填写表单字段并提交。断言操作结果——也就是用户提交后看到的内容。

test('submitting the login form', async () => {
  const onLogin = jest.fn();
  const user = userEvent.setup();
  render(<LoginForm onLogin={onLogin} />);

  await user.type(screen.getByLabelText('Email'), 'alice@example.com');
  await user.type(screen.getByLabelText('Password'), 'secret123');
  await user.click(screen.getByRole('button', { name: /sign in/i }));

  expect(onLogin).toHaveBeenCalledWith({ email: 'alice@example.com', password: 'secret123' });
});

jest-dom 自定义匹配器

@testing-library/jest-dom 添加了实用的匹配器:toBeInTheDocument()、toBeVisible()、toBeDisabled()、toHaveValue()、toHaveClass()、toHaveFocus()。

测试异步组件更新

对于异步出现的元素(例如获取数据后或超时后出现的元素),使用 waitFor() 或 findBy*。

test('shows data after loading', async () => {
  render(<UserList />);

  expect(screen.getByRole('status')).toHaveTextContent('Loading');

  const items = await screen.findAllByRole('listitem');
  expect(items).toHaveLength(3);
});

测试加载和错误状态

模拟 fetch 响应,以测试不同的状态。MSW(模拟服务工作线程)是在测试中模拟 API 响应的最佳工具。

可访问性测试

Testing Library 会自然地促进可访问性——如果您无法通过角色或标签查询某个元素,那么它很可能无法访问。在测试中使用 jest-axe 进行自动化可访问性审查。

不要测试实现细节

避免:按 CSS 类名查询、导入组件内部状态、测试是否调用了特定方法。请从用户视角测试行为:用户看到了什么,以及交互时发生了什么。

快速检查

查找交互元素时,应优先使用哪个 Testing Library 查询函数?

回顾:@testing-library/react

render() 会将组件挂载到模拟的 DOM 中。按角色、标签和文本查询,而不是查询实现细节。使用 userEvent.setup() 模拟更真实的用户交互。使用 findBy* 查找异步元素。使用 jest-dom 编写易读的断言。从用户视角进行测试:测试用户看到的内容和执行的操作。具有良好可访问性的组件更容易测试。

常见问题解答

「@testing-library/react:render 与 userEvent」课时是免费的吗?

是的 — 「@testing-library/react:render 与 userEvent」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Frontend Academy 课程的其余内容,请升级到 CoddyKit PRO。 Frontend Academy 课程共包含 4 节课。

「@testing-library/react:render 与 userEvent」这节课中我会学到什么?

在模拟 DOM 中渲染组件,按角色和标签文本查询,使用 userEvent 触发用户交互,并断言可见输出。 你通过在浏览器中直接运行的动手代码来练习 Frontend Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Frontend Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Frontend Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「@testing-library/react:render 与 userEvent」课时需要多长时间?

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

我能在这节 Frontend Academy 课中编写并运行代码吗?

能。每节 Frontend Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. Jest 设置与基础测试
  2. @testing-library/react:render 与 userEvent
  3. @testing-library/vue:挂载组件
  4. 模拟模块与 API 调用
← 返回 Frontend Academy