Locators are a powerful way to find elements in the DOM, originally developed by Playwright and currently being adopted by other testing frameworks including Vitest. They provide a robust, maintainable approach to element selection that prioritizes accessibility and user-centric attributes over brittle CSS selectors or XPaths.
This project acts as a playground for understanding how locators work in Playwright and Vitest. It contains a trivial Vite app whose sole purpose is to provide interesting test permutations. It also contains test suites to exercise Playwright and Vitest locators, and documentation comparing and contrasting the two implementations.
The locator API consists of a number of methods that find DOM elements by varying logical predicates:
- by ARIA role i.e. the UI function of the element
- by visible text associated with the element i.e. inner text, label, title, alt text, or placeholder
- by developer-provided test ID
Note that locators lack an API for finding elements by HTML ID, CSS class or other presentational attributes.
This is a deliberate omission, stemming from the testing-library philosophy that presentational attributes are volatile and lead to flakey tests.
In practice, it's easy for application developers to use volatile labels or make non-unique or unstable test IDs, so the value of this approach to application testers is questionable.
However, applications that rely heavily on ARIA for testing are also more accessible to vision- and motor-impaired users, which can be a valuable side benefit.
TODO
While Vitest implements the core Playwright locator APIs, there are some subtle differences between the implementations; for example, Vitest's getByTitle cannot find title elements within SVGs, unlike Playwright's version.
The table below outlines the locator methods available in Vitest, which closely approximate Playwright's capabilities while maintaining Vitest's ability to run with multiple browsers and automation providers.
Excerpted from the official documentation.
| Method | Discriminator | Modifiers | Notes |
|---|---|---|---|
| getByRole | name1 | exact, ARIA2 | Implicit3 or explicit role. |
| getByAltText | exact | ||
| getByLabelText | exact | ||
| getByPlaceholder | exact | ||
| getByText | exact | ||
| getByTitle | exact | ||
| getByTestId | exact |
Footnotes
-
Accessible name as defined by ARIA. ↩
-
ARIA attributes that define the user-interface state of an element. ↩
-
DOM elements may be tagged with
aria-roleor they may have an implicit role e.g. everybuttonhas rolebuttonunless otherwise specified. ↩