假设 React 组件返回以下 JSX,它代表一个简单的 Collapsible:
<>
<button
onClick={onClickHandler}
aria-controls="collapsible"
aria-expanded={expanded}
aria-label="collapsible"
/>
<div
id="collapsible"
aria-hidden={!expanded}
/>
</div>
</>
根据哈佛:技术:可扩展部分和包含组件:可折叠部分 所提供的示例应该可供屏幕阅读器访问;真正的用户可以轻松地与组件交互。
我无法使用 React 测试库 的可访问角色来查询折叠内容。然而,内容是可访问的,因为按钮是可访问的并且它控制 div,从
aria-controls
属性感知。
是否有一种方法可以使用React测试库从aria-controls属性中获取元素,我还没有遇到过?类似于
screen.getByRole('button').aria-controls
?
这里有一些使用 React 测试库来根据
aria-controls
属性获取元素的示例代码:
import { render } from '@testing-library/react';
test('should get the element based on aria-controls attribute', () => {
// Render your component
const { getByRole, getByTestId } = render(<YourComponent />);
// Get the button element
const button = getByRole('button');
// Get the value of the aria-controls attribute
const ariaControls = button.getAttribute('aria-controls');
// Use the value of aria-controls to get the collapsible element
const collapsible = getByTestId(ariaControls);
// Assert that the element is found
expect(collapsible).toBeInTheDocument();
});
在此示例中,
getByTestId
用于根据aria-controls
属性的值获取可折叠元素。
JSX 代码中的可折叠元素添加了 data-testid
属性:
<div
id="collapsible"
aria-hidden={!expanded}
data-testid="collapsible"
/>
通过使用
getByTestId
并传递 ariaControls
的值作为参数,您可以根据 aria-controls
属性检索可折叠元素。
如果这个答案能解决您的问题,我很高兴。