mirror of
https://github.com/tester-army/e2e.git
synced 2026-11-22 07:55:36 +08:00
* fix(web): read visibility as rendered, null box, checkable values, embedded names * fix(web): narrow visible queries by the reader's hidden state * fix(web): drop direct text a content-visibility hidden element skips * docs(changeset): note the display contents divergence from Playwright
712 lines
32 KiB
Plaintext
712 lines
32 KiB
Plaintext
---
|
|
title: screen and Locator
|
|
description: Queries, refinement, actions, and reads.
|
|
---
|
|
|
|
A `Locator` stores a query and resolves it when an action, read, or assertion
|
|
runs. Every `Screen` query method is also available on a locator, scoped to
|
|
its subtree. `tapAt` is not scoped: on a locator it still taps a viewport
|
|
point.
|
|
|
|
```ts
|
|
export interface Screen {
|
|
/** Creates a lazy role query. An alias such as `img` is rewritten to its role. */
|
|
getByRole(role: Role | RoleAlias, options?: RoleOptions): Locator;
|
|
/** Creates a lazy role query narrowed to an accessible name: `getByRole('button', 'Sign in')`. */
|
|
getByRole(role: Role | RoleAlias, name: TextMatch, options?: Omit<RoleOptions, 'name'>): Locator;
|
|
/** Creates a lazy accessible-label query. */
|
|
getByLabel(text: TextMatch, options?: TextMatchOptions): Locator;
|
|
/** Creates a lazy placeholder query. */
|
|
getByPlaceholder(text: TextMatch, options?: TextMatchOptions): Locator;
|
|
/** Creates a lazy visible-text query. */
|
|
getByText(text: TextMatch, options?: TextMatchOptions): Locator;
|
|
/** Creates a lazy displayed-value query. */
|
|
getByDisplayValue(value: TextMatch, options?: TextMatchOptions): Locator;
|
|
/** Creates a lazy test-id query: a string matches the whole id, case-sensitive; a RegExp tests it. */
|
|
getByTestId(id: TextMatch, options?: { visible?: boolean }): Locator;
|
|
/** Taps a viewport point, with no node behind it. */
|
|
tapAt(point: Point, options?: ActionOptions): Promise<void>;
|
|
/** Performs a viewport-level swipe: in a direction, or along a path from one point to another. */
|
|
swipe(options: SwipeOptions | SwipePathOptions): Promise<void>;
|
|
/** Scrolls until a locator resolves visibly or times out. */
|
|
scrollUntilVisible(
|
|
target: Locator,
|
|
options?: { direction?: ScrollDirection; momentum?: Momentum; timeout?: number },
|
|
): Promise<void>;
|
|
}
|
|
```
|
|
|
|
Most operations require exactly one match. Reads return the current value
|
|
without waiting for it to change: a frame that is not in the document answers
|
|
at once, and a node the engine reports stale (a resolve that raced a
|
|
navigation, or a match the app replaced while it was read) is re-resolved
|
|
within the action timeout, which repairs the race without waiting for a
|
|
match. Use [`expect`](/reference/expect) to wait.
|
|
|
|
| Operation | Zero matches | Multiple matches |
|
|
| --- | --- | --- |
|
|
| Actions | Poll until the timeout, then `LOCATOR_NOT_FOUND` | `LOCATOR_AMBIGUOUS` |
|
|
| Reads | `LOCATOR_NOT_FOUND` | `LOCATOR_AMBIGUOUS` |
|
|
| `count()`, `all()`, `allTextContents()` | `0`, `[]`, `[]` | The count, one locator per match, one text per match |
|
|
| `isVisible()`, `isHidden()` | `false`, `true` | `LOCATOR_AMBIGUOUS` |
|
|
| Assertions | Poll until the timeout | `LOCATOR_AMBIGUOUS` |
|
|
| Any of these under a frame that is not in the document | As zero matches for `count()`, `all()`, `allTextContents()`, `isVisible()`, and `isHidden()`; actions, reads, and assertions poll for the frame until the timeout, then `LOCATOR_NOT_FOUND` | `LOCATOR_AMBIGUOUS` when several frames match |
|
|
|
|
## Queries
|
|
|
|
Every query returns a `Locator` synchronously and performs no work. An
|
|
option key the query does not take (`{ nam: 'Save' }`) throws
|
|
`INVALID_LOCATOR` naming the keys it does.
|
|
|
|
`getByRole` takes the accessible name as its second argument, a string or a
|
|
`RegExp`, with the other options after it:
|
|
`getByRole('button', 'Save', { exact: false })`. The object form,
|
|
`getByRole('button', { name: 'Save', disabled: true })`, is the same query.
|
|
|
|
A string passed to `getByRole` as the name, `getByLabel`, `getByPlaceholder`,
|
|
`getByText`, or `getByDisplayValue` matches the whole text, case-sensitive,
|
|
after whitespace normalization: `getByRole('button', 'Save')` does
|
|
not match `Save changes`. `{ exact: false }` makes it a case-insensitive
|
|
substring match, and a `RegExp` matches as written.
|
|
|
|
`getByTestId` matches the node's `testId`: on the web the value of the
|
|
engine's test-id attribute (`web({ testIdAttribute })`, default
|
|
`data-testid`), on a device the accessibility identifier or resource id. A
|
|
string matches the whole id, case-sensitive; a `RegExp` such as
|
|
`/total-budgeted$/` matches as written.
|
|
|
|
```ts
|
|
screen.getByRole('button', 'Save');
|
|
screen.getByRole('heading', /welcome/i, { level: 1 });
|
|
screen.getByLabel('Email');
|
|
screen.getByText('Welcome back', { exact: false });
|
|
screen.getByTestId('todo-3');
|
|
```
|
|
|
|
### Echoed text
|
|
|
|
`getByText` answers with the innermost matching node, so a container that
|
|
echoes its child's text counts once. Browsers do this natively; on a device
|
|
the engine applies the same rule, since iOS reports a React Native `Text` as
|
|
a host view plus a `StaticText` child with the same label. Two matches that
|
|
do not contain each other remain `LOCATOR_AMBIGUOUS`.
|
|
|
|
### Hidden duplicates
|
|
|
|
Every query accepts `visible: true`, which drops nodes the platform reports
|
|
as hidden before the exactly-one rule runs. Frameworks often keep a hidden
|
|
copy of content in the document, such as a closed drawer or an inactive tab
|
|
panel, and without `visible` both copies match.
|
|
|
|
```ts
|
|
await browser.reload();
|
|
// Two "No memories yet" nodes exist for a moment; one is display:none.
|
|
await expect(screen.getByText('No memories yet', { visible: true })).toBeVisible();
|
|
await screen.getByPlaceholder('Search memory...', { visible: true }).fill('launch');
|
|
await screen.getByTestId('memory-list', { visible: true }).getByRole('listitem').first().tap();
|
|
```
|
|
|
|
`visible` uses the same visibility check as `toBeVisible()`, `isVisible()`,
|
|
and `waitFor()`: what renders, as Playwright reads it. `display: none`,
|
|
`visibility: hidden`, a box with no size, a closed `<details>` body, and
|
|
content under `content-visibility: hidden` are hidden; `aria-hidden` is not,
|
|
since a decorative spinner marked with it still paints, so
|
|
`toBeHidden()` on one waits until it leaves. A child that sets
|
|
`visibility: visible` under a hidden parent is visible. On the web, text
|
|
directly under a `display: contents` element with `visibility: hidden` is
|
|
hidden, where Playwright calls it visible. It works with scopes, `filter`, `first`, `last`, and `nth`:
|
|
`getByText('Save', { visible: true }).first()` is the first visible match.
|
|
Prefer it over `browser.locator('p:visible')`, which ties the test to CSS.
|
|
|
|
## Refinement
|
|
|
|
Refinement returns a new locator without querying the app. `hasText` with a
|
|
string is a case-insensitive substring match over the match and its
|
|
descendants, unlike a query text, which matches exactly; pass a RegExp for
|
|
anything stricter. `has` keeps a match whose subtree resolves the inner
|
|
locator.
|
|
|
|
Throws `INVALID_LOCATOR` when `filter` gets neither `hasText` nor `has`, when
|
|
it gets any other key, even beside them (`hasNot`, `hasNotText`, and
|
|
`visible` are not filters here), when `has` is not a runner locator or was
|
|
made by another target's screen, or when `nth` gets a negative or
|
|
non-integer index.
|
|
|
|
```ts
|
|
const row = screen.getByRole('listitem').filter({ hasText: 'Invoice 42' });
|
|
await row.getByRole('button', 'Void').tap();
|
|
```
|
|
|
|
<Note>
|
|
In the web engine a `getByDisplayValue` locator cannot be the scope
|
|
of a child query or a `has` filter; both fail with `UNSUPPORTED_CAPABILITY`.
|
|
Playwright has no selector for a control's current value, so the engine
|
|
filters candidates after the fact.
|
|
</Note>
|
|
|
|
## screen.tapAt
|
|
|
|
```ts
|
|
tapAt(point: Point, options?: ActionOptions): Promise<void>;
|
|
```
|
|
|
|
Taps a viewport point in CSS pixels, the space `boundingBox()` reports in,
|
|
with no node behind it: a pin on a canvas, a control the tree does not
|
|
list. Nothing is resolved or waited for; the page decides what the tap
|
|
lands on. Uses `config.actionTimeout`. Throws `INVALID_ARGUMENT` for a
|
|
negative or non-finite coordinate and `UNSUPPORTED_CAPABILITY` when the
|
|
engine does not list `tap` in its pointer actions.
|
|
|
|
```ts
|
|
const map = await screen.getByRole('image', 'Map').boundingBox();
|
|
await screen.tapAt({ x: map.x + 360, y: map.y + 70 });
|
|
```
|
|
|
|
Prefer a locator when the tree lists the control; a point moves with the
|
|
layout. For a point inside a node, `tap({ position })` reads the node's box
|
|
for you.
|
|
|
|
## screen.swipe
|
|
|
|
```ts
|
|
swipe(options: SwipeOptions | SwipePathOptions): Promise<void>;
|
|
```
|
|
|
|
Viewport-level gesture, in one of two shapes. `{ direction, momentum? }` is
|
|
a scroll gesture on the screen. `direction` is the way the content scrolls,
|
|
not the finger: `'down'` reveals what is below. `momentum` is its fling
|
|
strength, `'none'` by default: `'none'` a plain drag of half the surface,
|
|
`'slow'` a short fling, `'fast'` a long one. How far each carries is the
|
|
engine's.
|
|
`{ from, to }` is a swipe along a path between two viewport points: a touch
|
|
swipe on a device, a pointer drag on a document platform, which is what
|
|
reveals a row action, dismisses a sheet, or drags a card between columns.
|
|
Uses `config.actionTimeout`. Throws
|
|
`ACTION_FAILED` when the gesture is rejected, `INVALID_ARGUMENT` for a mix
|
|
of the two shapes or a coordinate off the plane, and `UNSUPPORTED_CAPABILITY`
|
|
when the engine does not list `swipe` in its actions (a direction) or
|
|
`swipeTo` in its pointer actions (a path).
|
|
|
|
```ts
|
|
await screen.swipe({ direction: 'up', momentum: 'fast' });
|
|
|
|
const row = await screen.getByText('Design review').boundingBox();
|
|
await screen.swipe({
|
|
from: { x: row.x + row.width - 10, y: row.y + row.height / 2 },
|
|
to: { x: row.x + 10, y: row.y + row.height / 2 },
|
|
});
|
|
```
|
|
|
|
## screen.scrollUntilVisible
|
|
|
|
```ts
|
|
scrollUntilVisible(
|
|
target: Locator,
|
|
options?: { direction?: ScrollDirection; momentum?: Momentum; timeout?: number },
|
|
): Promise<void>;
|
|
```
|
|
|
|
| Name | Type | Default |
|
|
| --- | --- | --- |
|
|
| `target` | `Locator` | - |
|
|
| `options.direction` | `ScrollDirection` | `'down'` |
|
|
| `options.momentum` | `Momentum` | `'slow'`; the gesture of each step, as [`screen.swipe`](#screen-swipe) defines it. A longer step is faster but must not carry the target past the surface unseen, which is what a virtualized list does |
|
|
| `options.timeout` | `number` | `30000`, its own default, not `config.actionTimeout`; it bounds the whole scroll, each swipe included |
|
|
|
|
On `screen` each step is a viewport swipe. On a locator the step is a swipe
|
|
of that node, so a feed or a table that is its own scroll container pages
|
|
without the pointer having to hover it first:
|
|
`screen.getByRole('feed').scrollUntilVisible(row)`.
|
|
|
|
Throws `INVALID_LOCATOR` for a non-runner locator or one made by another
|
|
target's screen, `INVALID_ARGUMENT` for an option it does not take,
|
|
`LOCATOR_NOT_FOUND` when the deadline expires first, a swipe it cut short
|
|
included.
|
|
|
|
```ts
|
|
await screen.scrollUntilVisible(screen.getByRole('button', 'Accept'));
|
|
```
|
|
|
|
## Locator actions
|
|
|
|
Each action resolves one node, waits for actionability, and performs one
|
|
operation. Default timeout `config.actionTimeout`, 30000 ms, overridable
|
|
with `{ timeout }`.
|
|
|
|
```ts
|
|
export interface Locator extends Screen {
|
|
/** Taps exactly one matching actionable node; with `position`, taps that point of its box once it is in view, with no other actionability check. */
|
|
tap(options?: TapOptions): Promise<void>;
|
|
/** Alias of tap. */
|
|
click(options?: TapOptions): Promise<void>;
|
|
/** Double-taps exactly one matching actionable node. */
|
|
doubleTap(options?: ClickOptions): Promise<void>;
|
|
/** Performs a secondary tap, such as a right click or two-finger tap. */
|
|
secondaryTap(options?: ClickOptions): Promise<void>;
|
|
/** Long-presses exactly one matching actionable node. */
|
|
longPress(options?: LongPressOptions): Promise<void>;
|
|
/** Fills exactly one input. Secret values are never logged. */
|
|
fill(value: string | Secret, options?: ActionOptions): Promise<void>;
|
|
/**
|
|
* Focuses exactly one input and types `text` through the keyboard, one
|
|
* character at a time, so the app receives key events. A `Secret` is
|
|
* refused; it goes through `fill`.
|
|
*/
|
|
pressSequentially(text: string, options?: PressSequentiallyOptions): Promise<void>;
|
|
/** Clears exactly one input. */
|
|
clear(options?: ActionOptions): Promise<void>;
|
|
/** Sends one key to exactly one node. */
|
|
press(key: string, options?: ActionOptions): Promise<void>;
|
|
/** Checks exactly one node. */
|
|
check(options?: ActionOptions): Promise<void>;
|
|
/** Unchecks exactly one node. */
|
|
uncheck(options?: ActionOptions): Promise<void>;
|
|
/** Selects one option from exactly one control. */
|
|
selectOption(value: SelectOption, options?: ActionOptions): Promise<void>;
|
|
/** Focuses exactly one node. */
|
|
focus(options?: ActionOptions): Promise<void>;
|
|
/** Hovers over exactly one matching actionable node. */
|
|
hover(options?: ActionOptions): Promise<void>;
|
|
/** Sets the files of exactly one file input; paths resolve from the project root. */
|
|
setInputFiles(paths: string | readonly string[], options?: ActionOptions): Promise<void>;
|
|
/** Drags exactly one node to exactly one target. */
|
|
dragTo(target: Locator, options?: ActionOptions): Promise<void>;
|
|
/** Scrolls exactly one node into view. */
|
|
scrollIntoView(options?: ActionOptions): Promise<void>;
|
|
/** Performs a swipe scoped to exactly one node. */
|
|
swipe(options: SwipeOptions & ActionOptions): Promise<void>;
|
|
/** Reads normalized text without retrying for a particular value. */
|
|
textContent(): Promise<string | null>;
|
|
/** Reads the current input value. */
|
|
inputValue(): Promise<string>;
|
|
/** Reads one attribute. */
|
|
getAttribute(name: string): Promise<string | null>;
|
|
/** Reads current visibility. */
|
|
isVisible(): Promise<boolean>;
|
|
/** Reads current hidden or absent state, the negation of `isVisible`. */
|
|
isHidden(): Promise<boolean>;
|
|
/** Reads current enabled state. */
|
|
isEnabled(): Promise<boolean>;
|
|
/** Reads current disabled state, the negation of `isEnabled`. */
|
|
isDisabled(): Promise<boolean>;
|
|
/** Reads current checked state. */
|
|
isChecked(): Promise<boolean>;
|
|
/** Reads the current viewport-relative rectangle. */
|
|
boundingBox(): Promise<{ x: number; y: number; width: number; height: number } | null>;
|
|
/** Counts current matches without auto-waiting. */
|
|
count(): Promise<number>;
|
|
/** One `nth(i)` locator per current match, without auto-waiting; empty when nothing matches. */
|
|
all(): Promise<Locator[]>;
|
|
/** Reads the normalized text of every current match, without auto-waiting; empty when nothing matches. */
|
|
allTextContents(): Promise<string[]>;
|
|
/**
|
|
* Waits for the requested locator state, `visible` by default: `attached`
|
|
* for one match, visible or not; `detached` for none; `hidden` for none or
|
|
* a hidden one.
|
|
*/
|
|
waitFor(options?: { state?: 'attached' | 'detached' | 'visible' | 'hidden'; timeout?: number }): Promise<void>;
|
|
/** Adds deterministic locator filters. */
|
|
filter(options: { hasText?: TextMatch; has?: Locator }): Locator;
|
|
/** Selects the first current match. */
|
|
first(): Locator;
|
|
/** Selects the last current match. */
|
|
last(): Locator;
|
|
/** Selects one zero-based current match. */
|
|
nth(index: number): Locator;
|
|
}
|
|
```
|
|
|
|
- An action whose kind the engine does not list in `actions` throws
|
|
`UNSUPPORTED_CAPABILITY` before reaching the engine.
|
|
- An action takes only the options its signature names. Any other key,
|
|
Playwright's `trial`, `force`, or `noWaitAfter` included, throws
|
|
`INVALID_ARGUMENT` before the node is resolved, so the control is never
|
|
touched.
|
|
- `click` is an alias of `tap`.
|
|
- `tap`, `doubleTap`, and `secondaryTap` take `modifiers`, the keys held for
|
|
the click, as a Shift-click extends a selection:
|
|
`row.click({ modifiers: ['Shift'] })`. `ControlOrMeta` is Control on Windows
|
|
and Linux, Meta on macOS. An unknown or repeated modifier is
|
|
`INVALID_ARGUMENT`, and so is `modifiers` beside `position`. The browser
|
|
engine holds them; an engine that does not declare `tapModifiers`, the
|
|
mobile engine among them, fails with `UNSUPPORTED_CAPABILITY` before it
|
|
acts.
|
|
- `tap({ position })` taps at an offset of the node's top-left corner, in
|
|
CSS pixels. The node is scrolled into view when the engine lists
|
|
`scrollIntoView`, then its box is read and the pointer dispatched at the
|
|
point, with no node behind the gesture, so the platform's other
|
|
actionability checks (enabled, not covered) do not run. A node the engine
|
|
cannot bring into view fails as the engine reports it (`ACTION_FAILED` on
|
|
the browser engine, whose scroll waits for visibility); one that resolves
|
|
but never shows a visible box within the timeout is `LOCATOR_NOT_FOUND`.
|
|
An engine without the `tap` pointer action is `UNSUPPORTED_CAPABILITY`.
|
|
- `press` takes zero or more modifiers (`Shift`, `Control`, `Alt`, `Meta`,
|
|
`ControlOrMeta`) and one key, joined with `+`: a named key (`Enter`,
|
|
`Escape`, `Tab`, `Backspace`, `Delete`, `Insert`, `Space`, the arrows,
|
|
`Home`, `End`, `PageUp`, `PageDown`, `F1` to `F12`) or one printable
|
|
character. `Shift++` presses `+`. A key the platform lacks throws
|
|
`UNSUPPORTED_CAPABILITY`. See the [key grammar](/reference/engine#keys).
|
|
- `longPress` holds for `{ duration }` milliseconds, 100 through 10000, else
|
|
for the engine's default: 500 ms on the browser engine, one second on the
|
|
mobile engine, past a React Native `Pressable`'s `delayLongPress`.
|
|
- `fill` replaces the current content. A `Secret` is resolved on the host
|
|
right before the call and never logged, reported, or sent to a model.
|
|
- `pressSequentially` focuses the input and sends the text as keystrokes
|
|
through the engine's keyboard, appending to the current content. `fill`
|
|
sets the value directly and fires no key events, so an autocomplete, a
|
|
search-as-you-type box, or a masked input wired to `keydown` or `keyup`
|
|
never reacts to it; this is the action for those. `{ delay }` waits that
|
|
many milliseconds between characters, each sent in its own keyboard call;
|
|
without it the whole text goes in one call. Focus, pauses, and keystrokes
|
|
share the one action deadline: a pause is cut short at it and no character
|
|
is sent past it, and the action fails with `ACTION_FAILED` naming how many
|
|
characters landed. It needs the engine's `focus` action and `keyboard`
|
|
capability, else `UNSUPPORTED_CAPABILITY` before any node resolves, and it
|
|
relies on the [keyboard contract](/reference/engine#engine): `type`
|
|
must deliver text as a person typing would, so key events reach the app
|
|
where the platform has them. A `Secret` is a type error and
|
|
`INVALID_ARGUMENT` at runtime: a secret is filled, never typed as
|
|
keystrokes. The step records the locator, not the text, like `fill`.
|
|
- `setInputFiles` paths resolve from the project root. An empty list or blank
|
|
entry throws `INVALID_ARGUMENT`.
|
|
- `dragTo` with a non-runner target, or one made by another target's screen,
|
|
throws `INVALID_LOCATOR`.
|
|
- `swipe` on a locator is a gesture on that one node: `{ direction,
|
|
momentum? }` as [`screen.swipe`](#screen-swipe) defines them, plus
|
|
`timeout`. It has no `{ from, to }` form. `screen.swipe` takes no
|
|
`timeout`: a `timeout` key there is `INVALID_ARGUMENT`.
|
|
- An action that may already have committed surfaces as `ACTION_FAILED` and
|
|
is never repeated.
|
|
|
|
```ts
|
|
await screen.getByLabel('Email').fill('ada@example.test');
|
|
await screen.getByRole('checkbox', 'Remember me').check();
|
|
await screen.getByLabel('Plan').selectOption({ label: 'Pro' });
|
|
await screen.getByLabel('Plan').selectOption({ value: 'pro' });
|
|
await screen.getByRole('button', 'Save').tap({ timeout: 10_000 });
|
|
await screen.getByRole('image', 'Seat map').tap({ position: { x: 120, y: 48 } });
|
|
await screen.getByRole('textbox', 'Search').press('Enter');
|
|
await screen.getByRole('textbox', 'Notes').press('ControlOrMeta+a');
|
|
await screen.getByLabel('City').pressSequentially('War', { delay: 50 });
|
|
```
|
|
|
|
## Locator reads
|
|
|
|
`waitFor` defaults `state` to `'visible'` and `timeout` to
|
|
`config.actionTimeout`, and throws `LOCATOR_NOT_FOUND` on timeout. `'attached'`
|
|
waits for one match, hidden or shown, `'detached'` for none, and `'hidden'` for
|
|
a hidden match or none. Several matches are `LOCATOR_AMBIGUOUS` in every
|
|
state. Any other state, or an option key besides `state` and `timeout`, is
|
|
`INVALID_ARGUMENT` before anything is resolved.
|
|
|
|
`textContent` and `allTextContents` return the node's rendered text with
|
|
whitespace collapsed to single spaces. On the web that is what `innerText`
|
|
reads, not the DOM's `textContent`: CSS `text-transform` applies,
|
|
`display: none` descendants are left out, and a `<br>` reads as a space. A
|
|
node that is not rendered itself, such as a `display: none` one, reads its
|
|
DOM text, as `innerText` does.
|
|
|
|
`isChecked` is `false` on a node with no checked state, such as a button or
|
|
a heading; it does not throw.
|
|
|
|
`textContent`, `inputValue`, `getAttribute`, and `allTextContents` throw
|
|
`POLICY_DENIED` on a secure field, and so do `expect(locator).toHaveValue`,
|
|
`toHaveText`, `toContainText`, and `toHaveAttribute`.
|
|
`isEnabled`, `isDisabled`, `isChecked`, and `boundingBox` are allowed there.
|
|
|
|
`boundingBox()` is `null` for a node that lays out no box (`display: none`
|
|
on it or an ancestor), and a box for one `visibility: hidden` keeps.
|
|
`inputValue()` and `toHaveValue` on a checkbox or radio read its value
|
|
attribute, `on` when it has none, whatever its checked state; `isChecked()`
|
|
reads the state.
|
|
|
|
`isHidden` is `!isVisible()` and `isDisabled` is `!isEnabled()`, with the
|
|
same strictness: `isHidden` is `true` for zero matches, `isDisabled` is
|
|
`LOCATOR_NOT_FOUND` there, and both are `LOCATOR_AMBIGUOUS` on several.
|
|
|
|
```ts
|
|
if (await screen.getByRole('alert').isVisible()) {
|
|
const message = await screen.getByRole('alert').textContent();
|
|
}
|
|
await screen.getByTestId('spinner').waitFor({ state: 'hidden' });
|
|
```
|
|
|
|
### Every match at once
|
|
|
|
`all()` resolves the query once and hands back one `nth(i)` locator per
|
|
match, so a loop can act on each row; `allTextContents()` reads every match's
|
|
normalized text in one call. Neither waits or enforces exactly-one: zero
|
|
matches is an empty array, the same snapshot rule as `count()`. A
|
|
`frameLocator` whose frame is not in the document counts as zero matches here
|
|
and in `isVisible()`, where an action or assertion polls for it. Each locator
|
|
`all()` returns re-resolves when used, so a list that changes under the loop
|
|
can make a later `nth(i)` point at a different row, or at nothing. Follow the
|
|
loop with an assertion on the list, and use
|
|
[`toHaveText([...])`](/reference/expect#locator-matchers) instead of a loop
|
|
when the point is to check the texts.
|
|
|
|
```ts
|
|
for (const row of await screen.getByRole('row').all()) {
|
|
await row.getByRole('checkbox').check();
|
|
}
|
|
expect(await screen.getByRole('listitem').allTextContents()).toEqual(['Alpha', 'Beta']);
|
|
```
|
|
|
|
## Types
|
|
|
|
```ts
|
|
/**
|
|
* The closed role vocabulary; an unsupported role is a type error. Every
|
|
* engine maps its platform's element types onto these names, so a role query
|
|
* reads the same against a browser and a device. A role the platform has no
|
|
* widget for matches nothing there; it is never a type error.
|
|
*/
|
|
export type Role =
|
|
| 'button'
|
|
| 'link'
|
|
| 'textbox'
|
|
| 'searchbox'
|
|
| 'combobox'
|
|
| 'listbox'
|
|
| 'option'
|
|
| 'checkbox'
|
|
| 'radio'
|
|
| 'radiogroup'
|
|
| 'switch'
|
|
| 'slider'
|
|
| 'spinbutton'
|
|
| 'progressbar'
|
|
| 'meter'
|
|
| 'image'
|
|
| 'heading'
|
|
| 'tab'
|
|
| 'tablist'
|
|
| 'tabpanel'
|
|
| 'menu'
|
|
| 'menubar'
|
|
| 'menuitem'
|
|
| 'menuitemcheckbox'
|
|
| 'menuitemradio'
|
|
| 'toolbar'
|
|
| 'tooltip'
|
|
| 'tree'
|
|
| 'treeitem'
|
|
| 'list'
|
|
| 'listitem'
|
|
| 'table'
|
|
| 'grid'
|
|
| 'row'
|
|
| 'rowgroup'
|
|
| 'rowheader'
|
|
| 'cell'
|
|
| 'gridcell'
|
|
| 'columnheader'
|
|
| 'separator'
|
|
| 'group'
|
|
| 'article'
|
|
| 'figure'
|
|
| 'form'
|
|
| 'status'
|
|
| 'alert'
|
|
| 'dialog'
|
|
| 'alertdialog'
|
|
| 'main'
|
|
| 'navigation'
|
|
| 'banner'
|
|
| 'contentinfo'
|
|
| 'complementary'
|
|
| 'region';
|
|
|
|
/**
|
|
* Spellings `getByRole` accepts beside the vocabulary and rewrites to a `Role`
|
|
* before the query is built: `img` is the ARIA name of `image`. An alias never
|
|
* reaches an engine, the replay cache, or a report; a `Role` is what they see.
|
|
*/
|
|
export type RoleAlias = 'img';
|
|
|
|
/** A string matches exactly; a RegExp uses its own source and flags. */
|
|
export type TextMatch = string | RegExp;
|
|
|
|
export interface TextMatchOptions {
|
|
/** Exact match, the default. `false` is case-insensitive substring matching; a RegExp ignores it. */
|
|
exact?: boolean;
|
|
/**
|
|
* When true, nodes the platform reports as hidden are excluded before the
|
|
* exactly-one rule is applied, so a visible node with a hidden twin (a
|
|
* prerendered copy kept after navigation, a closed drawer) still resolves.
|
|
* Omitted or false keeps every match, hidden ones included.
|
|
*/
|
|
visible?: boolean;
|
|
}
|
|
|
|
/**
|
|
* Role query options. A role query never matches a node hidden from the
|
|
* accessibility tree, on every engine; `visible` (inherited) is the one knob
|
|
* that narrows the other query kinds, to the nodes `toBeVisible()` accepts.
|
|
*/
|
|
export interface RoleOptions extends TextMatchOptions {
|
|
/** Accessible name filter. */
|
|
name?: TextMatch;
|
|
/** Requires the checked state. */
|
|
checked?: boolean;
|
|
/** Requires the disabled state. */
|
|
disabled?: boolean;
|
|
/** Requires the selected state. */
|
|
selected?: boolean;
|
|
/** Requires the expanded state. */
|
|
expanded?: boolean;
|
|
/** Requires the pressed state of a toggle button. */
|
|
pressed?: boolean;
|
|
/** Requires a heading level, 1 through 6. */
|
|
level?: number;
|
|
}
|
|
|
|
export interface ActionOptions {
|
|
/** Deadline in milliseconds; defaults to `config.actionTimeout`. */
|
|
timeout?: number;
|
|
}
|
|
|
|
/** `longPress` options: the hold time in milliseconds, 100 through 10000, default the engine's own. */
|
|
export interface LongPressOptions extends ActionOptions {
|
|
/** Hold time in milliseconds, 100 through 10000; unset, the engine's default. */
|
|
duration?: number;
|
|
}
|
|
|
|
/** `pressSequentially` options: an optional pause between characters. */
|
|
export interface PressSequentiallyOptions extends ActionOptions {
|
|
/** Milliseconds to wait between characters; omitted types the whole text in one call. */
|
|
delay?: number;
|
|
}
|
|
|
|
export interface SwipeOptions {
|
|
/** Swipe direction. */
|
|
direction: ScrollDirection;
|
|
/** Fling strength; default `none`. The three values are defined under screen.swipe. */
|
|
momentum?: Momentum;
|
|
from?: never;
|
|
to?: never;
|
|
}
|
|
|
|
/** A swipe along a path between two viewport points: a touch swipe on a device, a pointer drag on a document platform. */
|
|
export interface SwipePathOptions {
|
|
/** Where the finger goes down. */
|
|
from: Point;
|
|
/** Where it lifts. */
|
|
to: Point;
|
|
direction?: never;
|
|
momentum?: never;
|
|
}
|
|
|
|
/**
|
|
* A point in CSS pixels. For `screen.tapAt` and `screen.swipe` the origin is
|
|
* the viewport's top-left corner, the space `boundingBox()` reports in; for
|
|
* `tap({ position })` it is the node's own top-left corner.
|
|
*/
|
|
export type Point = ViewportPoint; // { x: number; y: number }
|
|
|
|
/** `tap`, `click`, `doubleTap`, and `secondaryTap` options: the action timeout and the keys held for the click. */
|
|
export interface ClickOptions extends ActionOptions {
|
|
/**
|
|
* Keys held while the pointer clicks, as a Shift-click extends a selection:
|
|
* `Shift`, `Control`, `Alt`, `Meta`, or `ControlOrMeta` (Control on Windows
|
|
* and Linux, Meta on macOS). Needs an engine that declares `tapModifiers`,
|
|
* `UNSUPPORTED_CAPABILITY` otherwise.
|
|
*/
|
|
modifiers?: readonly KeyModifier[];
|
|
}
|
|
|
|
/** A modifier key, for `modifiers` and the `press` key grammar. */
|
|
export type KeyModifier = 'Shift' | 'Control' | 'Alt' | 'Meta' | 'ControlOrMeta';
|
|
|
|
/** `tap` and `click` options. */
|
|
export interface TapOptions extends ClickOptions {
|
|
/**
|
|
* Where to tap, relative to the node's top-left corner. Without it the
|
|
* platform picks a point of the node, usually its center, behind its own
|
|
* actionability checks; with it the pointer is dispatched at that point
|
|
* once the node is in view and has a box, which needs the engine's `tap`
|
|
* pointer action.
|
|
*/
|
|
position?: Point;
|
|
}
|
|
|
|
/** One option of a select: its label (a bare string too), its `value` attribute, or its zero-based index. */
|
|
export type SelectOption =
|
|
| string
|
|
| { label: string; value?: never; index?: never }
|
|
| { value: string; label?: never; index?: never }
|
|
| { index: number; label?: never; value?: never };
|
|
|
|
/** A swipe or scroll direction. */
|
|
export type ScrollDirection = 'up' | 'down' | 'left' | 'right';
|
|
|
|
/** Fling strength of a swipe; defined under screen.swipe. */
|
|
export type Momentum = 'none' | 'slow' | 'fast';
|
|
```
|
|
|
|
A role query never matches a node hidden from the accessibility tree: one
|
|
that does not render, or one under `aria-hidden`. `visible` narrows the
|
|
other query kinds to the nodes that render, the check `toBeVisible()` makes,
|
|
so an `aria-hidden` node that still paints counts as visible there. See
|
|
[Hidden duplicates](#hidden-duplicates).
|
|
|
|
`img` is an alias, not a role: `getByRole('img', { name })` builds the same
|
|
query as `getByRole('image', { name })`, so a test ported from Playwright keeps
|
|
its spelling while engines, the replay cache, and reports see `image`. On the
|
|
web, `image` covers `<img>` with alt text and any element with `role="img"`;
|
|
an `<img alt="">` is decoration and matches nothing.
|
|
|
|
The web engine derives the roles from HTML the way HTML-AAM does: `<progress>`
|
|
is `progressbar`, `<meter>` is `meter`, `<hr>` is `separator`, `<fieldset>`
|
|
and `<details>` are `group`, `<input type="number">` is `spinbutton`,
|
|
`<input type="file">` is `button`, as Chrome and Playwright read it,
|
|
`<select size="3">` is a `listbox` like a `multiple` one, an `<input list>`
|
|
naming a `<datalist>` is a `combobox`, a `<td>` of a `role="grid"` table is a
|
|
`gridcell`,
|
|
`<thead>` and `<tbody>` are `rowgroup`, `<th scope="row">` is `rowheader`,
|
|
`<figure>` is `figure`, `<article>` is `article`, `<header>` and `<footer>` are
|
|
`banner` and `contentinfo` only outside sectioning content or an element with
|
|
a sectioning role (`article`, `complementary`, `main`, `navigation`, `region`),
|
|
and `<form>` and `<section>`
|
|
are `form` and `region` only when they carry an `aria-label`,
|
|
`aria-labelledby`, or `title`. A `<legend>`, `<figcaption>`, or `<caption>`
|
|
names its fieldset, figure, or table, so `toHaveAccessibleName` reads what
|
|
`getByRole('group', { name })` matched. A role accname names from content (a
|
|
button, link, heading, tab, menu item, option, checkbox, radio, switch, cell,
|
|
row or column header, row, tree item, tooltip) is named by its descendants, a
|
|
custom element's shadow tree included, so `getByRole('checkbox', { name })`
|
|
and `toHaveAccessibleName(name)` agree on a `<div role="checkbox">`. An
|
|
`<input type="submit">` or `type="reset"` with no `value` reads `Submit` or
|
|
`Reset`. `<menu>` is a `list`; only `role="menu"` is a
|
|
`menu`. A device engine maps the platform types it has (a tab bar or segmented
|
|
control is a `tablist`, a progress indicator a `progressbar`, a stepper a
|
|
`spinbutton`) and keeps any other type verbatim, so a role with no native
|
|
widget, such as `tooltip` or `figure`, matches nothing on a phone.
|
|
|
|
A `contenteditable` editing host, the root a TipTap, ProseMirror, Lexical, or
|
|
Slate editor renders into, is a `textbox` whose value is its text as rendered
|
|
(and, while it has focus, whose `selection` is the text selected inside it).
|
|
The value keeps spaces and newlines, so `toHaveValue` and `inputValue()` read
|
|
a `white-space: pre-wrap` editor like a textarea. An empty editor, holding only
|
|
the `<p><br></p>` or the zero-width no-break space its editor pads an empty
|
|
line with, reads as `''`, and that padding is never part of a value. It is named by its
|
|
`aria-label`, `aria-placeholder`, or the `data-placeholder` its editor paints;
|
|
the blocks inside it are content, not textboxes. The tag does not matter (an
|
|
`<article contenteditable>` is the editor, not an article), while a native
|
|
control or a drawn surface made editable keeps its own role. `getByRole` resolves through
|
|
Playwright's role selector, which has no such rule, so a test addresses an
|
|
editor by role only when the host carries `role="textbox"`; `getByLabel` and
|
|
`getByTestId` reach it either way. A name taken from a block's
|
|
`data-placeholder` (TipTap, ProseMirror) goes once the editor has content, as
|
|
the painted hint does, so the host reads as an unnamed `textbox` from then on;
|
|
a name from the host's own `aria-label`, `aria-labelledby`, `aria-placeholder`,
|
|
or `data-placeholder` (Quill) stays. Anchor a test on a label or a test id, not
|
|
on the placeholder.
|
|
|
|
|
|
For `selectOption`, pass a label string or exactly one of `label`, `value`,
|
|
or `index`. `value` matches the option's value attribute, which is what the
|
|
form submits. One option per call: an array, an object with more than one of
|
|
those keys, or a negative or fractional `index` fails with `INVALID_ARGUMENT`
|
|
before the engine acts.
|