It might be the expected behavior, but I'd like to ensure and, if so, find an alternative way.
Suppose, there is a react element
<span role="presentation" className="ag-hidden">
where ag-hidden
is defined in a stylesheet as
.ag-hidden { visibility: hidden; }
or display: none
.
The stylesheet is injected in the DOM.
screen.getAllByRole("presentation")
does not return the element.<span data-test="el" className="ag-hidden">
I'd like to use the following, but it works strange:
const selector = ".ag-hidden"l
const hiddenByRoleAndSelector = screen.queryByRole("presentation", {
name: (_: string, el: Element) => {
// the required element gets here, and it matches the selector
console.log("n", el.matches(selector), el);
// so we return true for it
return el.matches(selector);
}
});
// ...but eventually get null
So how should I test elements, which are hidden by styles? (not resorting all the time to test-ids or localizable label, text, etc.)
The point of RTL is it tests what your users see on the screen. But I get that can be frustrating sometimes when you need to test a very specific element.
You have an escape hatch in the form of the underlying jest jsdom selectors. You can use querySelector
like you would in the browser to find a specific class, like the ag-hidden
for example. Or you can use data-test-id
as you already showed.