mirror of
https://github.com/tester-army/e2e.git
synced 2026-11-25 02:24:26 +08:00
360 lines
13 KiB
Plaintext
360 lines
13 KiB
Plaintext
---
|
|
title: screen and Locator
|
|
description: Queries, refinement, actions, and reads.
|
|
---
|
|
|
|
A `Locator` is a query expression, not a node; nothing resolves until an
|
|
action, read, or assertion runs. `Locator extends Screen`, so every query
|
|
method is also available on a locator, scoped to its subtree.
|
|
|
|
```ts
|
|
export interface Screen {
|
|
/** Creates a lazy role query. */
|
|
getByRole(role: Role, 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;
|
|
/** Performs a viewport-level swipe. */
|
|
swipe(options: SwipeOptions): Promise<void>;
|
|
/** Scrolls until a locator resolves visibly or times out. */
|
|
scrollUntilVisible(
|
|
target: Locator,
|
|
options?: { direction?: ScrollDirection; timeout?: number },
|
|
): Promise<void>;
|
|
}
|
|
```
|
|
|
|
An action, read, or assertion requires exactly one match. Reads resolve once
|
|
and read once; use [`expect`](/reference/expect) to wait for a value.
|
|
|
|
| Operation | Zero matches | Multiple matches |
|
|
| --- | --- | --- |
|
|
| Actions | Poll until the timeout, then `LOCATOR_NOT_FOUND` | `LOCATOR_AMBIGUOUS` |
|
|
| Reads | `LOCATOR_NOT_FOUND` | `LOCATOR_AMBIGUOUS` |
|
|
| `count()` | `0` | The count |
|
|
| `isVisible()` | `false` | `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 (`playwright({ 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();
|
|
```
|
|
|
|
The predicate is the one `toBeVisible()`, `isVisible()`, and `waitFor()`
|
|
read. It composes 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
|
|
|
|
Synchronous, returns a new locator, performs no work.
|
|
|
|
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 Playwright 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.swipe
|
|
|
|
```ts
|
|
swipe(options: SwipeOptions): Promise<void>;
|
|
```
|
|
|
|
Viewport-level gesture. Uses `config.actionTimeout`. Throws `ACTION_FAILED`
|
|
when the gesture is rejected and `UNSUPPORTED_CAPABILITY` when the engine
|
|
does not list `swipe` in its actions.
|
|
|
|
## 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. */
|
|
tap(options?: ActionOptions): Promise<void>;
|
|
/** Alias of tap. */
|
|
click(options?: ActionOptions): Promise<void>;
|
|
/** Double-taps exactly one matching actionable node. */
|
|
doubleTap(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 enabled state. */
|
|
isEnabled(): 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>;
|
|
/** 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`.
|
|
- `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('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`, and `getAttribute` throw `POLICY_DENIED` on a
|
|
secure field. `isEnabled`, `isChecked`, and `boundingBox` are allowed there.
|
|
|
|
```ts
|
|
if (await screen.getByRole('alert').isVisible()) {
|
|
const message = await screen.getByRole('alert').textContent();
|
|
}
|
|
await screen.getByTestId('spinner').waitFor({ state: 'hidden' });
|
|
```
|
|
|
|
## Types
|
|
|
|
```ts
|
|
/** The closed role vocabulary; an unsupported role is a type error. */
|
|
export type Role =
|
|
| 'button'
|
|
| 'link'
|
|
| 'textbox'
|
|
| 'searchbox'
|
|
| 'combobox'
|
|
| 'listbox'
|
|
| 'option'
|
|
| 'checkbox'
|
|
| 'radio'
|
|
| 'switch'
|
|
| 'slider'
|
|
| 'image'
|
|
| 'heading'
|
|
| 'tab'
|
|
| 'menuitem'
|
|
| 'list'
|
|
| 'listitem'
|
|
| 'table'
|
|
| 'row'
|
|
| 'cell'
|
|
| 'columnheader'
|
|
| 'status'
|
|
| 'alert'
|
|
| 'dialog'
|
|
| 'alertdialog'
|
|
| 'main'
|
|
| 'navigation'
|
|
| 'banner'
|
|
| 'contentinfo'
|
|
| 'complementary'
|
|
| 'region';
|
|
|
|
/** 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;
|
|
}
|
|
|
|
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;
|
|
}
|
|
|
|
/** 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).
|
|
|
|
|
|
`label`, `value` (the option's `value` attribute, what the form submits), or
|
|
`index`, never two.
|