mirror of
https://github.com/tester-army/e2e.git
synced 2026-11-22 07:55:36 +08:00
* fix(web): evaluate a browser.evaluate string as an expression * docs(web): say evaluate returns a string's value and awaits a promise
725 lines
32 KiB
Plaintext
725 lines
32 KiB
Plaintext
---
|
|
title: Browser
|
|
description: The browser engine, its options, and the browser fixture it contributes.
|
|
---
|
|
|
|
`@e2e-dev/web` drives Chromium, Firefox, and WebKit through Playwright.
|
|
A web target names it as its engine, and it contributes the `browser` fixture for
|
|
browser-only work. Import `test` from the package to have `browser` typed.
|
|
|
|
The package depends on `playwright-core` pinned to an exact version, so the
|
|
engine always runs the Playwright it was tested against. An app that depends
|
|
on Playwright itself keeps its own copy; the two share a browser cache only
|
|
when their versions match.
|
|
|
|
```ts title="e2e.config.ts"
|
|
import type { E2EConfig } from 'e2e';
|
|
import { web } from '@e2e-dev/web';
|
|
|
|
export default {
|
|
targets: [{ engine: web(), app: { url: 'http://localhost:3000' } }],
|
|
} satisfies E2EConfig;
|
|
```
|
|
|
|
## Installing browsers
|
|
|
|
A missing browser downloads once per run, before the run's clock starts. To
|
|
install browsers as their own step, in CI or a container image, run the
|
|
package's command. It installs the browsers for the Playwright version the
|
|
engine pins:
|
|
|
|
<CodeGroup>
|
|
```bash npm
|
|
npx @e2e-dev/web install chromium --with-deps
|
|
```
|
|
|
|
```bash pnpm
|
|
pnpm exec e2e-web install chromium --with-deps
|
|
```
|
|
|
|
```bash bun
|
|
bunx @e2e-dev/web install chromium --with-deps
|
|
```
|
|
</CodeGroup>
|
|
|
|
Name any of `chromium`, `firefox`, and `webkit`; with none named it installs
|
|
`chromium`. `--with-deps` also installs the system libraries the browsers need
|
|
on Linux. The command exits with the installer's exit code.
|
|
|
|
## Options
|
|
|
|
```ts
|
|
/**
|
|
* Options of the browser engine: how it drives the app. The app itself
|
|
* (its `url`, `environment`, `identity`, and the command that starts it) is
|
|
* the target's `app`.
|
|
*/
|
|
export interface WebOptions {
|
|
/**
|
|
* Browser to launch, `chromium` by default. A `BrowserProvider` leases
|
|
* hosted browsers instead: one per worker slot at `prepare`, or one per
|
|
* attempt, each attached to over CDP and released when its scope ends. A
|
|
* provider implies chromium and excludes `connect`.
|
|
*/
|
|
readonly browser?: BrowserName | BrowserProvider;
|
|
/**
|
|
* Initial viewport of every attempt's page; default 1280 by 720. `null`
|
|
* emulates no size: the page fills the browser window, whatever size the
|
|
* window has (a hosted browser's live view, a headed run), and
|
|
* `browser.setViewport` still fixes one for the rest of the attempt.
|
|
*/
|
|
readonly viewport?: ViewportSize | null;
|
|
/**
|
|
* How the engine's own screencast records an attempt that records video.
|
|
* A browser provider that records (`BrowserProvider.record`) records in
|
|
* its place, and ignores these. Which attempts record is the config's
|
|
* `video`, not an engine option.
|
|
*/
|
|
readonly screencast?: WebScreencastOptions;
|
|
/**
|
|
* Attach to a remote browser over CDP instead of launching locally. Requires
|
|
* the chromium browser (the default). Wired by a hosted-browser engine.
|
|
*/
|
|
readonly connect?: WebConnectOptions;
|
|
/**
|
|
* Headers added to requests within the app's site, including subdomains.
|
|
* Useful for preview-protection tokens. Other sites never receive them.
|
|
* Names are case-insensitive and replace existing headers of the same name.
|
|
* This enables request routing, disables the browser's HTTP cache, and
|
|
* blocks service workers. Playwright traces record request headers.
|
|
*/
|
|
readonly headers?: Readonly<Record<string, string>>;
|
|
/**
|
|
* HTTP basic authentication. The browser answers a `401` challenge with
|
|
* these credentials on any origin, matching Playwright's `httpCredentials`.
|
|
*/
|
|
readonly basicAuth?: WebBasicAuth;
|
|
/**
|
|
* The attribute that carries an element's test id: what the `testId` query
|
|
* (`screen.getByTestId`) resolves and what `SemanticNode.testId` reports.
|
|
* Defaults to `data-testid`.
|
|
*/
|
|
readonly testIdAttribute?: string;
|
|
/**
|
|
* The `User-Agent` every attempt's context sends and `navigator.userAgent`
|
|
* reports, for an app that switches into a test mode on a marker in the
|
|
* agent string. Defaults to the browser's own. A `user-agent` entry in
|
|
* `headers` beside it is `INVALID_CONFIG`, and so is a persistent context
|
|
* (`connect.reconnectEndpoint`, or a provider with `scope: 'attempt'`).
|
|
*/
|
|
readonly userAgent?: string;
|
|
/**
|
|
* The locale every attempt's context runs in, a BCP 47 tag such as
|
|
* `de-DE`: what `navigator.language`, `Intl` formatting, and the
|
|
* `Accept-Language` header report. Defaults to the browser's own. An
|
|
* `accept-language` entry in `headers` beside it is `INVALID_CONFIG`, and
|
|
* so is a persistent context.
|
|
*/
|
|
readonly locale?: string;
|
|
/**
|
|
* The IANA time zone every attempt's context runs in, such as
|
|
* `Europe/Berlin`: what `Date` and `Intl` resolve local time against.
|
|
* Defaults to the machine's. A persistent context is `INVALID_CONFIG`.
|
|
*/
|
|
readonly timezoneId?: string;
|
|
/** Scripts every document runs before the page's own. See [Init scripts](#init-scripts). */
|
|
readonly initScripts?: readonly WebInitScript[];
|
|
}
|
|
|
|
/** JavaScript source, a file relative to the project root, or a function. */
|
|
export type WebInitScript = string | { readonly path: string } | (() => unknown);
|
|
|
|
/** The engine's screencast of the page: the frame size and the JPEG quality of the frames it encodes. */
|
|
export interface WebScreencastOptions {
|
|
/** Frame size in pixels; default the viewport's, or the window's under `viewport: null`. A smaller size makes a smaller file. */
|
|
readonly size?: ViewportSize;
|
|
/** JPEG quality of each captured frame, 0 through 100; Playwright's default when unset. */
|
|
readonly quality?: number;
|
|
}
|
|
```
|
|
|
|
The app a web target opens is the target's `app`, not an engine option:
|
|
`targets: [{ engine: web(), app: { url } }]`, documented under
|
|
[the app under test](/reference/config#the-app-under-test). A `web()` target
|
|
needs `app.url` and refuses the device keys (`bundleId`, `appPath`,
|
|
`launchArguments`, `permissions`); `web({ url })` or any other app key on
|
|
`web()` is an unknown key, `INVALID_CONFIG`.
|
|
A target with `app.url` is a `browser` target, so `requires: ['browser']`
|
|
selects web targets.
|
|
|
|
`connect` needs chromium; `cdpEndpoint(signal)` is called once per worker and
|
|
again at an attempt start after a disconnect. A `browser` provider object leases hosted
|
|
browsers and releases them when the run or the attempt ends; see
|
|
[Hosted browsers](/browser#hosted-browsers) for the `BrowserProvider`
|
|
contract and an example provider. `browser: provider` together with
|
|
`connect` is `INVALID_CONFIG`, and so is an option `web()` does not take, or
|
|
an unknown key inside `connect` or `basicAuth`, naming the nearest known key
|
|
when it is a likely typo (`viewprt` is `viewport`) and every key otherwise. `:` is not allowed in the `basicAuth` user name.
|
|
The `basicAuth` password is a string or `secrets.get(name)`: a secret the
|
|
engine resolves when each attempt starts, redacted like any configured one,
|
|
and so is the base64 credential of the `Authorization` header it becomes.
|
|
That protection is text only: unlike a fill, it withholds no screenshot or
|
|
model pixels, so a page that renders the password on screen is not masked in
|
|
them ([Security](/security#secrets)).
|
|
|
|
`headers` and `basicAuth` are how a test reaches a [protected preview](/starting-your-app#protected-previews).
|
|
|
|
`screencast` shapes the recording, not which attempts record: that is the
|
|
config's [`video`](/reference/config#video) mode. `size` takes whole pixels,
|
|
each side at least 1, and `quality` an integer from 0 through 100; anything
|
|
else, or another key, is `INVALID_CONFIG` at config load. The old
|
|
`web({ video })` spelling is `INVALID_CONFIG` naming `screencast`.
|
|
|
|
### Recovering a CDP transport
|
|
|
|
`connect.reconnectEndpoint(signal)` opts into recovery of the same remote
|
|
browser after its CDP transport disconnects. This mode uses the browser's
|
|
persistent default context because Chrome deletes ordinary Playwright contexts
|
|
when their transport detaches.
|
|
|
|
```ts
|
|
interface WebConnectOptions {
|
|
cdpEndpoint(signal: AbortSignal): string | Promise<string>;
|
|
reconnectEndpoint?(signal: AbortSignal): string | Promise<string>;
|
|
}
|
|
```
|
|
|
|
In this mode, `cdpEndpoint` provisions a fresh, dedicated browser at every
|
|
attempt start, including retries. The engine rejects a browser reused by a
|
|
previous attempt. The remote must have only its default context, and the host
|
|
must delete the browser when the attempt ends. Engine cleanup detaches its
|
|
connection; it does not terminate the host's browser.
|
|
|
|
After a disconnect, the next operation calls `reconnectEndpoint` once, bounded
|
|
by that operation's timeout and abort signal. This resolver must return the
|
|
existing browser's endpoint. The engine verifies the persistent default context
|
|
ID and the original page's target ID. It refuses browsers that do not expose
|
|
the default context ID. A missing page or a different context fails the attempt.
|
|
A URL match is insufficient to select a replacement tab.
|
|
The engine installs secure-field masking before publishing each CDP binding;
|
|
an incompatible Playwright version fails the connection instead of exposing pixels.
|
|
Recovery also requires the original page's frames to retain their closed shadow
|
|
DOM tracking hooks. If a document loaded without that hook while disconnected,
|
|
recovery fails with `ENGINE_FAILURE`: existing closed roots cannot be recovered
|
|
without reloading the application. Mask queries reject any untracked document.
|
|
|
|
Endpoint resolution, CDP attachment, setup, and dispatch share one timeout.
|
|
Exhausting it raises `OPERATION_TIMEOUT`; caller or attempt cancellation raises
|
|
`CANCELLED`. Cancelling a concurrent waiter does not cancel the operation that
|
|
started recovery. Cancelling that recovery owner fails the shared recovery.
|
|
|
|
Recovery clears old node references. Observation-derived `tapAt` calls,
|
|
observation-root swipes, and focused engine keyboard input require a fresh
|
|
engine observation before they resume.
|
|
An observation or locator read started before recovery cannot publish references
|
|
after the connection changes. Each attempt owns its binding and recordings, so
|
|
late cleanup cannot change a later attempt.
|
|
The deterministic `browser.mouse` and `browser.keyboard` fixtures remain available
|
|
without an agent observation. Test code owns its input and can read current
|
|
geometry and focus with `browser.evaluate` before acting.
|
|
|
|
Recovery preserves the page's unsaved state, storage, the attempt's secret
|
|
taint, and the agent ledger. Operations already dispatched
|
|
are never retried. Dialog and route handlers are reattached. Video and trace
|
|
recording resume, but a segment lost during the disconnect cannot be recovered.
|
|
Code using `surfaceOf(engine)` must read its accessors again after recovery;
|
|
previously retained Playwright objects belong to the disconnected transport.
|
|
|
|
Persistent recovery does not support `headers`, `basicAuth`, `userAgent`, `locale`, `timezoneId`, `app.clearState`,
|
|
or session state capture and restore. `app.restart` remains available. Omit
|
|
`reconnectEndpoint` to keep ordinary isolated contexts and the existing behavior.
|
|
A `browser` provider with `scope: 'attempt'` rides the same persistent
|
|
context, with the same limits: the lease's `cdpEndpoint` provisions the
|
|
attempt's browser and its `reconnectEndpoint` (else `cdpEndpoint` again)
|
|
reconnects to it. A lease is fresh by the provider's contract, so the engine
|
|
does not compare its context with earlier attempts': a hosted service may
|
|
restore browsers from one snapshot, which gives new browsers the same
|
|
context id.
|
|
|
|
The attempt's first page is the browser's own first tab, navigated to
|
|
`about:blank`, rather than a second tab beside it; a page opened after that,
|
|
such as the one `app.restart` opens, is a new tab.
|
|
|
|
## The active tab
|
|
|
|
`browser` is the whole browser, showing one active tab. What reads or acts on
|
|
a page acts on that tab: `goto`, `reload`, `back`, `forward`, `url`, `title`,
|
|
`waitForURL`, `locator`, `frameLocator`, `evaluate`, `waitForResponse`,
|
|
`waitForDownload`, `keyboard`, `mouse`, the `expect(browser)` matchers, and
|
|
every `screen` query. What belongs to the browser covers every tab:
|
|
`cookies`, `setCookies`, `route`, `unroute`, `onDialog`, and `addInitScript`. `setViewport`
|
|
sizes the active tab and every tab opened after it.
|
|
|
|
A tab the app opens itself, from a `target="_blank"` link or `window.open`,
|
|
is not followed: the active tab stays the one the attempt opened, so assert
|
|
on what that tab shows, or open the link's URL with `browser.goto`.
|
|
|
|
## The browser fixture
|
|
|
|
```ts
|
|
/**
|
|
* The browser the attempt drives, showing one active tab. Navigation, reads,
|
|
* `locator`, `frameLocator`, `evaluate`, `waitForResponse`, `waitForDownload`,
|
|
* the keyboard and mouse, `expect(browser)`, and `screen` act on the active
|
|
* tab; cookies, routes, and dialog handlers cover the whole browser, every
|
|
* tab included. A tab the app opens itself (a `target="_blank"` link,
|
|
* `window.open`) is not followed: the active tab stays the one the attempt
|
|
* opened.
|
|
*/
|
|
export interface Browser extends Expectable<BrowserExpectation> {
|
|
/** Navigates to an allowed URL. */
|
|
goto(
|
|
url: string,
|
|
options?: {
|
|
waitUntil?: 'load' | 'domcontentloaded' | 'networkidle';
|
|
timeout?: number;
|
|
},
|
|
): Promise<void>;
|
|
/** Reloads the current document. */
|
|
reload(options?: ActionOptions): Promise<void>;
|
|
/** Navigates browser history back once. */
|
|
back(options?: ActionOptions): Promise<void>;
|
|
/** Navigates browser history forward once. */
|
|
forward(options?: ActionOptions): Promise<void>;
|
|
/** Returns the current URL. */
|
|
url(): Promise<string>;
|
|
/** Returns the current title. */
|
|
title(): Promise<string>;
|
|
/** Waits for the current URL to match. */
|
|
waitForURL(url: string | RegExp, options?: { timeout?: number }): Promise<void>;
|
|
/** Creates a web-only CSS or XPath locator. */
|
|
locator(selector: string): Locator;
|
|
/** Creates a screen query scope inside one iframe. */
|
|
frameLocator(selector: string): FrameScreen;
|
|
/** Evaluates trusted test code in the page: a function, or a string expression whose value is returned, called first if it is a function. */
|
|
evaluate<T extends JsonValue>(fn: string | (() => T | Promise<T>)): Promise<T>;
|
|
/** Evaluates trusted test code with one required JSON-safe argument. */
|
|
evaluate<T extends JsonValue, Arg extends JsonValue>(
|
|
fn: string | ((arg: Arg) => T | Promise<T>),
|
|
arg: Arg,
|
|
): Promise<T>;
|
|
/** Adds a script every document runs before the page's own, from the next navigation on. */
|
|
addInitScript(script: string | { path: string } | (() => unknown)): Promise<void>;
|
|
/** Adds an init script function called with one JSON argument. */
|
|
addInitScript<Arg extends JsonValue>(script: (arg: Arg) => unknown, arg: Arg): Promise<void>;
|
|
/** Adds an attempt-scoped network route. */
|
|
route(
|
|
pattern: string | RegExp,
|
|
handler: (route: WebRoute) => void | Promise<void>,
|
|
): Promise<void>;
|
|
/** Removes matching attempt-scoped routes. */
|
|
unroute(pattern: string | RegExp): Promise<void>;
|
|
/** Waits for a matching response. */
|
|
waitForResponse(
|
|
pattern: string | RegExp,
|
|
options?: { timeout?: number },
|
|
): Promise<WebResponse>;
|
|
/** Returns cookies visible to the current context. */
|
|
cookies(): Promise<Cookie[]>;
|
|
/** Sets cookies after URL validation. */
|
|
setCookies(cookies: readonly Cookie[]): Promise<void>;
|
|
/** Sets the viewport size. */
|
|
setViewport(size: { width: number; height: number }): Promise<void>;
|
|
/** Registers an attempt-scoped dialog handler and returns an unsubscribe function. */
|
|
onDialog(handler: DialogHandler): Promise<() => Promise<void>>;
|
|
/** Runs a trigger and waits for its download. */
|
|
waitForDownload(
|
|
trigger: () => Promise<void>,
|
|
options?: { timeout?: number },
|
|
): Promise<{ path: string; suggestedFilename: string }>;
|
|
/** Viewport-level keyboard, for whatever has focus. */
|
|
readonly keyboard: {
|
|
/** Sends one key. */
|
|
press(key: string): Promise<void>;
|
|
/** Types plain text. */
|
|
type(text: string): Promise<void>;
|
|
};
|
|
/**
|
|
* Direct pointer input from test code, independent of agent observations.
|
|
* After CDP recovery, test code can read current geometry with `evaluate`
|
|
* before starting a pointer sequence.
|
|
*/
|
|
readonly mouse: {
|
|
/** Moves the pointer. */
|
|
move(x: number, y: number): Promise<void>;
|
|
/** Scrolls the pointer wheel. */
|
|
wheel(deltaX: number, deltaY: number): Promise<void>;
|
|
/** Presses the primary pointer button. */
|
|
down(): Promise<void>;
|
|
/** Releases the primary pointer button. */
|
|
up(): Promise<void>;
|
|
};
|
|
}
|
|
```
|
|
|
|
| Member | Default timeout |
|
|
| --- | --- |
|
|
| `goto`, `reload`, `back`, `forward` | `config.timeout`, 120000 ms, the same budget `app.open()` uses; `{ timeout }` overrides, capped by the test deadline |
|
|
| `waitForResponse`, `waitForDownload` | `config.actionTimeout`, 30000 ms; `{ timeout }` overrides, capped by the test deadline |
|
|
| `waitForURL` | `config.assertionTimeout`, 5000 ms |
|
|
| `url`, `title`, `evaluate`, `addInitScript`, `route`, `unroute`, `cookies`, `setCookies`, `setViewport`, `onDialog`, `keyboard.*`, `mouse.*` | `config.actionTimeout`, 30000 ms, not overridable |
|
|
|
|
Every `browser` call is a recorded `browser.<method>` step, except `locator` and
|
|
`frameLocator`: they build a locator without touching the page, and the
|
|
action or assertion on it is the step. A relative URL resolves against the
|
|
target's `app.url`, else `APP_URL_REQUIRED`. Declare `requires: ['browser']`
|
|
in a suite that also runs on other platforms.
|
|
|
|
### Navigation
|
|
|
|
`goto` defaults `waitUntil` to `'load'` and throws `POLICY_DENIED` for a
|
|
URL whose scheme is not `http:` or `https:` (`about:blank` is admitted). `waitForURL` polls every 100 ms; a
|
|
relative string resolves against the base URL and matches exactly after
|
|
normalization, a `RegExp` tests the full URL, anything else (a predicate
|
|
function, say) is `INVALID_ARGUMENT`, and a timeout is `ASSERTION_FAILED`. It
|
|
takes `timeout` only: another key, such as Playwright's `waitUntil`, is
|
|
`INVALID_ARGUMENT`. The other navigations throw `ACTION_FAILED`.
|
|
|
|
```ts
|
|
await browser.goto('/dashboard', { waitUntil: 'networkidle' });
|
|
await browser.waitForURL(/\/orders\/\d+$/, { timeout: 15_000 });
|
|
```
|
|
|
|
### Locators and frames
|
|
|
|
`locator` and `frameLocator`, at the page or inside a frame, throw
|
|
`INVALID_LOCATOR` for an empty selector. `frameLocator` throws
|
|
`LOCATOR_NOT_FOUND` for a missing frame and `LOCATOR_AMBIGUOUS` for several.
|
|
The selector is a Playwright selector: CSS by default, XPath with `xpath=` or
|
|
a leading `//`, and `>>` chains, so
|
|
`browser.locator('[data-testid="row"] >> nth=2 >> [data-testid="conditions"] > div')`
|
|
scopes CSS to one row. A `*` capture before the last part
|
|
(`*css=article >> text=Hello`) is `INVALID_LOCATOR`: use
|
|
`filter({ has })` for an element that contains another.
|
|
|
|
```ts
|
|
const payment = browser.frameLocator('#payment-frame');
|
|
await payment.getByLabel('Card number').fill('4242424242424242');
|
|
```
|
|
|
|
`frameLocator` returns a `FrameScreen`: a `Screen` whose queries answer from
|
|
inside the frame, plus the two web-only escape hatches scoped to it.
|
|
|
|
```ts
|
|
export interface FrameScreen extends Screen {
|
|
/** Creates a web-only CSS or XPath locator inside this frame. */
|
|
locator(selector: string): Locator;
|
|
/** Creates a screen query scope inside an iframe nested in this frame. */
|
|
frameLocator(selector: string): FrameScreen;
|
|
}
|
|
```
|
|
|
|
Reach for the frame's `locator` only when the control has no accessible
|
|
name, label, placeholder, or test id; the [browser guide](/browser#reach-into-an-iframe)
|
|
shows when that applies.
|
|
|
|
Every `screen` query searches its scope and each closed shadow root the page
|
|
attached under it, with Playwright's own role, name, text, label, and
|
|
attribute matching and each node found once, so a control the observed tree
|
|
lists inside a closed root resolves and takes actions and reads. `locator`,
|
|
`frameLocator`, and `filter({ hasText })` keep Playwright's reach and stop at
|
|
a closed root; the [browser guide](/browser#shadow-dom) has the details.
|
|
|
|
### evaluate
|
|
|
|
The function runs in the page and cannot access variables from the test.
|
|
It is serialized by its source and inlined into the page, so it must not
|
|
close over anything outside its own body; helpers declared inside the body
|
|
work. Pass outside values through `arg`. Both `arg` and the return value
|
|
must be `JsonValue`, otherwise the call fails with `INVALID_ARGUMENT`.
|
|
|
|
A string is evaluated as a single expression, not as statements. If it
|
|
evaluates to a function, that function is called with `arg`; otherwise its
|
|
value is the result. A promise, from either, is awaited.
|
|
|
|
An exception in the evaluated code is `EVALUATE_FAILED` with its message. A
|
|
Playwright timeout is `ACTION_FAILED`; a closed page or lost context is
|
|
`ENGINE_FAILURE`.
|
|
|
|
```ts
|
|
const count = await browser.evaluate(() => document.querySelectorAll('li').length);
|
|
const flag = await browser.evaluate(
|
|
(name: string) => window.localStorage.getItem(name),
|
|
'featureFlags',
|
|
);
|
|
const title = await browser.evaluate<string>('document.title');
|
|
```
|
|
|
|
### Init scripts
|
|
|
|
An init script runs in every document before the page's own scripts, in every
|
|
tab and frame. `web({ initScripts })` applies to every test;
|
|
`browser.addInitScript` adds one for the rest of the test.
|
|
|
|
A script is JavaScript source, a `{ path }` relative to the project root, or a
|
|
function. A function cannot close over test variables; pass a JSON `arg`
|
|
instead.
|
|
|
|
```ts
|
|
await browser.addInitScript((value) => { Math.random = () => value; }, 0.5);
|
|
await app.open('/raffle');
|
|
```
|
|
|
|
A script added after the page opened runs from the next navigation or reload.
|
|
|
|
### Routing
|
|
|
|
`route`, `unroute`, and `waitForResponse` take a string pattern (`*` within a
|
|
path segment, `**` across `/`) or a `RegExp`, both tested against the full
|
|
URL; a predicate function is `INVALID_ARGUMENT`. A route survives
|
|
`app.restart()`, `app.clearState()`, and session restore.
|
|
The handler must decide exactly once with `fulfill`, `continue`, `fallback`,
|
|
or `abort`; deciding twice or not at all is `ACTION_FAILED`. Routes run newest
|
|
first. `continue` sends the request to the network and no other route sees
|
|
it; its `url` resolves against the base URL and goes through the same rule as
|
|
`goto`, so a forbidden scheme is `POLICY_DENIED`, and it must keep the
|
|
request's scheme. `headers` replaces every request header. The configured
|
|
`headers` still ride a continued request bound for the app's site, and only
|
|
that site. `fallback` hands the request to the route registered before this
|
|
one, or the network when none matches. `fulfill` takes one of `json`, `body`,
|
|
or `path`, a file relative to the project root whose extension sets the
|
|
`Content-Type` unless `contentType` or a `content-type` header does. An option
|
|
a decision does not take (Playwright's `abort(errorCode)`, a misspelled key) is
|
|
`INVALID_ARGUMENT`: the request is aborted and the next step fails.
|
|
|
|
A `waitForResponse` that nothing matches inside the deadline is
|
|
`ACTION_FAILED`. The deadline bounds the match: the response resolves as soon
|
|
as its headers arrive, and `text()` and `json()` wait for the body on a budget
|
|
of their own, `config.actionTimeout` capped by the test deadline; a body still
|
|
streaming when it runs out is `ACTION_FAILED`. `url`, `status`, and `headers`
|
|
are always readable, and a body the
|
|
browser could not read (a connection reset short of the declared
|
|
`Content-Length`, a request the page aborted, or a redirect, whose body the
|
|
browser never keeps) rejects `text()` and `json()` with `ACTION_FAILED`
|
|
instead of an empty string. A genuinely empty body reads as `''`. A handler
|
|
that throws (a failed `expect` on the request, say) fails the next step with
|
|
that error, or the attempt at its end when no step follows; a handler still
|
|
running then gets the cleanup budget to finish. One that outlives the budget
|
|
fails the attempt with `CLEANUP_TIMEOUT`, and whatever it throws afterwards is
|
|
dropped.
|
|
|
|
```ts
|
|
await browser.route('**/api/quote', async (route) => {
|
|
await route.fulfill({ json: { cents: 4200 } });
|
|
});
|
|
|
|
const response = await browser.waitForResponse('**/api/orders');
|
|
expect(response.status).toBe(201);
|
|
```
|
|
|
|
```ts
|
|
/**
|
|
* One of `json`, `body`, or `path`, or none for an empty body. `path` names a
|
|
* file relative to the project root; its `Content-Type` follows its
|
|
* extension unless `contentType` or a `content-type` header sets one.
|
|
*/
|
|
export type RouteFulfillResponse = {
|
|
status?: number;
|
|
headers?: Record<string, string>;
|
|
/** Sets the `Content-Type` response header. */
|
|
contentType?: string;
|
|
} & (
|
|
| { json: JsonValue; body?: never; path?: never }
|
|
| { body: string; json?: never; path?: never }
|
|
| { path: string; json?: never; body?: never }
|
|
| { body?: never; json?: never; path?: never }
|
|
);
|
|
|
|
/** What `continue` changes about the request before it goes to the network. */
|
|
export interface RouteContinueOverrides {
|
|
/** Resolved against the base URL like `goto`; must keep the request's scheme. */
|
|
url?: string;
|
|
/** Request method. */
|
|
method?: string;
|
|
/** Replaces every request header; the configured `headers` for the app's site are added on top. */
|
|
headers?: Record<string, string>;
|
|
/** Request body. */
|
|
postData?: string;
|
|
}
|
|
|
|
export interface WebRoute {
|
|
/** The intercepted request. */
|
|
readonly request: {
|
|
readonly url: string;
|
|
readonly method: string;
|
|
readonly headers: Readonly<Record<string, string>>;
|
|
readonly postData?: string;
|
|
};
|
|
/** Fulfills the intercepted request once. */
|
|
fulfill(response: RouteFulfillResponse): Promise<void>;
|
|
/** Sends the intercepted request to the network once, skipping every other route. */
|
|
continue(overrides?: RouteContinueOverrides): Promise<void>;
|
|
/** Hands the intercepted request to the route registered before this one, or the network when none matches. */
|
|
fallback(): Promise<void>;
|
|
/** Aborts the intercepted request once. */
|
|
abort(): Promise<void>;
|
|
}
|
|
|
|
export interface WebResponse {
|
|
/** Response URL. */
|
|
readonly url: string;
|
|
/** HTTP status. */
|
|
readonly status: number;
|
|
/** Response headers, lower-cased names. */
|
|
readonly headers: Readonly<Record<string, string>>;
|
|
/** Waits for the body and parses it as JSON. */
|
|
json<T = unknown>(): Promise<T>;
|
|
/** Waits for the body and reads it as text. */
|
|
text(): Promise<string>;
|
|
}
|
|
```
|
|
|
|
### Cookies and viewport
|
|
|
|
`setCookies` validates every cookie before setting any; an unparseable
|
|
target or a forbidden scheme is `POLICY_DENIED` and nothing is set. A
|
|
relative `url` resolves against the base URL, as `goto` resolves it. For the
|
|
`domain` form the scheme follows the base URL and a leading `.` is stripped.
|
|
`setViewport` records the new size on the report. It works before the first
|
|
navigation too, as Playwright's `setViewportSize` does: the next `app.open`
|
|
loads at that size, so a phone-sized test never renders the desktop layout first.
|
|
The size holds for the rest of the attempt, through `app.restart()` and
|
|
`app.clearState()`.
|
|
|
|
```ts
|
|
export interface CookieFields {
|
|
/** Cookie name. */
|
|
name: string;
|
|
/** Cookie value. */
|
|
value: string;
|
|
/** Unix timestamp in whole seconds. */
|
|
expires?: number;
|
|
/** HttpOnly flag. */
|
|
httpOnly?: boolean;
|
|
/** Secure flag. */
|
|
secure?: boolean;
|
|
/** SameSite attribute. */
|
|
sameSite?: 'Strict' | 'Lax' | 'None';
|
|
}
|
|
|
|
/** `url`, or `domain` with an optional `path`, never both. */
|
|
export type Cookie = CookieFields &
|
|
(
|
|
| { url: string; domain?: never; path?: never }
|
|
| { url?: never; domain: string; path?: string }
|
|
);
|
|
```
|
|
|
|
```ts
|
|
await browser.setCookies([{ url: 'http://localhost:3000', name: 'tz', value: 'UTC' }]);
|
|
```
|
|
|
|
### Dialogs and downloads
|
|
|
|
A function handler must call `accept` or `dismiss`; one that does neither
|
|
has the dialog dismissed and fails the next step with `APP_NOT_OPEN`, as an
|
|
unhandled dialog does. One that throws fails the next step, or the attempt at
|
|
its end when no step follows, with its error: a failed `expect` stays
|
|
`ASSERTION_FAILED`, an unclassified throw is `ENGINE_FAILURE`.
|
|
`waitForDownload` registers the file as a `download`
|
|
artifact and throws `ACTION_FAILED` when it does not complete in time. A
|
|
trigger that resolves in time but starts no download fails with
|
|
`no download started within <n>ms; the trigger resolved after <m>ms`, where
|
|
the wait includes the trigger's own time. A trigger still running at the
|
|
timeout fails with the step timeout, and one that throws with its own error.
|
|
On a hosted browser the file comes back through the provider's
|
|
[`downloads`](/browser#downloads-on-the-provider).
|
|
|
|
```ts
|
|
/** A native dialog as a test's handler sees it. */
|
|
export interface Dialog {
|
|
/** The dialog's text. */
|
|
readonly message: string;
|
|
/** Accepts the dialog once. */
|
|
accept(text?: string): Promise<void>;
|
|
/** Dismisses the dialog once. */
|
|
dismiss(): Promise<void>;
|
|
}
|
|
```
|
|
|
|
```ts
|
|
const off = await browser.onDialog('accept');
|
|
await screen.getByRole('button', 'Delete').tap();
|
|
await off();
|
|
|
|
const file = await browser.waitForDownload(() =>
|
|
screen.getByRole('link', 'Export CSV').tap(),
|
|
);
|
|
```
|
|
|
|
### keyboard and mouse
|
|
|
|
Both namespaces are viewport-level. Prefer `locator.press` and
|
|
`locator.fill` when a target exists. `keyboard.type` takes plain text only,
|
|
never a `Secret`.
|
|
|
|
### JsonValue
|
|
|
|
```ts
|
|
/** A JSON scalar. */
|
|
export type JsonPrimitive = string | number | boolean | null;
|
|
|
|
/** Data that survives JSON serialization. */
|
|
export type JsonValue =
|
|
| JsonPrimitive
|
|
| { readonly [key: string]: JsonValue }
|
|
| readonly JsonValue[];
|
|
```
|
|
|
|
## Semantic capture recovery
|
|
|
|
When the semantic reader times out, agent observations can recover using a
|
|
fresh viewport screenshot. Playwright runs a new secure-field mask sweep
|
|
across every reachable frame, including open and closed shadow roots. Every
|
|
mask probe must succeed. The observation explicitly reports unavailable
|
|
semantics and clears earlier node references.
|
|
|
|
Recovery requires time left in the operation budget and permission from the
|
|
runner. `act` permits it before a secret fill; judgments also require
|
|
`vision: true` or `'only'`. Failed masking, cancellation, and hard engine
|
|
errors still stop the observation.
|
|
|
|
When fallback is permitted, the reader reserves one quarter of the remaining
|
|
observation budget, capped at two seconds, for the screenshot. The deadline
|
|
covers the page walk, metadata and element readback, and nested frames.
|
|
Semantic metadata crosses the Playwright connection as one JSON string to
|
|
reduce serialization overhead. Actions still use the live element handles
|
|
captured with that metadata. Pages that replace `JSON.stringify` or add
|
|
`toJSON` methods to object or array prototypes use structured transfer.
|
|
Cleanup does not wait for stalled protocol replies. An abandoned reader
|
|
cannot reuse node IDs or publish handles over a newer observation.
|
|
|
|
## Exported types
|
|
|
|
`WebOptions`, `WebScreencastOptions`, `WebConnectOptions`, `WebBasicAuth`, `BrowserName`,
|
|
`BrowserProvider`, `BrowserProviderScope`, `BrowserRequest`, `BrowserLease`,
|
|
`BrowserReleaseContext`, `BrowserProviderDownloads`, `BrowserDownloadContext`,
|
|
`PlaywrightLiveSurface`, `Browser`, `FrameScreen`,
|
|
`BrowserExpectation`, `WebRoute`, `RouteFulfillResponse`, `RouteContinueOverrides`, `WebResponse`,
|
|
`Cookie`, `CookieFields`, `Dialog`, and `DialogHandler` are exported from the
|
|
package for typing config helpers and fixtures. The runtime exports are
|
|
`web`, [`surfaceOf`](#surfaceof), and `test`, `describe`, `beforeEach`,
|
|
`afterEach`, `beforeAll`, and `afterAll`, typed with the `browser` fixture.
|
|
|
|
## expect(browser)
|
|
|
|
`expect(browser)` returns the `BrowserExpectation` the engine attaches: `toHaveURL`,
|
|
`toHaveTitle`, and `toHaveClass`. See [browser matchers](/reference/expect#browser-matchers).
|
|
|
|
## surfaceOf
|
|
|
|
```ts
|
|
import { web, surfaceOf } from '@e2e-dev/web';
|
|
|
|
const engine = web();
|
|
const live = surfaceOf(engine); // PlaywrightLiveSurface | undefined
|
|
live!.page(); // the Page of the current attempt
|
|
live!.context(); // its BrowserContext
|
|
```
|
|
|
|
Use `surfaceOf(handle)` in a [custom executor](/executors#driving-the-page-yourself)
|
|
to access the current Playwright page and context directly. It returns
|
|
`undefined` for a handle from another package. The accessors throw
|
|
`INVALID_STATE` outside an active attempt. Direct Playwright calls are not
|
|
recorded as steps.
|