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.
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 aform
element, or the text content of abutton
, or the value of thearia-label
attribute.
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
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:
label
element with an htmlFor
property. You could do this and then use getByLabelText()
title
property. Then you can get the button with getByTitle()
.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With