Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

html - Injecting mark or span tag for highlighting breaks component testing

I am using react testing library to test a dropdown component to check if a particular option is available on search and it used to work as expected using the following query that asserts that the option is selected or not.

expect(
      screen.getByRole('option', {
        name: 'ZAT',
        selected: false,
      })
    ).toBeInTheDocument();

Introduced a new feature where I highlight the search term in the options list and the tests started breaking as introducing the mark or span ( with styling applied ) tag is creating an empty space in the test renderer because of which the query is no longer able to find the option with the exact text due to the spaces generated in the accessible element name ( even though the white spaces are collapsed in the DOM )

enter image description here

Wondering if anyone has any pointers as to how I can fix this so that the tests work as expected.

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After some investigation found a better solution to the issue I am facing. Instead of relying on the default name that gets associated with the element we can provide the aria-label attribute to the elements in question as ARIA triumphs all as per the this article - Using aria

Injecting the aria-label to the element seems to fix the problem and the tests are working as expected without any changes.

<li
  aria-label="ZAT"
  aria-selected="false"
  class="SearchableDropdown__StyledMenuContent-l5l1l4-4 iNSwly"
  id="downshift-1-item-2"
  role="option"
>
   ....
</li>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...