Testing the presence of a Material UI Icon in Jest/Vitest can be done by using the Testing Library.
First, in the production code, assign a titleAccess
attribute to the icon. For example, if the
icon of interest is AddIcon
, the code would look like:
<AddIcon titleAccess="My Add Icon" />
This attribute would also surface to the user interface.
Then, in the test, test the presence of the icon using *byTitle
from the Testing Library.
Continuing the example above:
expect(screen.getByTitle("My Add Icon")).toBeInTheDocument();
Why not data-testid
?
One may be tempted to assign a data-testid
attribute to the icon and test the presence with
*byTestId
. However, this is inadvisable here because, unlike titleAccess
, the data-testid
attribute is not visible to the user. Testing by *byTestId
here effectively tests the internal
implementation, rather than the public interface of the app. As suggested by the Guiding Principles
of Testing Library:
It should be generally useful for testing the application components in the way the user would use it. … in general, utilities should encourage tests that use the components the way they’re intended to be used.
Testing Library official doc also recommends using *byTestId
only when
other queries do not work out.