Having the following HTML output:
<ul>
<li>Menu 1</li>
<li>Menu 2(Parent)
<ul>
<li>Child 1</li>
<li>Child 2</li>
<li>Child 3 (Parent 2)
<ul>
<li>Child 4</li>
<li>Child 5</li>
</ul>
</li>
</ul>
</li>
</ul>
I need to test whether the elements exist and are properly nested. I can write a test as follows:
it('should render nested elements', () => {
<MyComponent />
expect(screen.getByText('Menu 1').toBeInDocument())
expect(screen.getByText('Menu 2(Parent)').toBeInDocument())
expect(screen.getByText('Child 3 (Parent 2)').toBeInDocument())
expect(screen.getByText('Child 5').toBeInDocument())
}
and that will tell me it does exist in the DOM but this test will also pass for the following HTML and I do not want that:
<ul>
<li>Menu 1</li>
<li>Menu 2(Parent)</li>
<li>Child 1</li>
<li>Child 2</li>
<li>Child 3 (Parent 2)</li>
<li>Child 4</li>
<li>Child 5</li>
</ul>
How can I test if the element exists and it is properly nested?