Reputation: 443
I use enzyme + jest to test our react application.
How to find just below elements by selector if rendered html has nested same structure?
I want to parent two button
elements if render
method returns following HTML.
<ul>
<li><button ...>parent1</button></li>
<li><button ...>parent2</button>
<ul>
<li><button ...>child1</button></li>
<li><button ...>child2</button></li>
</ul>
</li>
</ul>
In enzyme 2.7.1, I can get parent two button
elements by > ul > li > button
selector like following code.
(uh... it's obviously weird selector. but it did work)
const component = shallow(<Sample {...props}/>)
const parentButtons = component.find('> ul > li > button')
expect(parentButtons.length).toBe(2)
But in enzyme 3.3.0 occur an "Failed to parse selector" error.
ul > li > button
returns all buttons which contain child buttons, it makes sense.:root
pseudo selector, it isn't supported enzyme yet.Does anyone have any idea?
Upvotes: 3
Views: 6971
Reputation: 2074
Assuming that given DOM structure won't change (at least that parent
buttons will always be first nodes of top li
's) this should work:
const parentButtons = component.find('ul').first().children().map(child => child.childAt(0));
const parentButtonsTexts = component.find('ul').first().children().map(child => child.childAt(0).text());
expect(parentButtons).toHaveLength(2);
expect(parentButtonsTexts).toEqual(['parent1', 'parent2']);
Upvotes: 4