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

Jest中如何精准选择icon-container内的Icon组件?

精准定位挂载组件中特定容器内的Icon组件

Got it! Since you're mounting the component (and can't use shallow because you need to test HOC functionality) and have multiple Icon instances floating around, here's how you can precisely target the one inside the .icon-container div:

方案1:使用React Testing Library(推荐)

React Testing Library aligns better with real user interactions, and adding data-testid attributes is a solid way to make tests more stable (class names might change with style updates, but test-ids are meant specifically for testing):

First, update your component code to include test-ids:

<div className='icon-container' data-testid="close-icon-container">
  <Icon name='close' data-testid="close-icon" />
</div>

Then in your test, target the parent container first, then narrow down to the Icon inside it:

import { screen, within } from '@testing-library/react';

// After mounting your component
const iconContainer = screen.getByTestId('close-icon-container');
// Precisely find the target Icon within the container
const closeIcon = within(iconContainer).getByTestId('close-icon');

// Now you can run assertions, like checking the name prop
expect(closeIcon).toHaveAttribute('name', 'close');

If you prefer not to add test-ids, you can use the container's class name combined with the Icon's role/text:

const iconContainer = screen.getByClassName('icon-container');
// Assuming Icon renders as an img element where the name prop maps to alt text
const closeIcon = within(iconContainer).getByRole('img', { name: /close/i });

方案2:使用Enzyme

If you're using Enzyme's mount method, you can chain selectors to narrow down your search:

import { mount } from 'enzyme';

const wrapper = mount(<YourComponent />);
// First find the .icon-container, then look for the Icon component inside it
const closeIcon = wrapper.find('.icon-container').find(Icon);

// Assert the Icon has the correct name prop
expect(closeIcon.prop('name')).toBe('close');

If your Icon is wrapped in a HOC and direct lookup for Icon doesn't work, you can target it by checking the component's displayName or props:

// If the HOC-wrapped component has a displayName like "WithHOC(Icon)"
const closeIcon = wrapper.find('.icon-container').find(component => 
  component.type().displayName?.includes('Icon') && component.prop('name') === 'close'
);

The core idea here is limiting your search scope: by first locking onto the .icon-container parent, you avoid accidentally picking up other Icon instances elsewhere in the rendered tree.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:21:15