Inspiraller
Inspiraller

Reputation: 3806

How to test parent child relationship in react-testing-library?

Lets say this is my HTML, created from using semantic-ui.

I select number 35 from my dropdown and the result becomes this:

<div name="genre" style="width:400px" role="combobox" aria-expanded="false" class="ui compact fluid multiple search selection dropdown">
  <a class="ui label" value="35">Comedy<i aria-hidden="true" class="delete icon"></i></a>

  <div role="option" aria-checked="false" aria-selected="true" class="selected item" style="pointer-events: all;"><span class="text">Comedy</span></div>
</div>

Ideally I want to test the parent items children like this:

This doesn't seem possible.

I can only test one selector level for example - by getByText('Comedy') which is too generic since there are other 'Comedy' elements on the same page.

So how to select something like this:

getByWhatever('Some parent').getChildByWhatever('Some child').exists()

Upvotes: 2

Views: 3425

Answers (1)

juliomalves
juliomalves

Reputation: 50308

You can use the within query to get elements within another specific element.

const combobox = screen.getByRole('combobox'); // Retrieve the parent
expect(combobox).toHaveAttribute('name', 'genre');
const link = within(combobox).getByRole('link', { name: 'Comedy' }); // Retrieve the link child from within the parent
expect(link).toHaveAttribute('value', '35');

Upvotes: 2

Related Questions