Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 696
klabe Avatar asked Mar 13 '19 21:03

klabe


People also ask

Should I use test IDS?

In general, it's best to try and avoid using test-id if you can use any other form of selectors. For instance, when you want to query for an image element, try to use findByRole . Don't worry. You can filter these out in the outputted code, so they don't appear in the HTML.

What is a test ID?

A “Test ID” is three digits minimum in length, representing a dot notation “N. vv” Test Identifier. The value 'N' may be any length >= 1, indicating a specific test, and “vv” represents a two digit version.

Why you should avoid testing React components with test IDS?

Whilst in some cases it's unavoidable, testing the existence of data using these attributes could introduce false passes if we happen to pass in the incorrect information.

Why You Should Use React testing library?

React Testing Library is a set of helpers that let you test React components without relying on their implementation details. This approach makes refactoring a breeze and also nudges you towards best practices for accessibility.


1 Answers

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.

like image 114
Estus Flask Avatar answered Sep 19 '22 00:09

Estus Flask