Rules Hub

Coding Rules Library

← Back to all rules
frontend ruleStack: testing
testingaccessibilityvitestclean-code

Prefer accessibility locators for user interaction tests

Query elements by accessible roles (e.g., button, option) to ensure tests resemble user behavior and verify accessibility.

PR: Learning how to write tests meaningCreated: Dec 10, 2025

Bad example

Old codetsx
1test("select option", async () => {
2 page.render(<ExampleCombobox />);
3
4 // BAD: Using CSS selectors is brittle and ignores accessibility
5 // If the class name changes, the test breaks.
6 await page.locator(".combobox-trigger").click();
7
8 // BAD: Relies on internal data attributes instead of user-visible text
9 await page.locator(".option-item[data-value='remix']").click();
10});

Explanation (EN)

Relying on CSS classes, IDs, or internal data attributes creates brittle tests that break when implementation details change (e.g., refactoring CSS). It also fails to verify that the element is correctly exposed to assistive technologies (screen readers).

Objašnjenje (HR)

Oslanjanje na CSS klase, ID-ove ili interne atribute stvara krhke testove koji pucaju kada se promijene implementacijski detalji (npr. refaktoriranje CSS-a). Također ne provjerava je li element ispravno izložen pomoćnim tehnologijama (čitačima zaslona).

Good example

New codetsx
1import { page } from "vitest/browser";
2
3test("select option", async () => {
4 page.render(<ExampleCombobox />);
5
6 // GOOD: Using roles simulates real user interaction and verifies semantics
7 // Ensures the element is actually a 'combobox' to the browser
8 await page.getByRole("combobox").click();
9
10 // GOOD: Selects by the visible accessible name, mirroring user intent
11 await page.getByRole("option", { name: "Remix" }).click();
12
13 await expect.element(page.getByRole("combobox")).toHaveTextContent("Remix");
14});

Explanation (EN)

Using `getByRole` ensures the element allows interaction via standard accessibility APIs. This guarantees that the UI works not just visually, but also semantically for all users, and the test mimics how a real user finds elements on the page.

Objašnjenje (HR)

Korištenje `getByRole` osigurava da element omogućuje interakciju putem standardnih API-ja za pristupačnost. To jamči da UI radi ne samo vizualno, već i semantički za sve korisnike, a test oponaša način na koji stvarni korisnik pronalazi elemente na stranici.