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

使用React Testing Library测试自定义组件的后代元素是否符合预期

实现方案

假设你使用的是 React Testing Library 生态,搭配@testing-library/jest-dom提供的断言匹配器,测试代码可以按如下方式补充:

import { screen } from '@testing-library/react';
import '@testing-library/jest-dom';

it('Should render the component with all element', () => {
  render(<MyDiv faClassName="fa fa-pencil">Hello</MyDiv>)

  // 1、验证容器内正确渲染了i标签
  const iconElement = screen.getByRole('img', { hidden: true });
  expect(iconElement).toBeInTheDocument();
  expect(iconElement).toHaveClass('fa', 'fa-pencil');

  // 2、验证文本Hello是被div标签包裹
  const textElement = screen.getByText('Hello');
  expect(textElement.parentElement.tagName).toBe('DIV');
}

逻辑说明

  • 校验i标签的逻辑:font-awesome的i标签默认无语义role,查询时加{ hidden: true }可以匹配到隐藏语义元素,同时校验class属性和存在性,确保渲染的i标签完全符合传入的参数。
  • 校验文本父标签的逻辑:先通过文本内容定位到Hello的文本节点,直接校验它的父元素标签名是否为大写的DIV(DOM原生tagName属性返回值为全大写),即可确认文本没有被其他类型标签包裹。

如果你更习惯直接通过选择器查询,也可以使用render返回的container实例实现相同效果:

it('Should render the component with all element', () => {
  const { container } = render(<MyDiv faClassName="fa fa-pencil">Hello</MyDiv>)

  // 校验i标签
  expect(container.querySelector('i.fa.fa-pencil')).toBeInTheDocument();

  // 校验文本父标签
  const textWrapper = container.querySelector('div:nth-child(2)');
  expect(textWrapper).toHaveTextContent('Hello');
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 14:57:00