Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't test element which is styled to display: none

I am trying to getByRole where I have an <li />, which is a child of a styled component.

The styled component is by default display: none, then under a min-width media query it's set to display: flex.

Running getByRole('listitem') works without the display: none but not with it, indicating that styled-components is telling the DOM that because it is set to display: none it doesn't exist.

This is despite the debug HTML output actually showing the <li /> being rendered:

TestingLibraryElementError: Unable to find an accessible element with the role "listitem"

    Here are the accessible roles:

      document:

      Name "":
      <body />

      --------------------------------------------------

    <body>
      <div>
        <div>
          <ul
              class="sc-gzVnrw sc-VigVT kjwzNy"
            >
              <li><!-- bunch of stuff --></li>
          </ul>
        </div>
      </div>
    </body>

I have tried mocking the media query matching using jest-matchmedia-mock, with no luck.

I don't care about testing the media query or styles at all, so is there a way I can tell styled components to not apply the styles during testing?

like image 384
Fela Maslen Avatar asked Jan 26 '23 01:01

Fela Maslen


1 Answers

I found a kind of solution which is a feature of dom-testing-library:

getByRole('listitem', { hidden: true })

This includes hidden items.

There is a commit detailing this change here: https://github.com/testing-library/dom-testing-library/pull/352/files/7cdfcfa466774ca78940330fe95d00c9e744b673

like image 150
Fela Maslen Avatar answered Jan 31 '23 02:01

Fela Maslen