如何组合复杂的选择器



我们面临着一个更复杂的UI,我们想要测试:

# Section Header A
- Option 1
[ ] checkbox
- Option 2
[ ] checkbox
# Section Header B
- Option 1
[ ] checkbox

我想在章节标题A的选项1中找到复选框,或者在伪代码中找到:

chain(
getByRole('fieldset', {name: 'Section Header A'}),
getByText('Option 1'),
getByRole('checkbox')
)

目前我们已经通过解决了这个问题

import {
getByText as globalGetByText,
getByRole as globalGetByRole,
} from '@testing-library/dom';
const { container } = render(<MyComponent />);
const sectionA = globalGetByRole(container, 'fieldset', {name: 'Section Header A'}),
const option1 = globalGetByText(sectionA, 'Option 1'),
const finallyMyElement = globalGetByRole(option1, 'checkbox')

注意全局导入重命名以避免与常规getBy*查询发生冲突,并显式传递容器引用。

根据react测试库的精神,我们没有使用测试。

有没有更直观的方法?

似乎within()解决了我的问题(https://testing-library.com/docs/dom-testing-library/api-within):

const { getByRole } = render(<MyComponent />);
const sectionA = getByRole('fieldset', {name: 'Section Header A'});
const option1 = within(sectionA).getByText('Option 1');
const finallyMyElement = within(option1).getByRole('checkbox');

请注意,这是未经测试的。

最新更新