Search code examples
reactjstestingjestjsreact-testing-librarytesting-library

Unable to use getByRole on listitem with a specific name - RTL


My apologies If this is a duplicate question. I couldn't find an answer anywhere else.

Component:

<ul>
  <li>Pending tasks</li>
</ul>

Test code:

expect(getByRole("listitem", { name: "Pending tasks" })).toBeInTheDocument();

Error:

TestingLibraryElementError: Unable to find an accessible element with the role "listitem" and name "Pending tasks"

Here's the codesandbox link to reproduce this: https://codesandbox.io/s/wandering-browser-mrf78?file=/src/App.test.js

Even though it shows error saying unable to find, it still suggests me li & ul tags as the available roles.

Here are the accessible roles:
 --------------------------------------------------
  list:

  Name "":
  <ul />

  --------------------------------------------------
  listitem:

  Name "":
  <li />

Could someone please explain what am I missing here? I tried using regex matchers but no luck.


Solution

  • A listitem is named by the Author by spec (https://www.w3.org/TR/wai-aria-1.2/#listitem).

    Name from author is defined as

    author: name comes from values provided by the author in explicit markup features such as the aria-label attribute, the aria-labelledby attribute, or the host language labeling mechanism, such as the alt or title attributes in HTML, with HTML title attribute having the lowest precedence for specifying a text alternative.

    -- https://www.w3.org/TR/wai-aria-1.2/#namecalculation

    That does not mean you should give it an aria-label. You should only add aria attributes if you have identified an issue with assistive technology.

    For your specific query I'd suggest getAllByRole('listitem').find(listitem => listitem.textContent === 'Pending task').