Why You Should Avoid data-testid and Use aria-label Instead

Introduction
When writing end-to-end tests with Playwright, it’s common to rely on data-testid attributes for element selection. While this can work, it’s not ideal. In fact, there’s a better way that improves both your tests and your product: using accessible attributes like aria-label.
Solution
Instead of adding data-testid attributes purely for testing purposes, use aria-label, role, or other accessible attributes. These not only allow Playwright to reliably locate elements—but they also make your app usable by people who rely on assistive technologies, like screen readers.
Why is this important now more than ever? Because we’re entering a world where AI agents and LLM-powered tools are starting to interact with web applications just like humans. These agents often rely on the accessibility tree to understand your UI—just like real users with disabilities do.
By using aria-label, you’re enabling both humans and machines to understand your app better. That’s a win-win.
Example
Instead of doing this:
<button data-testid="submit-btn">Submit</button>
Do this:
<button aria-label="Submit Form">Submit</button>
And in Playwright:
await page.getByRole('button', { name: 'Submit Form' }).click();
This approach ties your selectors to meaningful user interactions, not testing-specific attributes.
Summary
Using aria-label instead of data-testid improves:
• Test resilience and readability
• Accessibility for users with disabilities
• Compatibility with AI agents and screen readers
Accessible design isn’t just the right thing to do—it’s becoming essential in an increasingly automated, AI-integrated world.
Next time you’re writing a Playwright test, ask yourself: Would an AI or a screen reader know what this element does?
If the answer is no, you’re missing an opportunity.