Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to find an accessible element with the role "generic"

I have want to test this component:

const Tag = ({
  value,
  color,
}: TagProps): ReactElement => (
  <CellContentStyled role="generic" aria-label={value as string} color={color}>
    {value as string}
  </CellContentStyled>
);

And this is my test :

test('is rendered', () => {
    render(<Tag value="99" color="red" />);
    const tag = screen.getByRole('generic', { name: '99' });
    expect(tag).toBeVisible();
  });

But this test fails for some reason, here is the console log:

Unable to find an accessible element with the role "generic" and name "99"

    There are no accessible roles. But there might be some inaccessible roles. If you wish to access them, then set the `hidden` option to `true`. Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole

    Ignored nodes: comments, <script />, <style />
    <body>
      <div>
        <span
          aria-label="99"
          class="sc-bdvvtL dVKtID"
          color="red"
          role="generic"
        >
          99
        </span>
      </div>
    </body>

       5 |   test('is rendered', () => {
       6 |     render(<Tag value="99" color="red" />);
    >  7 |     const tag = screen.getByRole('generic', { name: '99' });
         |                           ^
       8 |     expect(tag).toBeVisible();
       9 |   });

if I use getByLabelText instead of getByRole my test works:

test('is rendered', () => {
    render(<Tag value="99" color="red" />);
    const circle = screen.getByLabelText('99');
    expect(circle).toBeVisible();
  });

Why my test fails even though I have defined the role generic ?

like image 627
Renaud is Not Bill Gates Avatar asked Sep 18 '25 08:09

Renaud is Not Bill Gates


1 Answers

Just check that and looks like it isn't work because testing-library is unable to find an element using the generic role with name option.

And that´s because generic its not a valid role, although testing-library is capable to finds elements with the role generic only when you not use name options.

If you change it to e.g. definition it wil work:

<CellContentStyled role="definition" aria-label={value as string} color={color}>
  {value as string}
</CellContentStyled>

const tag = screen.getByRole('definition', { name: '99' });

You just need to find the proper role for your case.

As testing-library docs says, you can check the possible roles here or here.

*A tip - if you just want to check if the element is in the document you can use .toBeInTheDocument() instead toBeVisible(). Check out the difference between each other here.

like image 109
Luis Paulo Pinto Avatar answered Sep 19 '25 23:09

Luis Paulo Pinto