Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@testing-library getByRole does not return elements hidden by CSS

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.
  • if the stylesheet is removed from the DOM, the element is found.
  • a similar hidden element is found by test id, like this:
    <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.)

Here is the codesandbox demo.

like image 278
Distagon Avatar asked Oct 30 '25 16:10

Distagon


2 Answers

queryByRole does include hidden properties if you query for it:

  const hiddenDiv = screen.queryByRole('presentation', { hidden: true });
like image 179
Jim Sosa Avatar answered Nov 01 '25 09:11

Jim Sosa


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.

like image 42
omid Avatar answered Nov 01 '25 09:11

omid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!