Kse*_*nia 10 accessibility reactjs react-testing-library
为什么 RTL 将隐藏元素显示为可见?
expect(screen.queryByText(/months in operation\?/i)).not.toBeVisible()
Run Code Online (Sandbox Code Playgroud)
Received element is visible: <label aria-hidden="true" for="monthsDropdown" />
expect(screen.queryByText(/months in operation \?/i)).not.toBeInTheDocument()
Run Code Online (Sandbox Code Playgroud)
expected document not to contain element, found <label aria-hidden="true" for="monthsDropdown">Months in operation?</label> instead
该标签的父div也有display:none;的样式。可见性:隐藏;高度:0;
这是预期的行为吗?
jul*_*ves 12
TL;DR:该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>
</>
);
};
Run Code Online (Sandbox Code Playgroud)
尽管第一个元素由于父元素的样式而不可见,并且第二个元素被从可访问性树中排除aria-hidden,但它们都可以通过查询访问,getByText因为它们都存在于 DOM 中。
// Both assertions will be pass
expect(screen.getByText("Hidden Button")).toBeInTheDocument();
expect(screen.getByText("Aria Hidden Button")).toBeInTheDocument();
Run Code Online (Sandbox Code Playgroud)
但是,尝试使用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 })
Run Code Online (Sandbox Code Playgroud)
就可见性而言,第二个按钮可见,而第一个按钮不可见。
// Both assertions will be pass
const [hiddenButton, visibleButton] = screen.getAllByRole("button", { hidden: true })
expect(hiddenButton).not.toBeVisible();
expect(visibleButton).toBeVisible();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6523 次 |
| 最近记录: |