We've all been faced with the challenge of choosing a better test ID for our component at some point. Why not leverage the logic we already use for CSS, like BEM (Block Element Modifier)? What is the best solution for achieving consistent and logical IDs across the board? What are the existing best practices?
✅ The Solution:
The best solution I've found with React is to create a custom hook that generates an ID, making it easier to locate them in our tests.
📚 Code Examples:
Create a custom hook useTestIdGenerator.ts:
Use the custom hook in your grid component:
Now, each element in your grid has unique "data-testid" attributes!
This approach greatly facilitates testing of dynamic components while maintaining the cleanliness and maintainability of your code. 🔥
An example test using this unique attribute:
Don't hesitate If you have another even better solution, to suggest it in the comments.
Top comments (0)