Files
e2e/docs/reference/screen.mdx
T

534 lines
21 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.
```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 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. */
getByTestId(id: string, 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; timeout?: number },
): Promise<void>;
}
```
Most operations require exactly one match. Reads return the current value
without waiting for it to change; 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` |
## Queries
Every query returns a `Locator` synchronously and performs no work.
`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.
```ts
screen.getByRole('button', { name: 'Save' });
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 web.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()`. It works with scopes, `filter`, `first`, `last`, and `nth`:
`getByText('Save', { visible: true }).first()` is the first visible match.
Prefer it over `web.locator('p:visible')`, which ties the test to CSS.
## Refinement
Refinement returns a new locator without querying the app.
Throws `INVALID_LOCATOR` when `filter` gets neither `hasText` nor `has`, when
`has` is not a runner locator, or when `nth` gets a negative or non-integer
index.
```ts
const row = screen.getByRole('listitem').filter({ hasText: 'Invoice 42' });
await row.getByRole('button', { name: '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', { name: '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. `{ 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; timeout?: number },
): Promise<void>;
```
| Name | Type | Default |
| --- | --- | --- |
| `target` | `Locator` | - |
| `options.direction` | `ScrollDirection` | `'down'` |
| `options.timeout` | `number` | `30000`, its own default, not `config.actionTimeout` |
Throws `INVALID_LOCATOR` for a non-runner locator, `LOCATOR_NOT_FOUND` when the
deadline expires first.
```ts
await screen.scrollUntilVisible(screen.getByRole('button', { name: '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?: ActionOptions): Promise<void>;
/** Performs a secondary tap, such as a right click or two-finger tap. */
secondaryTap(options?: ActionOptions): 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>;
/** 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. */
waitFor(options?: { state?: '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.
- `click` is an alias of `tap`.
- `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).
- `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.
- `setInputFiles` paths resolve from the project root. An empty list or blank
entry throws `INVALID_ARGUMENT`.
- `dragTo` with a non-runner target throws `INVALID_LOCATOR`.
- 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', { name: 'Remember me' }).check();
await screen.getByLabel('Plan').selectOption({ label: 'Pro' });
await screen.getByLabel('Plan').selectOption({ value: 'pro' });
await screen.getByRole('button', { name: 'Save' }).tap({ timeout: 10_000 });
await screen.getByRole('image', { name: 'Seat map' }).tap({ position: { x: 120, y: 48 } });
await screen.getByRole('textbox', { name: 'Search' }).press('Enter');
await screen.getByRole('textbox', { name: 'Notes' }).press('ControlOrMeta+a');
```
## Locator reads
`waitFor` defaults `state` to `'visible'` and `timeout` to
`config.actionTimeout`, and throws `LOCATOR_NOT_FOUND` on timeout.
`textContent`, `inputValue`, `getAttribute`, and `allTextContents` throw
`POLICY_DENIED` on a secure field. `isEnabled`, `isDisabled`, `isChecked`,
and `boundingBox` are allowed there.
`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()`. 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 trace 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 the same way.
*/
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 500. */
export interface LongPressOptions extends ActionOptions {
/** Hold time in milliseconds, 100 through 10000; default 500. */
duration?: number;
}
export interface SwipeOptions {
/** Swipe direction. */
direction: ScrollDirection;
/** Fling strength; default `none`. */
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` and `click` options. */
export interface TapOptions extends ActionOptions {
/**
* 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. */
export type Momentum = 'none' | 'slow' | 'fast';
```
A role query never matches a node hidden from the accessibility tree.
`visible` applies the same rule to the other query kinds. 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 trace 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`,
`<thead>` and `<tbody>` are `rowgroup`, `<th scope="row">` is `rowheader`,
`<figure>` is `figure`, `<article>` is `article`, 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. `<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.
For `selectOption`, pass exactly one of `label`, `value`, or `index`. `value`
matches the option's value attribute, which is what the form submits.