如何组合复杂的选择器
How to combine complex selectors
我们面临着更复杂的UI我们要测试:
# Section Header A
- Option 1
[ ] checkbox
- Option 2
[ ] checkbox
# Section Header B
- Option 1
[ ] checkbox
我想在 Section Header 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')
请注意 global... 导入重命名以避免与常规 getBy* 查询发生冲突并显式传递容器引用。
根据 react-testing-library 的精神,我们没有使用 testids。
有没有更直观的方法?
看来 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');
请注意,这是未经测试的。
我们面临着更复杂的UI我们要测试:
# Section Header A
- Option 1
[ ] checkbox
- Option 2
[ ] checkbox
# Section Header B
- Option 1
[ ] checkbox
我想在 Section Header 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')
请注意 global... 导入重命名以避免与常规 getBy* 查询发生冲突并显式传递容器引用。
根据 react-testing-library 的精神,我们没有使用 testids。
有没有更直观的方法?
看来 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');
请注意,这是未经测试的。