使用Enzyme和Jest测试React Tab组件时mount无法找到点击元素
Why You're Seeing "0 Nodes Found" in Your TabbedArea Test
Let's break down exactly why this error is happening and how to fix it quickly:
The Root Cause
Your TabbedArea component completely relies on props.children to generate tab elements (<li>) and their corresponding content. When you render <TabbedArea/> without passing any child components in your tests:
this.props.childrenis eitherundefinedor an empty array- The
tabNodes()method returns nothing, so there are no<li>elements inside the<ul#navTabs> - Enzyme can't find any nodes to simulate a click on, hence the "0 found instead" error
The Fix: Pass Mock Child Components
You need to provide mock child components to TabbedArea in your tests. These mocks need to have the display prop (since your tab labels use child.props.display) and inner content for the tab panes.
First, create a simple mock tab component at the top of your test file:
// Mock a child component that matches what TabbedArea expects const MockTab = ({ display, children }) => <div>{children}</div>;
Then update your test cases to pass these mock tabs to TabbedArea:
Updated Test Code
describe('Given the Tabbed Area component is rendered', () => { describe('Initial Snapshots', () => { let component beforeEach(() => { // Pass mock tabs with display props and content component = shallow( <TabbedArea> <MockTab display="Tab 1">Content for Tab 1</MockTab> <MockTab display="Tab 2">Content for Tab 2</MockTab> </TabbedArea> ) }) it('should be as expected', () => { expect(shallowToJson(component)).toMatchSnapshot() }) }) describe('When clicking on the second tab', () => { let component let tab2 beforeEach(() => { component = shallow( <TabbedArea> <MockTab display="Tab 1">Content for Tab 1</MockTab> <MockTab display="Tab 2">Content for Tab 2</MockTab> </TabbedArea> ) tab2 = component.find('ul li').at(1); }) it('renders the second tab\'s content', () => { tab2.simulate('click'); component.update(); expect(shallowToJson(component)).toMatchSnapshot(); }); }); describe('Clicking on a tab', () => { it('triggers the handleClick method', () => { // Mount with mock tabs const wrapper = mount( <TabbedArea> <MockTab display="Tab 1">Content for Tab 1</MockTab> <MockTab display="Tab 2">Content for Tab 2</MockTab> </TabbedArea> ) const handleClickSpy = jest.spyOn(wrapper.instance(), 'handleClick'); const firstTab = wrapper.find('ul#navTabs li').first() firstTab.simulate('click') expect(handleClickSpy).toHaveBeenCalled(); }); }) })
Bonus Cleanup Tips
- I moved the component mounting logic into
beforeEachblocks or directly into theitblock to avoid state leakage between tests (your original third test hadwrapperdefined in thedescribeblock, which can cause issues if other tests modify it). - Using
toHaveBeenCalled()(instead oftoBeCalled()) is the more standard Jest syntax for spy assertions.
内容的提问来源于stack exchange,提问作者Mauro74
相关产品推荐
相关产品推荐

