---
title: A Test ID Contract With Your Developers | TestingBot
description: 'Role and label locators are the first choice when the element has a
  stable, unique, user-facing name. Many elements do not: a table cell, a container,
  a…'
source_url:
  html: https://testingbot.com/resources/courses/locator-strategies/a-test-id-contract
  md: https://testingbot.com/resources/courses/locator-strategies/a-test-id-contract.md
---

Course

[Selenium Locators and Locator Strategies](https://testingbot.com/resources/courses/locator-strategies)

Chapter 7 of 12

1. [1 Selenium Locators: Strategies That Survive Change](https://testingbot.com/resources/courses/locator-strategies)
2. [2 Why Tests Break on Locators](https://testingbot.com/resources/courses/locator-strategies/why-locators-break)
3. [3 Inspect the DOM and Test Selectors in DevTools](https://testingbot.com/resources/courses/locator-strategies/inspect-and-test-selectors-in-devtools)
4. [4 CSS Selectors for Test Automation](https://testingbot.com/resources/courses/locator-strategies/css-selectors)
5. [5 XPath in Selenium: Text, Axes and When to Use It](https://testingbot.com/resources/courses/locator-strategies/xpath-in-selenium)
6. [6 Role-Based, Label and Relative Locators](https://testingbot.com/resources/courses/locator-strategies/role-based-and-relative-locators)
7. [7 A Test ID Contract With Your Developers](https://testingbot.com/resources/courses/locator-strategies/a-test-id-contract)
8. [8 Shadow DOM and iframes](https://testingbot.com/resources/courses/locator-strategies/shadow-dom-and-iframes)
9. [9 Lists, Tables and Dynamic Content](https://testingbot.com/resources/courses/locator-strategies/lists-tables-and-dynamic-content)
10. [10 A Note on Mobile Locators](https://testingbot.com/resources/courses/locator-strategies/a-note-on-mobile-locators)
11. [11 A Locator Review Checklist](https://testingbot.com/resources/courses/locator-strategies/locator-review-checklist)
12. [12 Locator Strategies Knowledge Check](https://testingbot.com/resources/courses/locator-strategies/knowledge-check)

[Exit course](https://testingbot.com/resources/courses)

 Chapter 7 of 12 Intermediate 6 min read 2 quick checks Updated Nov 2026 

# A Test ID Contract With Your Developers
On this page
1. [What a test id is](https://testingbot.com#what-a-test-id-is)
2. [Using test ids](https://testingbot.com#using-test-ids)
3. [Writing the contract down](https://testingbot.com#writing-the-contract-down)
4. [Test ids and user-facing locators work together](https://testingbot.com#test-ids-and-user-facing-locators-work-together)
5. [Common objections](https://testingbot.com#common-objections)
6. [Summary](https://testingbot.com#summary)

Role and label locators are the first choice when the element has a stable, unique, user-facing name. Many elements do not: a table cell, a container, a status badge, an icon in a list of identical icons, a field whose label is translated. For those, the most reliable handle is one the team adds on purpose for tests: a test id.

## What a test id is[#](https://testingbot.com#what-a-test-id-is)

A test id is an attribute whose only job is to be found by tests:

```html
<button type="button" data-testid="invoice-save">Save</button>
```

It has no styling and no behaviour, so a designer restyling the button and a developer refactoring the component have no reason to touch it. That is the whole point. The attribute name varies by team: `data-testid` is the most common and Playwright's default, `data-test` and `data-qa` are widespread too. Pick one and use it everywhere.

## Using test ids[#](https://testingbot.com#using-test-ids)

The TodoMVC demo at `demo.playwright.dev/todomvc` puts `data-testid` on each todo title and on the counter. Selenium reads them with an attribute selector; a two-line helper keeps the attribute name in one place (`tests/test_test_ids.py`):

```python
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait

TODO = "https://demo.playwright.dev/todomvc/"

def by_test_id(value):
    return (By.CSS_SELECTOR, f"[data-testid='{value}']")

def test_todo_titles_by_test_id(driver):
    driver.get(TODO)
    new_todo = driver.find_element(By.CSS_SELECTOR, "input.new-todo")
    for title in ["Buy milk", "Walk the dog"]:
        new_todo.send_keys(title, Keys.ENTER)

    titles = WebDriverWait(driver, 10).until(
        lambda d: d.find_elements(*by_test_id("todo-title")))
    assert [t.text for t in titles] == ["Buy milk", "Walk the dog"]
    assert driver.find_element(*by_test_id("todo-count")).text == "2 items left"
```

Do not name the helper `test_id`: pytest collects every function whose name starts with `test` as a test, and then fails because `value` is not a fixture.

Playwright has `getByTestId` built in (`tests/test-ids.spec.ts`):

```typescript
import { test, expect } from './fixtures';

test('getByTestId reads data-testid', async ({ page }) => {
  await page.goto('https://demo.playwright.dev/todomvc/');
  const newTodo = page.getByPlaceholder('What needs to be done?');
  await newTodo.fill('Buy milk');
  await newTodo.press('Enter');
  await newTodo.fill('Walk the dog');
  await newTodo.press('Enter');

  await expect(page.getByTestId('todo-title')).toHaveText(['Buy milk', 'Walk the dog']);
  await expect(page.getByTestId('todo-count')).toHaveText('2 items left');
});
```

If your team uses a different attribute, set `testIdAttribute` once, in `playwright.config.ts` under `use`, or per file:

```typescript
test.describe('a team that uses data-qa', () => {
  test.use({ testIdAttribute: 'data-qa' });

  test('getByTestId follows testIdAttribute', async ({ page }) => {
    await page.setContent(`
      <form>
        <button type="button" data-qa="invoice-save">Save</button>
        <button type="button" data-qa="invoice-cancel">Cancel</button>
      </form>`);
    await expect(page.getByTestId('invoice-save')).toHaveText('Save');
  });
});
```

`page.setContent()` loads a snippet of HTML into the page, which is a handy way to try a locator against markup you control.

## Writing the contract down[#](https://testingbot.com#writing-the-contract-down)

A test id only stays stable if everybody agrees what it is for. Put a short section in the repository's contributing guide; something like this is enough:

1. **Attribute** : we use `data-testid`. Nothing else in the codebase reads it: no CSS, no JavaScript, no analytics.
2. **Naming** : lowercase kebab case, `<area>-<thing>` or `<area>-<thing>-<action>`: `checkout-total`, `invoice-save`, `user-menu-logout`. Name what the element _is_, never how it looks (`invoice-save`, not `blue-button`) or where it is (`header-left-3`).
3. **Lists** : put the same id on every item (`invoice-row`) and let tests filter by content, or add the record's own key (`invoice-row-INV-42`) when the content is not unique. Never number by position (`invoice-row-3`).
4. **Uniqueness** : an id that is not a list item appears once per page. If a component is rendered twice (two "Save" buttons in two panels), scope the id by its container (`billing-save`, `shipping-save`) or let tests scope by the container's id.
5. **Ownership** : renaming or removing a test id is a change to the test contract. It is fine, but it happens in the same pull request as the test update, and reviewers check for it.
6. **Where they go** : on elements tests need and that have no stable role and name. Buttons with a clear label usually do not need one.

A list of invoices renders each row with a test id. Which naming survives sorting, filtering and new invoices?

 `invoice-row-1`, `invoice-row-2`, ... in display order `blue-row` and `grey-row` for alternating rows A random UUID generated on each render `invoice-row` on every row, or `invoice-row-INV-42` using the invoice's own number

Display-order numbers change when the list is sorted or a new invoice is added, so `invoice-row-1` points at a different invoice tomorrow. A UUID per render is a generated id. The record's own key, or a shared id plus filtering by content, identifies the same invoice wherever it appears.

## Test ids and user-facing locators work together[#](https://testingbot.com#test-ids-and-user-facing-locators-work-together)

Test ids are not a replacement for role locators; they fill the gaps. A sensible order:

1. `getByRole` / `getByLabel` when the element has a stable, unique, user-facing name in the language you test in.
2. A test id when it does not, or when the copy changes often or is translated.
3. CSS on a meaningful attribute (`name`, `type`, a semantic class) when you cannot get a test id added.
4. XPath for text and structure, scoped from one of the above.

Mixing them is normal: find the row by test id, then the button inside it by role.

A developer wants to reuse `data-testid="cart-badge"` as a CSS hook to style the badge. What is the problem?

 CSS cannot select on `data-` attributes The attribute stops being test-only, so a styling change can now rename or remove it and break tests Playwright ignores test ids that have styles attached

A test id is stable because nothing else depends on it. Once styles hang off it, a designer has a reason to change it, and the test breaks for a visual change, which is exactly what test ids are meant to prevent. CSS can select on data attributes; the point is that it should not.

## Common objections[#](https://testingbot.com#common-objections)

- **"It bloats the HTML."** A few attributes per page add a handful of bytes, and they compress well. Some teams strip them from production builds with a build-time plugin; if you do, remember that tests against production (smoke tests, monitoring) then cannot use them.
- **"Tests should use what users use."** Agreed, and that is why roles and labels come first. A test id is for elements users identify by position or context, which a locator cannot express well.
- **"It's work for developers."** It is a one-line change in a component, done once. A brittle selector costs a triage session every time it breaks.

## Summary[#](https://testingbot.com#summary)

- A test id is an attribute that only tests read, so nothing else has a reason to change it.
- Agree on one attribute name and a naming scheme; name what the element is, never its look or position.
- Configure `testIdAttribute` in Playwright and wrap the attribute in a helper in Selenium.
- Use role and label locators first and test ids where they fall short.

[Previous · Chapter 6 Role-Based, Label and Relative Locators](https://testingbot.com/resources/courses/locator-strategies/role-based-and-relative-locators) [Next · Chapter 8 Shadow DOM and iframes](https://testingbot.com/resources/courses/locator-strategies/shadow-dom-and-iframes)

On this page

1. [What a test id is](https://testingbot.com#what-a-test-id-is)
2. [Using test ids](https://testingbot.com#using-test-ids)
3. [Writing the contract down](https://testingbot.com#writing-the-contract-down)
4. [Test ids and user-facing locators work together](https://testingbot.com#test-ids-and-user-facing-locators-work-together)
5. [Common objections](https://testingbot.com#common-objections)
6. [Summary](https://testingbot.com#summary)

Certification

Earn the free, resume-worthy TestingBot Locator Strategies Certification for this course.

[How it works](https://testingbot.com/resources/courses/locator-strategies/certification)
