如何在 react-testing-library 中测试 parent child 关系?
How to test parent child relationship in react-testing-library?
假设这是我的 HTML,使用 semantic-ui 创建的。
我从下拉列表中 select 编号 35,结果变为:
<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>
理想情况下,我想像这样测试 parent 项 children:
- parent: name="流派"
- child: value="35", text = Comedy
这似乎不可能。
我只能测试一个 select 或级别,例如 - getByText('Comedy')
这太笼统了,因为同一页上还有其他 'Comedy' 元素。
那么如何 select 这样的事情:
getByWhatever('Some parent').getChildByWhatever('Some child').exists()
您可以使用 within
查询来获取另一个特定元素中的元素。
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');
假设这是我的 HTML,使用 semantic-ui 创建的。
我从下拉列表中 select 编号 35,结果变为:
<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>
理想情况下,我想像这样测试 parent 项 children:
- parent: name="流派"
- child: value="35", text = Comedy
这似乎不可能。
我只能测试一个 select 或级别,例如 - getByText('Comedy')
这太笼统了,因为同一页上还有其他 'Comedy' 元素。
那么如何 select 这样的事情:
getByWhatever('Some parent').getChildByWhatever('Some child').exists()
您可以使用 within
查询来获取另一个特定元素中的元素。
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');