react-testing-library why use test id

react-testing-library is primarily intended for black-box functional testing. The use of selectors that are specific to the implementation can mean that a test tests the implementation rather than behaviour that could be observed by a user. While the use of data-testid designates that it is unambiguous and was added deliberately to make testing easier, while selectors can be ambiguous and be accidentally changed when the implementation is changed.

This doesn't mean that regular selectors shouldn't be used if they already serve the purpose, as long as a developer doesn't use them to test implementation in functional tests.

This also doesn't mean that react-testing-library cannot be used to test the implementation in isolated unit tests. It actually can but it lacks necessary features for that so this results in a lot of boilerplate code in comparison to Enzyme that was designed for that.


Good question. On the surface it wouldn't seem to make much sense as users can't see or identify testids either.

I'd say it comes down to minimising the fallout. If your test code queries by class or id, other devs are more likely to copypasta that than they are the testid usage, simply because you have to add testids to the components, which as you've seen, doesn't feel right. Using a testid says "I have no good options here, I'm forced to do this".