为什么 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/