Search code examples
reactjsreact-testing-library

react-testing-library why use test id


I am using react-testing-library. In the document it says

Note that using this as an escape hatch to query by class or id is a bad practice because users can't see or identify these attributes. Use a testid if you have to.

I was wondering why this is a bad practice. I do not want to litter my code with data-testid. I already have ids and classNames in my component. Why is it not recommended to use them?

Thanks.


Solution

  • 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".