Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions .changeset/viewport-matcher.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
---
"e2e": patch
"@e2e-dev/core": patch
"@e2e-dev/web": patch
"@e2e-dev/mobile": patch
---

Add `expect(locator).toBeInViewport({ ratio })`, which waits for part of the
match, or that share of its box, to be inside the viewport without scrolling.
No match counts as outside, so `.not` accepts zero matches. The web engine
measures with the page's `IntersectionObserver`, matching Playwright, so
scrolling and `overflow` ancestors and frames clip the box. The mobile engine
reports only whether the node is on screen, because a device reports bounds
already clipped, so `ratio > 0` there fails with `UNSUPPORTED_CAPABILITY`
once the node is on screen.
Engines implement the optional `viewportIntersection` method for the new
`viewport-intersection` capability.
5 changes: 5 additions & 0 deletions apps/mobile-benchmark/tests/flows-lists.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,12 @@ test('sticky chrome: accept below the fold, then continue', async ({ app, device
await screen.getByTestId('continue-button').tap();
await expect(screen.getByText('Accept the terms at the bottom first')).toBeVisible();
const accept = screen.getByTestId('accept-terms');
await expect(accept).not.toBeInViewport();
await screen.scrollUntilVisible(accept, { direction: 'down' });
await expect(accept).toBeInViewport();
// A device reports only the visible part of a box, so no share of it can be measured.
const refused = await expect(accept).toBeInViewport({ ratio: 0.5 }).then(() => undefined, (error: unknown) => error);
expect(refused).toHaveProperty('code', 'UNSUPPORTED_CAPABILITY');
await accept.tap();
await expect(screen.getByText('Terms accepted ✓')).toBeVisible();
await screen.getByTestId('continue-button').tap();
Expand Down
13 changes: 13 additions & 0 deletions apps/testbed/tests/controls.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,19 @@ test.describe('controls', { requires: ['browser'], tags: ['controls'] }, () => {
expect(error).toHaveProperty('message', expect.stringContaining('opened no file chooser'));
});

test('toBeInViewport follows the scroll position, and no match is outside the viewport', async ({ screen }) => {
const footnote = screen.getByText('Footnote', { exact: true });
await expect(footnote).not.toBeInViewport();
const error = await failure(() => expect(footnote).toBeInViewport({ timeout: 500 }));
expect(error).toHaveProperty('code', 'ASSERTION_FAILED');
expect(error).toHaveProperty('message', expect.stringContaining('observed: outside the viewport'));

await footnote.scrollIntoView();
await expect(screen.getByLabel('Footnote state')).toHaveText('in view');
await expect(footnote).toBeInViewport({ ratio: 1 });
await expect(screen.getByText('No such footnote')).not.toBeInViewport();
});

test('a missing locator fails as LOCATOR_NOT_FOUND after its timeout', async ({ screen }) => {
expect(await failure(() => screen.getByRole('button', 'Nope').tap({ timeout: 500 }))).toHaveProperty(
'code',
Expand Down
4 changes: 2 additions & 2 deletions docs/migrate/playwright.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ run only in a browser, so a test that uses it declares

| Playwright | e2e |
| --- | --- |
| `toBeVisible()`, `toBeHidden()`, `toBeEnabled()`, `toBeDisabled()`, `toBeChecked()`, `toBeFocused()`, `toBeAttached()`, `toHaveText()`, `toContainText()`, `toHaveValue()`, `toHaveAttribute()`, `toHaveCount()`, `toHaveAccessibleName()`, `toHaveRole()`, `toBeEditable()` | the same, with `{ visible }`, `{ enabled }`, `{ editable }`, `{ checked }`, `{ attached }`, and `{ ignoreCase }` |
| `toBeVisible()`, `toBeHidden()`, `toBeEnabled()`, `toBeDisabled()`, `toBeChecked()`, `toBeFocused()`, `toBeAttached()`, `toBeInViewport()`, `toHaveText()`, `toContainText()`, `toHaveValue()`, `toHaveAttribute()`, `toHaveCount()`, `toHaveAccessibleName()`, `toHaveRole()`, `toBeEditable()` | the same, with `{ visible }`, `{ enabled }`, `{ editable }`, `{ checked }`, `{ attached }`, `{ ratio }`, and `{ ignoreCase }`; `toBeInViewport` reads a zero-size element as outside and [differs on a device](/reference/expect#tobeinviewport) |
| `toHaveId(id)`, `toContainClass(name)` | `toHaveAttribute('id', id)`, `toHaveAttribute('class', RegExp)` |
| `expect(page).toHaveURL()`, `toHaveTitle()` | `expect(browser).toHaveURL()`, `toHaveTitle()` |
| `expect(page).toHaveScreenshot()`, `expect(locator).toHaveScreenshot()` | `expect(screen).toHaveScreenshot()` and the locator form, see [Visual comparison](/visual-testing) |
Expand Down Expand Up @@ -268,7 +268,7 @@ purpose. Use the workaround, or keep the test in Playwright.

| Playwright | Use today |
| --- | --- |
| `toBeEmpty()`, `toBeInViewport()` | `toHaveValue('')` on a form control, `toHaveText('')` on other elements; `expect.poll` over `boundingBox()` |
| `toBeEmpty()` | `toHaveValue('')` on a form control, `toHaveText('')` on other elements |
| `{ fullPage, clip }`, `snapshotPathTemplate`, `ignoreSnapshots` | The viewport or one locator in `toHaveScreenshot`; a tag and `--exclude-tag` to skip visual tests |
| `expect.configure()` | `{ timeout }` on each call |
| `@axe-core/playwright` | axe-core through `browser.addInitScript({ path: 'node_modules/axe-core/axe.min.js' })`, then `axe.run()` in `browser.evaluate` |
Expand Down
1 change: 1 addition & 0 deletions docs/reference/engine-protocol.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ params are the member's arguments by name, with every `OperationContext` as
| --- | --- | --- |
| `engine/observe` | `{ operation, options? }` | `EngineSnapshot` |
| `engine/readStyle` | `{ ref, properties, operation }` | `ComputedStyleValues` |
| `engine/viewportIntersection` | `{ ref, operation }` | `ViewportIntersection`; leave `ratio` out, never `null`, when the platform cannot measure it |
| `engine/locate` | `{ expression, operation }` | `SemanticNode[]` |
| `engine/perform` | `{ ref, action, operation }` | `null` |
| `engine/performAt` | `{ point, action, operation }` | `null` |
Expand Down
32 changes: 31 additions & 1 deletion docs/reference/engine.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,10 @@ rules:
| `spiVersion` | Anything but `1`. |
| `platform` | Empty. |
| `workers` | Not a positive safe integer. |
| `observe`, `readStyle`, `locate`, `perform`, `performAt`, `prepare`, `finish`, `doctor`, `init`, `startAttempt`, `settleAttempt`, `endAttempt`, `dispose`, `validateApp` | Not a function. |
| `observe`, `readStyle`, `viewportIntersection`, `locate`, `perform`, `performAt`, `prepare`, `finish`, `doctor`, `init`, `startAttempt`, `settleAttempt`, `endAttempt`, `dispose`, `validateApp` | Not a function. |
| any other top-level key | On an object literal, `app` included: declare the app on the target and check it in `validateApp`. A class instance's own fields are not checked. |
| `readStyle`, `perform`, `locate`, `performAt`, `keyboard` | Declared without `observe`. |
| `viewportIntersection` | Declared without `locate`. |
| `perform`, `actions` | One without the other. An `actions` list that is empty, repeats a kind, or names one outside `KNOWN_LOCATOR_ACTION_KINDS`. |
| `performAt`, `pointerActions` | One without the other. A `pointerActions` list that is empty, repeats a kind, or names one outside `POINTER_ACTION_KINDS`. |
| `tapModifiers` | Not a boolean, or `true` without `perform`. |
Expand Down Expand Up @@ -140,6 +141,7 @@ The body of one target. Every member but `name`, `version`, and
| `workers` | `number` |
| [`observe`](#observation) | method |
| [`readStyle`](#rendered-node-properties) | method |
| [`viewportIntersection`](#viewport-intersection) | method |
| [`perform`, `actions`](#actions) | method, kinds |
| [`locate`](#capabilities) | method |
| [`performAt`, `pointerActions`](#pointer-actions) | method, kinds |
Expand Down Expand Up @@ -189,6 +191,8 @@ export interface Engine {
observe?(context: OperationContext, options?: EngineObserveOptions): Promise<EngineSnapshot>;
/** capability: computed-style, requires observation. Read-only rendered properties of an observation ref. */
readStyle?(ref: NodeRef, properties: readonly ComputedStyleProperty[], context: OperationContext): Promise<ComputedStyleValues>;
/** capability: viewport-intersection, requires location. How much of a located node is inside the viewport. */
viewportIntersection?(ref: NodeRef, context: OperationContext): Promise<ViewportIntersection>;
/**
* Performs one action on a ref from the newest observation or `locate`,
* with the platform's actionability checks. Both agent tools and locator
Expand Down Expand Up @@ -407,6 +411,7 @@ member. Three gaps end differently:
| `readStyle` | `computed-style` | `observe` | Allow-listed rendered properties for read-only project tools. |
| `perform` + `actions` | `actions` | `observe` | Node actions of the declared kinds, with platform actionability checks. |
| `locate` | `location` | `observe` | `screen`, `Locator`, `expect(locator)`. |
| `viewportIntersection` | `viewport-intersection` | `locate` | `expect(locator).toBeInViewport()`. |
| `tapModifiers: true` | - | `perform` | `modifiers` on `tap`, `doubleTap`, and `secondaryTap`. |
| `selectsDevice: true` | - | `prepare` | `e2e run --device`, the device `prepare` binds. |
| `launchArgumentValues: true` | - | - | The object form of `app.launchArguments`, in `EngineAppInfo.launchArgumentValues`. |
Expand Down Expand Up @@ -440,6 +445,30 @@ throws `INVALID_ARGUMENT` for an empty list or a property outside the
allow-list. Call it before page access.
See [Project tools](/tools#read-a-nodes-computed-style) for `ToolContext.read`.

#### Viewport intersection

`viewportIntersection(ref, context)` measures how much of a located node is
inside the viewport for [`toBeInViewport`](/reference/expect#tobeinviewport),
without scrolling or changing app state. Clip the box by the viewport and every
clipping ancestor, such as a scroll container, `overflow: hidden`, or a frame.

```ts
export interface ViewportIntersection {
/** Whether a positive area of the box is inside; false for a node with no box or an empty one. */
readonly intersects: boolean;
/** The inside area's share of the whole box, from 0 to 1; absent where the platform reports only the visible part of a box. */
readonly ratio?: number;
}
```

Omit `ratio` when the platform reports only the visible part of a box, as a
device does. `toBeInViewport` with `ratio > 0` then fails with
`UNSUPPORTED_CAPABILITY` instead of reading that part as the whole box. Throw
retryable `NODE_STALE` if the node no longer binds, and
`UNSUPPORTED_CAPABILITY` if the platform cannot report the node's bounds or
screen position. A `ratio` is above `0` exactly when `intersects` is true. The
harness fails the step with `ENGINE_FAILURE` on an answer outside this shape.

#### Agent verbs

The agent offers the model only the verbs the engine's declarations unlock.
Expand Down Expand Up @@ -537,6 +566,7 @@ engine. A target with `app.url` has `browser`, and one with `app.bundleId` or
export type EngineCapability =
| 'observation'
| 'computed-style'
| 'viewport-intersection'
| 'actions'
| 'location'
| 'pointer'
Expand Down
2 changes: 1 addition & 1 deletion docs/reference/errors.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ These appear in terminal output and in the report as plain string codes.
| `TEST_AMBIGUOUS` | `e2e mcp`: `open_session`'s `test` selected several tests on the session's target. The message lists them as `file:line` | configuration | 2 |
| `SESSION_TEST_UNSUPPORTED` | `e2e mcp`: `open_session`'s `test` selected a test a session cannot run alone: a serial group member, a test that starts from a setup test's `session`, or a test that runs as several agents. Run it with `e2e run` | configuration | 2 |
| `UNSUPPORTED_ARTIFACT` | A [`video` mode](/reference/config#recording) set on a target, or on a test that will run there, records on some attempt, and the target's engine cannot record video. The message names the target, and the test for a test's mode. A mode from the config root or `--video` never raises it: it applies to the targets that can record, with a notice naming the rest | configuration | 2 |
| `UNSUPPORTED_CAPABILITY` | A fixture, action, or tier the target's engine does not declare: a built-in fixture a worker fixture uses while no test or suite hook runs (a fixture the target does not have is `COLLECTION_ERROR`), `screen` without `locate`, state restore without `state`, screenshots without `artifacts`, `app.clearState()` on a persistent browser context (the message names the mode), `agent.assert` `vision` with an executor that does not declare `vision: true`, `app.startRecording()` while the test's video records, or `browser.webmcp` in a browser or on a page without WebMCP. Also `e2e run --device` when no selected target's engine chooses a device (`web()`), or the target's devices come from a device provider | configuration | 2 |
| `UNSUPPORTED_CAPABILITY` | A fixture, action, or tier the target's engine does not declare: a built-in fixture a worker fixture uses while no test or suite hook runs (a fixture the target does not have is `COLLECTION_ERROR`), `screen` without `locate`, state restore without `state`, screenshots without `artifacts`, `app.clearState()` on a persistent browser context (the message names the mode), `agent.assert` `vision` with an executor that does not declare `vision: true`, `app.startRecording()` while the test's video records, `browser.webmcp` in a browser or on a page without WebMCP, or `toBeInViewport` on an engine without `viewportIntersection`, on a node whose bounds or screen position the engine cannot report, or with `ratio` above 0 on an engine that reports no share of the box, such as a device. Also `e2e run --device` when no selected target's engine chooses a device (`web()`), or the target's devices come from a device provider | configuration | 2 |
| `NO_TESTS` | Zero runnable ordinary test-target pairs. The message names the cause: no file matched the `tests` globs (it lists look-alike files), a positional matched nothing (it names the `!` entry that excludes a file the positional names), a file registered no tests, or filters excluded everything. Suppress with `--pass-with-no-tests`. When [test filters](/filters) leave nothing to run, the run passes instead (exit 0). Also `e2e mcp`'s `open_session` when its `test` selects no runnable test. | configuration | 2 |
| `RUNNER_BUSY` | A suite overlapped another suite, an opening or open host, or a live attempt; or a host opened during a suite; or `e2e run --step` started without a terminal in a directory where another run is already controlled with `e2e run --step`; or a test reached `screen.pause()` in a run without a terminal while another run in the directory was controlled that way; or a run killed while it took control of the directory left its lock (the message names the file to remove). Await the suite and close existing hosts before you retry; end a stepped run with `e2e run --step stop`, or remove the lock file the message names. | configuration | 2 |
| `RUNNER_NOT_INSTALLED` | `test`, `describe`, or a hook from `@e2e-dev/web`, `@e2e-dev/mobile`, or `@e2e-dev/desktop` was called where `e2e` is not installed, as in a program on `@e2e-dev/core` alone. The engine factory from the same entry still works. Install `e2e` to write tests | configuration | 2 |
Expand Down
42 changes: 39 additions & 3 deletions docs/reference/expect.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ await expect(screen.getByTestId('cart-empty'), 'the cart is empty').toBeVisible(
| --- | --- |
| [`toBeVisible`](#tobevisible-and-tobehidden) | Waits for visibility |
| [`toBeHidden`](#tobevisible-and-tobehidden) | Waits for hidden or absent state |
| [`toBeInViewport`](#tobeinviewport) | Waits for the match to be in view |
| [`toBeAttached`](#tobeattached) | Waits for one match to exist |
| [`toBeEnabled`](#tobeenabled-and-tobedisabled) | Waits for enabled state |
| [`toBeDisabled`](#tobeenabled-and-tobedisabled) | Waits for disabled state |
Expand Down Expand Up @@ -105,6 +106,34 @@ await expect(screen.getByRole('dialog')).not.toBeVisible({ timeout: 10_000 });
await expect(screen.getByRole('dialog')).toBeVisible({ visible: false }); // as toBeHidden()
```

#### `toBeInViewport`

Waits for part of the one match to be inside the viewport. It never scrolls,
and it says nothing about another element covering the match. No match counts
as outside the viewport, so `.not` accepts zero matches. A zero-size box, or a
web element with no box such as `display: none`, also counts as outside.

```ts
await expect(screen.getByRole('toolbar', 'Selection')).toBeInViewport();
await expect(screen.getByRole('toolbar', 'Selection')).toBeInViewport({ ratio: 0.5 });
await expect(screen.getByRole('alert')).not.toBeInViewport();
```

`ratio` is a number from `0` to `1` setting the share of the box that must be
inside. `0` means any positive area, the same as omitting `ratio`. Any value
outside `0` to `1` fails with `INVALID_ARGUMENT`. What counts as inside depends
on the engine:

| Engine | Measures | `ratio` |
| --- | --- | --- |
| `@e2e-dev/web` | Uses the page's `IntersectionObserver`, matching Playwright. The viewport, scrolling or `overflow` ancestors, and frames clip the box. Replacing `IntersectionObserver` changes the result | Supported |
| `@e2e-dev/mobile` | Checks device-reported bounds against the confirmed screen. Scroll containers clip the bounds, and offscreen nodes leave the tree | `ratio > 0` fails with `UNSUPPORTED_CAPABILITY` once the node is on screen, because the device reports only the visible part |

It fails at once with `UNSUPPORTED_CAPABILITY`, `.not` included, if the target's
engine does not implement
[`viewportIntersection`](/reference/engine#viewport-intersection), or if the
engine cannot report a node's bounds or screen position.

#### `toBeAttached`

Waits for one match to exist, hidden or shown, where `toBeVisible` needs a
Expand Down Expand Up @@ -862,11 +891,12 @@ has held:

- A positive locator matcher requires exactly one match. The exceptions are
`toHaveCount` and the list form of `toHaveText` and `toContainText`.
- Zero matches keep polling until the timeout.
- Zero matches keep polling until the timeout, except for the matchers below
that accept them.
- Multiple matches fail immediately with `LOCATOR_AMBIGUOUS`.
- `toBeHidden`, `toBeVisible({ visible: false })`,
`toBeAttached({ attached: false })`, negated visibility, and negated
`toBeAttached` accept zero matches.
`toBeAttached({ attached: false })`, negated visibility, negated
`toBeAttached`, and negated `toBeInViewport` accept zero matches.
- For those, for `toHaveCount` and the list forms, and for
`waitFor({ state: 'detached' })` and `'hidden'`, a locator under a frame
that is not in the document is zero matches rather than a wait for the
Expand Down Expand Up @@ -971,6 +1001,12 @@ export interface AsyncExpectation {
toBeVisible(options?: { visible?: boolean; timeout?: number }): Promise<void>;
/** Waits for hidden or absent state. */
toBeHidden(options?: { timeout?: number }): Promise<void>;
/**
* Waits for part of the match to be inside the viewport, after clipping by
* scrolling and overflow ancestors; `ratio` (0 to 1) sets the share of its
* box that must be. No match is outside the viewport. It never scrolls.
*/
toBeInViewport(options?: { ratio?: number; timeout?: number }): Promise<void>;
/** Waits for one match to exist, visible or not; `attached: false` waits for none. */
toBeAttached(options?: { attached?: boolean; timeout?: number }): Promise<void>;
/** Waits for enabled state; `enabled: false` waits for disabled state. */
Expand Down
3 changes: 2 additions & 1 deletion docs/reference/test.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -732,7 +732,8 @@ test('onboarding asks for the camera', { requires: ['native-app'] }, async ({ ap
Accepted values:

- The harness capabilities of the target's engine: `observation`, `actions`,
`location`, `pointer`, `keyboard`, `computed-style`, `state`, `artifacts`.
`location`, `pointer`, `keyboard`, `computed-style`, `viewport-intersection`,
`state`, `artifacts`.
- One per built-in fixture an engine contributes: `browser`, `device`. See
[the engine contract](/reference/engine#engine).
- The kind of app the target declares: `browser` for an `app.url`,
Expand Down
Loading
Loading