Accepted answer

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

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

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.


For me non of above answers works, what is worked for me is:

screen.getByRole('button', { name: /<icon-file-name>/i });

In my case the button with only svg file.


The best possible way of finding an element is to simulate the most User oriented approach. So probably User expects the role button and then searches for an icon in your case. That's where semantic HTML plays a role for elements structure inside your component.

MUI buttons also implement a name attribute for some icon buttons used inside another component e.g. Select and I strongly recommend using this attribute for testing purpose.

Please remember that, your tests should be unaware of implementation, so identification should rely on name, role, label and other "natural" attributes. But if that is not possible using data-testid should be your last resort.

A very good overall approach (not only for icon buttons) is to specify a name property alongside role in getByRole query:

const listOpenButton = screen.getByRole("button", { name: /open/i });

Also a data-testid approach:

const listOpenButton = screen.getByTestId("myButtonId");


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().


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:

Related Query

More Query from same tag