mirror of
https://github.com/tester-army/e2e.git
synced 2026-11-25 02:24:26 +08:00
381 lines
13 KiB
Plaintext
381 lines
13 KiB
Plaintext
---
|
|
title: Playwright
|
|
description: The browser engine, its options, and the web fixture it contributes.
|
|
---
|
|
|
|
`@e2edev/playwright` drives Chromium, Firefox, and WebKit through Playwright.
|
|
A web target names it as its engine, and it contributes the `web` fixture for
|
|
browser-only work. Import `test` from the package to have `web` typed.
|
|
|
|
The package declares `playwright` as a peer dependency (`>=1.63.0 <2`) and
|
|
does not install it. An app that already depends on Playwright keeps its
|
|
version; `e2e init` adds `playwright` only to a project that has none.
|
|
|
|
```ts title="e2e.config.ts"
|
|
import type { E2EConfig } from 'e2e';
|
|
import { playwright } from '@e2edev/playwright';
|
|
|
|
export default {
|
|
targets: [{ engine: playwright({ url: 'http://localhost:3000' }) }],
|
|
} satisfies E2EConfig;
|
|
```
|
|
|
|
## Options
|
|
|
|
```ts
|
|
/**
|
|
* Options of the browser engine: the app it drives (`url`, `command`,
|
|
* `services`, `environment`, `identity`, `readyUrl` - the
|
|
* engine contract's app declaration) plus the browser itself.
|
|
*/
|
|
export interface PlaywrightOptions extends EngineAppDeclaration {
|
|
/** Browser to launch; defaults to chromium. */
|
|
readonly browser?: BrowserName;
|
|
/** Initial viewport of every attempt's page; default 1280 by 720. */
|
|
readonly viewport?: { readonly width: number; readonly height: number };
|
|
/**
|
|
* 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?: PlaywrightConnectOptions;
|
|
/**
|
|
* HTTP headers added to every request the browser sends to an allowed
|
|
* origin: a preview-protection bypass token, a tunnel's interstitial skip.
|
|
* Requests to any other origin (a CDN, an analytics endpoint, an identity
|
|
* provider) never carry them, so a header that is a secret stays with the
|
|
* app it unlocks. Names are case-insensitive; a header the page already
|
|
* sends under the same name is replaced. Applies to every path onto the
|
|
* page, deterministic and agent-driven alike. Injecting headers routes
|
|
* every request of the attempt, which turns the browser's HTTP cache off
|
|
* and blocks service workers (a worker's requests bypass routing, so a
|
|
* page it controlled would reach the gate bare), and a Playwright trace
|
|
* records request headers.
|
|
*/
|
|
readonly headers?: Readonly<Record<string, string>>;
|
|
/**
|
|
* HTTP basic authentication for a staging app behind a browser challenge.
|
|
* The browser answers a `401` with these credentials wherever one is
|
|
* issued, as Playwright's own `httpCredentials` does. Applies to every path
|
|
* onto the page.
|
|
*/
|
|
readonly basicAuth?: PlaywrightBasicAuth;
|
|
/**
|
|
* 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 app declaration fields (`url`, `command`, `readyUrl`, `services`,
|
|
`environment`, `identity`) are documented under
|
|
[the app under test](/reference/config#the-app-under-test). `connect` needs
|
|
chromium; `cdpEndpoint(signal)` is called once per worker and again when a
|
|
session drops. `:` is not allowed in the `basicAuth` user name.
|
|
|
|
`headers` and `basicAuth` are how a test reaches a [protected preview](/starting-your-app#protected-previews).
|
|
|
|
## Web
|
|
|
|
```ts
|
|
export interface Web extends Expectable<WebExpectation> {
|
|
/** 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): Screen;
|
|
/** Evaluates trusted test code in the page. */
|
|
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 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>;
|
|
};
|
|
/** Viewport-level pointer. */
|
|
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`, `route`, `unroute`, `cookies`, `setCookies`, `setViewport`, `onDialog`, `keyboard.*`, `mouse.*` | `config.actionTimeout`, 30000 ms, not overridable |
|
|
|
|
Every `web` call is a recorded `web.<method>` step. A relative URL needs the
|
|
engine's declared `url`, else `APP_URL_REQUIRED`. Declare `requires: ['web']`
|
|
in a suite that also runs on other platforms.
|
|
|
|
### Navigation
|
|
|
|
`goto` defaults `waitUntil` to `'load'` and throws `POLICY_DENIED` for a
|
|
`file:`, `data:`, or `javascript:` URL. `waitForURL` polls every 100 ms; a
|
|
relative string resolves against the base URL and matches exactly after
|
|
normalization, a `RegExp` tests the full URL, and a timeout is
|
|
`ASSERTION_FAILED`. The other navigations throw `ACTION_FAILED`.
|
|
|
|
```ts
|
|
await web.goto('/dashboard', { waitUntil: 'networkidle' });
|
|
await web.waitForURL(/\/orders\/\d+$/, { timeout: 15_000 });
|
|
```
|
|
|
|
### Locators and frames
|
|
|
|
`locator` throws `INVALID_LOCATOR` for an empty selector. `frameLocator`
|
|
throws `LOCATOR_NOT_FOUND` for a missing frame and `LOCATOR_AMBIGUOUS` for
|
|
several.
|
|
|
|
```ts
|
|
const payment = web.frameLocator('#payment-frame');
|
|
await payment.getByLabel('Card number').fill('4242424242424242');
|
|
```
|
|
|
|
### evaluate
|
|
|
|
The function is serialized and run in the page, so it cannot close over
|
|
test-scope variables; pass data through `arg`. Both `arg` and the return
|
|
value must be `JsonValue`, else `INVALID_ARGUMENT`.
|
|
|
|
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 web.evaluate(() => document.querySelectorAll('li').length);
|
|
const flag = await web.evaluate(
|
|
(name: string) => window.localStorage.getItem(name),
|
|
'featureFlags',
|
|
);
|
|
```
|
|
|
|
### Routing
|
|
|
|
A route survives `app.restart()`, `app.clearState()`, and session restore.
|
|
The handler must decide exactly once with `fulfill`, `continue`, or `abort`;
|
|
deciding twice or not at all is `ACTION_FAILED`, as is a `waitForResponse`
|
|
that nothing matches inside the deadline.
|
|
|
|
```ts
|
|
await web.route('**/api/quote', async (route) => {
|
|
await route.fulfill({ json: { cents: 4200 } });
|
|
});
|
|
|
|
const response = await web.waitForResponse('**/api/orders');
|
|
expect(response.status).toBe(201);
|
|
```
|
|
|
|
```ts
|
|
/** `json` or `body`, never both; neither fulfills with an empty body. */
|
|
export type RouteFulfillResponse = {
|
|
status?: number;
|
|
headers?: Record<string, string>;
|
|
} & (
|
|
| { json: JsonValue; body?: never }
|
|
| { body: string; json?: never }
|
|
| { body?: never; json?: never }
|
|
);
|
|
|
|
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>;
|
|
/** Continues the intercepted request once. */
|
|
continue(): 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>>;
|
|
/** Parses the response body as JSON. */
|
|
json<T = unknown>(): Promise<T>;
|
|
/** Reads the response body 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. For the
|
|
`domain` form the scheme follows the base URL and a leading `.` is stripped.
|
|
`setViewport` records the new size on the report.
|
|
|
|
```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 web.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. `waitForDownload` registers the file as a `download`
|
|
artifact and throws `ACTION_FAILED` when it does not complete in time.
|
|
|
|
```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 web.onDialog('accept');
|
|
await screen.getByRole('button', { name: 'Delete' }).tap();
|
|
await off();
|
|
|
|
const file = await web.waitForDownload(() =>
|
|
screen.getByRole('link', { name: '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[];
|
|
```
|
|
|
|
## Exported types
|
|
|
|
`PlaywrightOptions`, `PlaywrightConnectOptions`, `PlaywrightBasicAuth`,
|
|
`BrowserName`, `PlaywrightLiveSurface`, `Web`, `WebExpectation`, `WebRoute`,
|
|
`WebResponse`, `Cookie`, `Dialog`, and `DialogHandler` are exported from the
|
|
package for typing config helpers and fixtures.
|
|
|
|
## expect(web)
|
|
|
|
`expect(web)` returns the `WebExpectation` the engine attaches: `toHaveURL`,
|
|
`toHaveTitle`, and `toHaveClass`. See [web matchers](/reference/expect#web-matchers).
|
|
|
|
## surfaceOf
|
|
|
|
```ts
|
|
import { playwright, surfaceOf } from '@e2edev/playwright';
|
|
|
|
const engine = playwright({ url: 'http://localhost:3000' });
|
|
const live = surfaceOf(engine); // PlaywrightLiveSurface | undefined
|
|
live!.page(); // the Page of the current attempt
|
|
live!.context(); // its BrowserContext
|
|
```
|
|
|
|
`surfaceOf(handle)` returns the `PlaywrightLiveSurface` behind a handle this
|
|
package created, or `undefined`. Both accessors throw `INVALID_STATE` before
|
|
an attempt is running. It exists for a
|
|
[custom executor](/executors#driving-the-page-yourself) that brings its own
|
|
browser tooling; what it does there is not recorded as steps.
|