Skip to content

Shallow 渲染

一句话解释

Shallow 渲染 shows 组件不使用它的 children — useful for isolating 组件's logic 从它的 children.

用大白话说

Shallow 渲染是 方式到 测试组件不使用渲染它的 child 组件. 它渲染仅 组件它自己 — children appear as stub 元素使用它们的类型但 否内容.

For 示例, 如果你 有 <Profile> 哪个渲染 <Avatar> and <UserInfo>, shallow 渲染会 show <Profile> 使用 <Avatar /> and <UserInfo /> as placeholder 元素, 但 wouldn't 渲染什么's 内部 Avatar or UserInfo.

The benefit: 你测试组件's own logic in isolation, 不使用 worrying 关于它的 children's behavior. 如果 child 有 bug, 你的组件's 测试 still 通过.

The downside: 你're 不测试真实 rendered 输出. Modern 测试 philosophy (React 测试库) prefers 完整渲染因为它 测试真实 behavior. Shallow 渲染是 popular 使用 enzyme 但是 现在 discouraged 通过 React team.

示例

javascript
// Shallow rendering — test a component without its children

import { shallow } from '@testing-library/react'; // or enzyme
import { UserCard } from './UserCard';
import { Avatar } from './Avatar';  // child component

test('UserCard renders name without rendering Avatar', () => {
  const wrapper = shallow(<UserCard name="Alice" avatarUrl="x.png" />);

  // Avatar is NOT actually rendered — just stubbed as <Avatar />
  expect(wrapper.find(Avatar).length).toBe(1);
  expect(wrapper.find('.name').text()).toBe('Alice');

  // Avatar's internal logic is NOT exercised — that's the point
  // of shallow rendering: isolate the component under test.
});

浅渲染只渲染一层:UserCard 被渲染但其子组件 Avatar 被存根(不实际渲染)。这样将被测组件与其子组件的行为隔离。

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表