Member-only story
Why You Should Avoid Testing React Components With Test IDs
And how to test them instead

Testing Library is a popular library facilitating frontend component testing through different utilities. And if you’re familiar with it, you’re also familiar with getByTestId
— a pretty convenient way to target elements within the DOM to assert their existence. When I first learnt about testing React components, getByTestId
was my go-to. Simply add an data-testid
attribute to your element and query it in your tests. It may look something like this:
Component
Test
But what is this really telling us about the title
being displayed to the user? Nothing. We are simply asserting that a heading element exists. This value could be anything at all, and certainly not what the user expected.
This test may make more sense in the context of the Project
component’s parent where we might want to assert that a project has been loaded querying the heading above. Either way though, this value could be anything and our test would still pass.
When we test our React components, we should aim to test them in the same way that users would interact with them, and thus checking for the values they would see or actions they would carry out. Users aren’t interested in data attributes or classNames
. The creators of Testing Library themselves advocate for querying elements in various ways other than with data-testid
if possible:
In the spirit of the guiding principles, it is recommended to use this only after the other queries don’t work for your use case. Using data-testid attributes do not resemble how your software is used and should be avoided if possible.
Testing Library