The data-testid
attribute is a custom attribute commonly used in testing to uniquely identify elements in the HTML markup. Unlike standard attributes like id
, class
, or name
, which are typically used for styling or JavaScript interactions, the data-testid
attribute is specifically intended for testing purposes.
When writing tests, using data-testid
allows you to target elements without relying on their structure or other attributes that might change. It provides a stable and clear way to select elements in your tests, making your test suite more robust and easier to maintain.
Hereβs an example of how you might use data-testid
in your component:
<button data-testid="submit-button">Submit</button>
In this example, the data-testid
attribute is added to a button element with the value "submit-button"
. In your test code, you can then query this button using getByTestId
:
const submitButton = screen.getByTestId('submit-button');
Using data-testid
helps decouple your tests from the implementation details of your components, making them less likely to break due to changes in your component's structure or other attributes. It's a best practice to use data-testid
judiciously, focusing on elements that are critical for testing scenarios and might be subject to change.