Exit course
Chapter 7 of 12 Intermediate 6 min read 2 quick checks Updated

A Test ID Contract With Your Developers

On this page
  1. What a test id is
  2. Using test ids
  3. Writing the contract down
  4. Test ids and user-facing locators work together
  5. Common objections
  6. 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#

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

<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#

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):

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):

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:

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#

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?

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#

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?

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#

  • "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#

  • 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.