data-testid should be used as a stable testing contract when an element cannot be located reliably by role, label, or visible text. Prefer role-based locators for interactive controls and text locators for visible content.
Test IDs improve selector stability, but they do not verify accessibility or user-facing behavior.
🤖 Summarize this article with AI:
💬 ChatGPT 🔍 Perplexity 💥 Claude 🐦 Grok 🔮 Google AI Mode
🎯 TL;DR - Data-testid Attributes
- Use
data-testidwhen semantic locators are unavailable, ambiguous, dynamic, or intentionally separated from visible content. - Prefer role-based locators for buttons, links, checkboxes, form controls, and other interactive elements.
- Use text locators for visible, non-interactive content when the wording is part of the expected user experience.
- Playwright supports
getByTestId()withdata-testidas the default attribute. React Testing Library treatsgetByTestId()as a fallback, while Cypress recommends stabledata-*attributes such asdata-cy.
| When to use | Recommendation |
|---|---|
**data-testid** |
Use it as an explicit testing contract when role, label, or visible text cannot identify the element reliably. Keep the value stable, descriptive, and unique within the relevant page or component. |
| Role | Prefer role and accessible name for interactive elements such as buttons, links, checkboxes, and form controls. This most closely reflects how users and assistive technologies identify the interface. |
| Text | Use visible text for headings, messages, labels, and other content when the wording itself is part of the behavior being tested. Avoid it when copy changes frequently or is translated. |
Check also
- 🎯 TL;DR - Data-testid Attributes
- What Are data-testid Attributes?
- Using Data-testid Means Automating with Ease
- Separation of Concerns: A Pillar of Modern Development
- Precise Element Targeting in Complex UIs
- Fostering Collaboration Between Teams
- Versatility Across Testing Methodologies
- Indirect Support for Accessibility Testing
- Conclusion
What Are data-testid Attributes?
data-testid is a custom HTML data-* attribute that provides an explicit hook for automated tests. It does not change the element's appearance or add accessibility semantics. HTML does not enforce uniqueness for test IDs, so teams should define stable naming rules and avoid assigning the same value to multiple elements within the same testing scope.
The primary use of data-testid attributes is to improve the robustness and reliability of UI (User Interface) tests. By using these identifiers, tests can locate and interact with specific elements on a page without relying on CSS classes or element tags, which can change more frequently and be less unique.
When a stable data-testid attribute is unavailable, the XPath cheat sheet can help you build a precise locator from the element’s attributes and DOM position.
💡 TIP
This approach helps to create more maintainable and stable test suites, as tests are less likely to break due to changes in the application's UI.
Here's a simple example of how a data-testid attribute might be used in HTML:
<div data-testid="unique-element">Some content</div>
Current framework recommendations
The correct selector depends on the testing framework and what the test is intended to verify.
Playwright
Playwright uses data-testid as the default test ID attribute:
await page.getByTestId('submit-button').click();
A different attribute can be configured in playwright.config.ts:
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
testIdAttribute: 'data-pw',
},
});
React Testing Library
React Testing Library supports getByTestId(), but recommends role-based queries first:
const button = screen.getByRole('button', { name: /submit/i });
Use a test ID when a semantic query is unavailable or unsuitable:
const element = screen.getByTestId('unique-element');
These queries work with test runners such as Jest and Vitest; getByTestId() is provided by Testing Library, not Jest itself.
Cypress
Cypress recommends dedicated data-* attributes that remain independent of styling and JavaScript behavior. Its documentation commonly uses data-cy:
cy.get('[data-cy="submit-button"]').click();
Cypress can also select data-testid through a standard attribute selector:
cy.get('[data-testid="submit-button"]').click();
| Element Tag | Data Test ID | Intended Purpose |
|---|---|---|
<button> |
submit-button | Identifies the submit button in a form for click actions. |
<input> |
email-input | Marks the input field for an email address in a form. |
<div> |
loading-indicator | Used to find the loading indicator during page or data load. |
<span> |
error-message | Points to an error message displayed for form validation. |
<img> |
profile-picture | Identifies the user's profile picture on a page. |
<a> |
home-link | Marks the link to the homepage in a navigation bar. |
<select> |
country-selector | Used to locate the dropdown for selecting a country. |
<textarea> |
feedback-text | Identifies the text area for entering feedback in a form. |
<p> |
welcome-message | Points to a welcome message displayed to the user. |
<ul> |
product-list | Marks the list of products displayed on a page. |
Automate your tests for free
Test easier than ever with BugBug test recorder. Faster than coding. Free forever.
Sign up for free
Using Data-testid Means Automating with Ease
In the domain of automated testing, efficiency and coverage are king. data-testid attributes facilitate the automation of tests by providing a clear and consistent way to identify UI elements, making it easier to script complex interactions and scenarios. This accessibility accelerates the creation of comprehensive automated tests, enhancing the application's quality and reducing manual testing efforts.
Separation of Concerns: A Pillar of Modern Development
The principle of separating concerns underpins much of modern development practices. By adopting data-testid attributes, developers can isolate the concerns of styling and functionality/testing. This separation ensures that changes to the application's style have no bearing on the functionality of tests, promoting a more modular and maintainable codebase.
Precise Element Targeting in Complex UIs
As applications grow in complexity, so does the difficulty of targeting specific elements for testing. data-testid attributes shine in these scenarios, allowing developers and testers to pinpoint exact elements with precision, regardless of their nesting level or position in the DOM tree. This precision is invaluable in ensuring the reliability and effectiveness of tests.
Fostering Collaboration Between Teams
The introduction of data-testid attributes can serve as a bridge between developers and QA engineers, providing a common language for referring to UI elements. This shared vocabulary facilitates communication, streamlines the testing process, and enhances the overall efficiency of the development lifecycle.
Versatility Across Testing Methodologies
Whether it's unit testing individual components or conducting integration tests to evaluate the interaction between components, data-testid attributes prove their versatility. This adaptability ensures that the attributes can be seamlessly integrated into various testing methodologies, contributing to a more robust testing strategy.
Automate your tests for free
Test easier than ever with BugBug test recorder. Faster than coding. Free forever.
Sign up for free
Indirect Support for Accessibility Testing
data-testid does not provide an accessible name, role, label, or any other accessibility information. A test that finds a button only through its test ID can therefore pass even when the button is inaccessible to assistive technology. Use role- and label-based locators when accessibility semantics are part of the expected behavior, and treat test IDs only as stable automation hooks. Test IDs can coexist with accessibility checks, but they do not replace them.
Conclusion
The adoption of data-testid attributes in development practices heralds a new era of efficiency, stability, and collaboration in testing. By embracing this approach, development teams can unlock the full potential of their testing suite, ensuring that their applications are not only visually appealing but also robust and reliable.
In the fast-paced world of web development, data-testid attributes stand out as a pillar of modern testing strategies, empowering teams to deliver high-quality applications with confidence.
Happy (automated) testing!


