You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在控制台打印React组件层级?Jest测试场景需求

在Jest中打印React组件层级的方法

你可以通过以下几种官方或常用工具实现需求,无需额外寻找小众第三方包:

1. 使用官方的react-test-renderer(推荐)

React官方提供的测试渲染器,自带debug()方法可直接打印组件层级结构(非DOM),格式清晰易读。

示例代码:

import renderer from 'react-test-renderer';
import MyComponent from './MyComponent';

test('查看组件层级', () => {
  const componentInstance = renderer.create(<MyComponent />);
  // 直接打印组件树到控制台
  componentInstance.debug();
});

执行测试后,控制台会输出类似这样的层级结构:

<MyComponent userId={123}>
  <UserProfile>
    <Avatar size="medium" />
    <UserStats />
  </UserProfile>
</MyComponent>

如果需要获取结构化数据(比如JSON格式),可以用toJSON()方法:

const componentTree = renderer.create(<MyComponent />).toJSON();
console.log(JSON.stringify(componentTree, null, 2));

2. 用Jest自带的pretty-format格式化组件

pretty-format是Jest内置的格式化工具,配合React插件可将组件元素转换成可读性强的文本结构。

示例代码:

import prettyFormat from 'pretty-format';
import MyComponent from './MyComponent';

const reactFormatPlugin = require('pretty-format/plugins/react');

test('格式化打印组件层级', () => {
  const formattedTree = prettyFormat(<MyComponent />, {
    plugins: [reactFormatPlugin],
    printFunctionName: true, // 显示组件函数/类名称
    indent: 2, // 缩进格式化
  });
  console.log(formattedTree);
});

3. 结合@testing-library/react获取组件树

如果你已经在用@testing-library/react,可以通过render方法返回的result对象访问组件实例,再配合上述工具打印:

import { render } from '@testing-library/react';
import prettyFormat from 'pretty-format';
import MyComponent from './MyComponent';

test('打印组件层级', () => {
  const { result } = render(<MyComponent />);
  console.log(prettyFormat(result.container.firstChild, {
    plugins: [require('pretty-format/plugins/react')],
  }));
});

内容的提问来源于stack exchange,提问作者Eric

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 03:31:06