Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to getByRole a button with image in React Testing Library

The best possible selector we can use in React Testing Library is getByRole(). This is good because we can select our node by it's role and accessibility name.

If we have a rendered component where we have multiple buttons - so I can't just use only getByRole('button') - and the button doesn't have text, meaning it doesn't have an accessible name, instead we have an image, how would I go about selecting that?

I know the image's accessible name derives from the alt attribute, and I am also aware I could use alternatives such as data-testid, however I would prefer to go with getByRole if there is a chance, so my tests resembles the way my software is used.

<Button onClick{() => void}>
 <img
  src={"foo"}
  alt={"alt text"}
/>
<Button/>

getByRole('button') will throw me an error as there will be multiple buttons on the wrapping component getAllByRole('button') will return an array with all the buttons, however I only want the one with the image

I tried getByRole('button', {name: "alt text"}) but this doesn't work, it kinda makes sense as it's a different node.

Any ideas if there is a logical way to get this using getByRole or I have to give up and resort to something like data-testid?

Thank you!

like image 663
anddak Avatar asked Jul 20 '20 17:07

anddak


People also ask

How do you use getByRole in react test library?

You can also query the returned element(s) by their accessible name by specifying the name argument: getByRole(expectedRole, name: 'The name') . The accessible name is for simple cases equal to the label of a form element, or the text content of a button, or the value of the aria-label attribute.

How do you test if a button is clicked in react testing library?

Properly Testing Button Clicks in React Testing Library In order to test button click events in React Testing Library, we need to use the fireEvent API: Once you have the rendered component, you will need to grab the button using screen.

How do I debug in react test library?

Simple Debugging With Default Test Runnerjest -p <path to your react application>/bin/<name-of-your-react-app> --coverage -t debug. test. js . jest -p ./src/bin/<name> --coverage -t debug.

What does Querybytestid return?

Returns a single element with the given testId value for the data-test-id attribute, defaulting to an exact match.


1 Answers

The best way that I know of to do this is by adding an aria-label to the button element. RTL will be able to query that as an accessible name with:

getByRole('button', { name: /button-name/i })

<Button aria-label="button-name" onClick{() => void}>
  <img
    src={"foo"}
    alt={"alt text"}
  />
<Button/>
like image 175
abdeboskey Avatar answered Sep 19 '22 19:09

abdeboskey