Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I find and click a button that has no text using React Testing Library?

Many React Testing Library examples show how to find and click a button using the getByText query, as in:

fireEvent.click(getByText("Create"))

OR

userEvent.click(getByText("Create"))

However, it's common to have buttons with no text and only SVG icons, like Material UI's icon buttons or floating action buttons. Is there a recommended way to query for and click buttons like these? For context, I'm using the higher-level events provided by the companion user-event library.

like image 672
Roman Scher Avatar asked Feb 27 '20 00:02

Roman Scher


3 Answers

For icon buttons, add an aria-label attribute like below:

<button aria-label='edit'>
  <edit-icon />
</button>

Then in your test, pass the accessible name when calling getByRole()

screen.getByRole('button', {
  name: /edit/i
})

From the docs:

The accessible name is for simple cases equal to e.g. the label of a form element, or the text content of a button, or the value of the aria-label attribute.

like image 68
NearHuscarl Avatar answered Sep 28 '22 07:09

NearHuscarl


There are several ways to query an element, without seeing your hierarchy of elements, it's hard to say. But, there are several ways to query an element, an alternative to using getByText() could be getByRole('button'). If you want to add a data-testid to the element you could use getByTestId(). There are some more available queries found here: https://testing-library.com/docs/dom-testing-library/api-queries

like image 43
Alex K Avatar answered Sep 28 '22 05:09

Alex K


There are a bunch of different ways to do it, including everyone's favorite fallback, data-tested. But if you're using Material UI, you might be looking for the most "MUI" way to do this. Two ideas:

  • The MUI documentation shows all its buttons wrapped with a label element with an htmlFor property. You could do this and then use getByLabelText()
  • Your icon buttons probably have (and should!) a tooltip, and the tooltip text is probably coming from a title property. Then you can get the button with getByTitle().
like image 43
Alesh Houdek Avatar answered Sep 28 '22 05:09

Alesh Houdek