reactjs - Aria-hidden 不会从查询中隐藏元素

标签 reactjs accessibility react-testing-library

为什么 RTL 将隐藏元素显示为可见?

expect(screen.queryByText(/months in operation\?/i)).not.toBeVisible()
Received element is visible: <label aria-hidden="true" for="monthsDropdown" />
expect(screen.queryByText(/months in operation \?/i)).not.toBeInTheDocument()
expected document not to contain element, found <label aria-hidden="true" for="monthsDropdown">Months in operation?</label> instead这个标签的父div也有显示样式:none;可见性:隐藏;高度:0;
这是预期的行为吗?

最佳答案

TL;博士: aria-hidden属性仅对 *ByRole 隐藏元素查询。

假设我们有以下带有两个按钮的组件。

const TestComponent = () => {
  return (
    <>
      <div style={{ display: "none", visibility: "hidden", height: 0 }}>
        <button>Hidden Button</button>
      </div>
      <button aria-hidden="true">Aria Hidden Button</button>
    </>
  );
};
即使第一个元素由于父元素的样式不可见,第二个元素也被排除在可访问性树之外 aria-hidden ,它们都可以通过 getByText 访问查询,因为它们都存在于 DOM 中。
// Both assertions will be pass
expect(screen.getByText("Hidden Button")).toBeInTheDocument();
expect(screen.getByText("Aria Hidden Button")).toBeInTheDocument();
但是,尝试使用 getByRole 访问它们查询将不可能进行,因为该查询会查看可访问性树 - 除非 hidden选项在查询中传递。
// Will not find the elements
const [hiddenButton, visibleButton] = screen.getAllByRole("button")

// Will return both elements
const [hiddenButton, visibleButton] = screen.getAllByRole("button", { hidden: true })
在可见性方面,第二个按钮可见而第一个按钮不可见。
// Both assertions will be pass
const [hiddenButton, visibleButton] = screen.getAllByRole("button", { hidden: true })
expect(hiddenButton).not.toBeVisible();
expect(visibleButton).toBeVisible();

关于reactjs - Aria-hidden 不会从查询中隐藏元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66479172/

相关文章:

reactjs - 如何/在何处将模型/ Controller 放入下一个 js 应用程序?

css - 如何通过 NPM 分发 CSS

accessibility - VoiceOver (Mac) 使用 tabindex 进行导航并忽略 aria- 属性

unit-testing - 单元测试使用Jest和React测试库对外部Click外部组件进行测试

reactjs - 我如何测试 url 搜索与 react 测试库的变化?

javascript - 函数外调用事件

node.js - 如何在 React.js 中显示 "email-id already exists"消息?

android - 使用 AccessibilityService 读取通知

html - 如何格式化 HTML5 中的 <section> 元素以向辅助设备用户提供有意义的见解?

reactjs - Webpack 5 & Jest - 类型 'toBeInTheDocument' 上不存在属性 'JestMatchers<HTMLElement>'