π·οΈ What are Custom Test ID Attributes?
While user-facing locators (like roles and labels) are ideal for standard web flows, complex interactive widgetsβsuch as custom canvas graphs, deeply nested grid rows, legacy UI frameworks, or components with fluctuating localization textβfrequently require an explicit, unshakeable contract between front-end developers and automation engineers. Test ID attributes (defaulting to data-testid) isolate automation code from visual redesigns, CSS re-theming, and DOM restructuring. Playwright exposes first-class support for test IDs via page.get_by_test_id() and allows seamless configuration to match existing enterprise naming conventions such as data-cy, data-qa, or data-test.
page.get_by_test_id("submit-order") resolves directly to the CSS selector [data-testid="submit-order"]. This decouples the test suite from volatile class names and dynamic tag changes.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
Pooja Patil
""")
# 1. Locate elements directly by test ID
profile_widget = page.get_by_test_id("user-profile-widget")
user_name = page.get_by_test_id("user-display-name")
settings_btn = page.get_by_test_id("account-settings-btn")
# 2. Web-first auto-waiting assertions
expect(profile_widget).to_be_visible()
expect(user_name).to_have_text("Pooja Patil")
expect(settings_btn).to_be_enabled()
print(f"Verified User Profile via Test ID: '{user_name.inner_text()}'")
browser.close()
data-cy) or custom QA markers (data-qa, data-test), reconfigure Playwright's global selector engine using selectors.set_test_id_attribute().
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
# Globally override test id attribute across all browsers and contexts
p.selectors.set_test_id_attribute("data-cy")
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# Frontend template utilizing Cypress data-cy attributes
page.set_content("""
""")
# get_by_test_id now searches for [data-cy="..."] automatically!
email_field = page.get_by_test_id("login-email-input")
password_field = page.get_by_test_id("login-password-input")
submit_btn = page.get_by_test_id("submit-login-button")
email_field.fill("admin@nikita-infotech.com")
password_field.fill("PassSecure2026!")
expect(email_field).to_have_value("admin@nikita-infotech.com")
expect(submit_btn).to_be_visible()
print("Successfully resolved custom 'data-cy' attributes via get_by_test_id()!")
browser.close()
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
Industrial Optical Sensor
βΉ 4,500
Ethernet Control Relay
βΉ 2,200
""")
# Scope strictly to the specific cart row for Ethernet Control Relay
target_row = (
page.get_by_test_id("cart-container")
.get_by_test_id("cart-item-row")
.filter(has=page.get_by_test_id("item-name").filter(has_text="Ethernet Control Relay"))
)
remove_btn = target_row.get_by_test_id("remove-item-btn")
price_tag = target_row.get_by_test_id("item-price")
expect(target_row).to_be_visible()
expect(price_tag).to_have_text("βΉ 2,200")
expect(remove_btn).to_be_enabled()
print(f"Scoped Row Item : '{target_row.get_by_test_id('item-name').inner_text()}'")
print(f"Scoped Price : '{price_tag.inner_text()}'")
browser.close()
re.compile() patterns to match dynamic, parameterized, or prefixed test IDs (e.g., matching any order card like data-testid="order-card-ORD-10492").
import re
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
Order #ORD-8812 - Completed
Order #ORD-8813 - In Transit
Order #ORD-8814 - Pending
""")
# 1. Match all order cards matching regex pattern
order_cards_pattern = re.compile(r"^order-card-ORD-\d+$")
all_order_cards = page.get_by_test_id(order_cards_pattern)
expect(all_order_cards).to_have_count(3)
print(f"Discovered {all_order_cards.count()} dynamic order cards via Regex test ID!")
# 2. Target specific pending order
pending_card = page.get_by_test_id(re.compile(r".*8814$"))
expect(pending_card).to_contain_text("Pending")
print(f"Target Pending Order Readout: '{pending_card.inner_text()}'")
browser.close()
conftest.py fixture so every test worker respects the convention automatically.
# content of conftest.py
import pytest
from playwright.sync_api import Playwright
@pytest.fixture(scope="session", autouse=True)
def configure_custom_test_id(playwright: Playwright):
"""Configures global test id attribute for the entire automation suite."""
custom_attribute = "data-qa"
playwright.selectors.set_test_id_attribute(custom_attribute)
print(f"\n[Test Setup] Configured global test ID attribute: '{custom_attribute}'")
yield
# content of test_checkout.py
def test_user_checkout(page):
page.set_content('')
# Resolves to [data-qa="checkout-submit-btn"] seamlessly
submit_btn = page.get_by_test_id("checkout-submit-btn")
expect(submit_btn).to_be_visible()
submit_btn.click()
data-test while App 2 uses data-testid), reset or adapt attributes dynamically.
from playwright.sync_api import sync_playwright, expect
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
# App 1 uses data-test
p.selectors.set_test_id_attribute("data-test")
page.set_content('')
expect(page.get_by_test_id("portal-btn")).to_be_visible()
print("App 1 (data-test) validated.")
# App 2 uses standard data-testid
p.selectors.set_test_id_attribute("data-testid")
page.set_content('')
expect(page.get_by_test_id("dashboard-btn")).to_be_visible()
print("App 2 (data-testid) validated.")
browser.close()
[context]-[component]-[action/role]) to make test IDs self-documenting, maintainable, and clash-free across teams.
RECOMMENDED TEST ID NAMING CONVENTION:
Format: ---
EXAMPLES:
1. Container Card:
data-testid="billing-invoice-card"
2. Interactive Inputs:
data-testid="auth-login-input-username"
data-testid="auth-login-input-password"
3. Action Buttons:
data-testid="cart-checkout-btn-submit"
data-testid="dialog-confirm-btn-cancel"
4. Display Data Metrics:
data-testid="dashboard-kpi-text-total-revenue"
data-testid="inventory-status-badge-in-stock"
ANTI-PATTERNS TO AVOID:
* data-testid="btn1" (Too vague, prone to duplicate collisions)
* data-testid="blue-button" (Coupled to visual CSS color styling)
* data-testid="right-column-div" (Coupled to visual page layout)
from playwright.sync_api import Page, sync_playwright, expect
class BillingLedgerPage:
"""Page Object for Billing Management utilizing Test IDs."""
def __init__(self, page: Page):
self.page = page
self.ledger_table = page.get_by_test_id("ledger-table")
self.new_invoice_btn = page.get_by_test_id("create-invoice-btn")
self.tax_summary = page.get_by_test_id("total-gst-summary")
def get_invoice_row(self, invoice_id: str):
return self.ledger_table.get_by_test_id(f"invoice-row-{invoice_id}")
def pay_invoice(self, invoice_id: str):
row = self.get_invoice_row(invoice_id)
row.get_by_test_id("action-pay-btn").click()
with sync_playwright() as p:
browser = p.chromium.launch(headless=True)
page = browser.new_page()
page.set_content("""
INV-201
βΉ 14,200
""")
ledger_page = BillingLedgerPage(page)
expect(ledger_page.tax_summary).to_have_text("βΉ 14,200")
ledger_page.pay_invoice("INV-201")
print("POM method pay_invoice() executed cleanly via test ID locators!")
browser.close()
babel-plugin-react-remove-properties) to strip data-testid attributes from production bundles while preserving them in QA/staging environments.
// Example babel.config.js in your frontend project
module.exports = {
presets: ['@babel/preset-react'],
env: {
production: {
plugins: [
[
'babel-plugin-react-remove-properties',
{
// Automatically removes test id attributes in production output bundles
properties: ['data-testid', 'data-cy', 'data-qa']
}
]
]
}
}
};
LOCATOR STRATEGY DECISION MATRIX:
ββββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββ¬βββββββββββββββββββββββββ¬βββββββββββββββββββββββββ
β Selection Criteria β User-Facing Roles β Custom Test IDs β Raw CSS / XPath β
β β (get_by_role, label) β (get_by_test_id) β (locator, xpath) β
ββββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββΌβββββββββββββββββββββββββΌβββββββββββββββββββββββββ€
β Refactoring Resilience β High (Semantic HTML) β Maximum (Dedicated ID) β Low (Breaks on CSS) β
β Enforces Accessibility β Yes (Encourages a11y) β No (Hidden metadata) β No β
β Ease of Disambiguation β High β Highest β Complex β
β Code Maintainability β High β High β Low β
β Frontend Developer Effort β Zero (Uses native HTML)β Low (Add data-testid) β Zero β
β Best For β Public Web Flows, Auth β Complex Data Grids, β Third-Party Iframes, β
β β Forms, User Actions β Canvas, Dynamic State β Uncontrollable Legacy β
ββββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββ΄βββββββββββββββββββββββββ΄βββββββββββββββββββββββββ