test
Tests, setup tests, groups, hooks, options, and fixtures.
test declares tests, setup tests, groups, and hooks. Declarations run
synchronously while the test file is imported. Use test.extend to add
fixtures and test.skip to skip a test at registration or during its body.
import { beforeEach, describe, expect, test } from 'e2e';
describe('checkout', { tags: ['billing'] }, () => {
beforeEach(async ({ app }) => {
await app.open('/checkout');
});
test('pays with a saved card', { retries: 2 }, async ({ screen }) => {
await screen.getByRole('button', 'Pay').tap();
await expect(screen.getByText('Payment received')).toBeVisible();
});
});Reference
Members
describe and the four hooks are also top-level exports, the same functions
as test.describe, test.beforeEach, and the rest:
import { describe, beforeEach, test } from 'e2e'.
- A per-test hook imported from
e2eis typed with the core fixtures. @e2e-dev/weband@e2e-dev/mobileexporttest,describe, and all four hooks typed with theirbrowserordevicefixture, so a test file registers from one import.- A
testyou extended with your own fixtures registers hooks that see them throughtest.beforeEach.
Registering a test, group, or hook outside module evaluation throws
COLLECTION_ERROR. The full declarations are under Types.
test
Registers one test, with or without options.
import { describe, test } from '@e2e-dev/web';
import { expect } from 'e2e';
test('app opens', async ({ app, browser }) => {
await app.open();
await expect(browser).toHaveURL('/');
});
test('checks out', { tags: ['billing'], retries: 2, timeout: 60_000 }, async ({ app }) => {
await app.open('/checkout');
});A test or group title is 1 through 512 UTF-8 bytes after NFC normalization, with no NUL character.
test.skip
Registers a skipped test, or skips the running test.
test.skip('exports a PDF', async ({ app }) => {}); // at registration
test.skip(organizations.length < 2, 'a single organization'); // inside a body
test.skip('not on this tenant'); // inside a body, always- A skipped test does not affect the exit code by default.
- To skip at collection by option, use the
skipoption. - At registration it returns a
TestCase; inside a body,void.
Call test.skip(condition, reason) inside a test for a condition you learn
at runtime, such as a disabled feature flag:
test('switches organizations', { session: 'admin' }, async ({ app, agent }) => {
const organizations = await listOrganizations();
test.skip(organizations.length < 2, 'the demo tenant has a single organization');
await app.open('/backend');
await agent.act(`switch to the organization "${organizations[1].name}"`);
});- When the condition is true, the call throws, as Playwright’s does. Nothing after the call runs.
- With no failure before it, the test is reported
skippedwithreason, with no retry. - Steps before it stay in the report as they ran.
- A failed
expect.softbefore the call still fails the attempt, as in Playwright. The attempt isfailed, with the soft failures as its error and the skip reason in itsskip. It retries like any failure. - Hooks and fixtures still run their teardown.
- When the condition is a precondition, call it first, before any step.
- A failed attempt followed by a skip on retry leaves the test
skipped. The CLI lists it underSkipped After Failurewith its original error. SetfailOnSkippedFailure: trueto fail the run with exit code 1 in that case. The default isfalse.
test.fail
Registers a test that is expected to fail, or marks the running test.
test.fail('shows the cart badge', async ({ app, screen }) => {}); // at registration
test.fail(platform === 'web', 'tap on a display: contents element'); // inside a body
test.fail('known gap'); // inside a body, always
test('exports a PDF', { fail: 'PDF export is broken' }, async ({ app }) => {}); // by option- The body keeps running after the call. A
beforeEachhook can mark the test too. - A failed assertion, action, thrown error, or timeout makes the test
passed. The report keeps the reason and the error. - A pass makes the test
failedwithUNEXPECTED_PASS. Remove the mark once the cause is fixed. - Infrastructure errors, interrupts, a failed
beforeAllorafterAll, and API misuse such asINVALID_ARGUMENTstill fail the test. - An expected failure is not retried. An unexpected pass is.
- A skip wins over the mark.
test.only
Registers one focused local test.
test.only('pays', async ({ app }) => {
await app.open('/checkout');
});Other tests are reported as filtered. A CI run with a focused test fails
with ONLY_IN_CI.
test.setup
Registers a setup test that declares the sessions it saves, and must save each exactly once.
import { credentials } from 'e2e';
test.setup('authenticate', { sessions: ['member'] }, async ({ app, screen, session }) => {
await app.open('/login');
await screen.getByLabel('Email').fill(credentials.user('member').username);
await screen.getByLabel('Password').fill(credentials.user('member').password);
await screen.getByRole('button', 'Sign in').tap();
await session.save('member');
});test.setupmust be top-level, not insidedescribe.- The
sessionsoption declares the names. - A test consumes a saved session with the
sessionoption. - The setup body gets one extra fixture,
session:
export interface SetupSession {
/** Saves state under a setup-declared name. */
save(name: string): Promise<void>;
}test.extend
Returns a new test typed with more fixtures. The one it was called on is
unchanged.
import { test as base } from 'e2e';
import type { Device } from '@e2e-dev/mobile';
export const test = base.extend<{ device: Device }>(); // types only- With no argument,
extendrefines only the types: it returns the same runtimetest, typed with an engine’s contributed fixtures. They still resolve from the target’s engine at runtime. This types a device, desktop, or web surface without a globaldeclare moduleaugmentation. - With definitions, it adds fixtures of your own. See Your own fixtures.
describe
Declares a group of tests, with or without options.
import { describe, test } from 'e2e';
describe('checkout', { tags: ['smoke'], serial: true }, () => {
test('adds an item', async ({ screen }) => {});
test('pays', async ({ screen }) => {});
});Hooks
Hook order follows scope nesting, not position in the file, so a hook declared after a test still applies to it.
beforeEach
Registers a test-attempt setup hook.
test.beforeEach(async ({ app }) => {
await app.open('/');
});- Runs outermost group first, then in declaration order within a group.
beforeEachand the body share the test timeout.- Receives the test fixtures.
afterEach
Registers a test-attempt teardown hook.
test.afterEach(async ({ app }) => {
await app.screenshot('after');
});- Runs innermost group first, in reverse declaration order, after a failure or timeout too.
- Each
afterEachhook gets its owncleanupTimeoutbudget with working fixtures, so teardown can still drive the app after the body timed out. - Receives the test fixtures.
beforeAll
Registers a suite-instance setup hook. It runs once per suite instance, on first entry into the scope.
beforeAll(async ({ platform }) => {
await seedDatabase(platform);
});The module is re-imported for every retry, serial group, and setup test, so
beforeAll runs again in each. Its only fixture is platform.
afterAll
Registers a suite-instance teardown hook. It runs as soon as the scope’s last test in the realm is done.
afterAll(async () => {
await resetDatabase();
});A realm that a failure discards runs afterAll for every scope whose
beforeAll started. Its only fixture is platform. A throw is HOOK_FAILED,
as for beforeAll.
Blocked event loop
A test that blocks its worker’s event loop (while (true) {} in a fixture,
beforeEach, the body, or afterEach) stops every timer in that worker, so
the worker cannot time it out.
- When the worker has not responded
cleanupTimeout(at least 5 s) after the test timeout, the runner kills it. - That attempt is reported
timed-outwithTEST_TIMEOUTand no artifacts, after the attempts before it, and is not retried. - The rest of its file runs on a new worker. In a serial group, the members after it are skipped.
- A
beforeAllorafterAllthat blocks still hangs the run.
A worker with a debugger attached when the test starts (an editor’s
auto-attach, or NODE_OPTIONS=--inspect=0) is never killed this way, so a
breakpoint can stay paused. A programmatic run with an inline config or
in-memory tests runs in the runner’s own process and has no worker to kill: a
blocked event loop hangs it.
Options
test takes every option but serial and sessions. describe takes
every option but only, fail, and sessions. test.setup requires
sessions and takes no session, only, skip, or fail.
Resolution order: test, nearest group, outer groups, config, built-in
default. Inside a serial group, the group’s retries, trace, and
video apply.
timeout
The attempt deadline in milliseconds. Innermost wins.
test('imports a large file', { timeout: 300_000 }, async ({ app }) => {}); // default: config.timeouttimeout must be a positive safe integer.
retries
How many times a failed test is retried.
test('checks out', { retries: 2 }, async ({ app }) => {}); // default: config.retriesAn integer from 0 through 10.
tags
Tags that --tag selects on. Every layer’s tags are unioned.
describe('checkout', { tags: ['billing', 'smoke'] }, () => {});Tags are distinct names, none blank, with no comma and no leading or trailing whitespace.
skip
Skips the test at collection. A string is the reason. Any truthy layer skips.
test('exports a PDF', { skip: 'PDF export is off on staging' }, async ({ app }) => {});fail
Expects the test to fail; see test.fail. A string is the
reason. Not allowed inside a serial group.
test('exports a PDF', { fail: 'PDF export is broken' }, async ({ app }) => {});only
Focuses the test locally. CI rejects it with ONLY_IN_CI.
test('pays', { only: true }, async ({ app }) => {});platforms
Platforms the test runs on. Other targets skip it. Innermost wins.
test('uses Face ID', { platforms: ['ios'] }, async ({ app }) => {});requires
Capabilities the target must have. A target that lacks one skips the test at selection. Innermost wins.
test('onboarding asks for the camera', { requires: ['native-app'] }, async ({ app, agent }) => {
await app.open();
await agent.assert('The app asks for camera access');
});Accepted values:
- The harness capabilities of the target’s engine:
observation,actions,location,pointer,keyboard,state,artifacts. - One per contributed fixture:
browser,device. See the engine contract. - The kind of app the target declares:
browserfor anapp.url,native-appfor anapp.bundleIdorapp.appPath.
session
The session a setup test saved, restored before the body runs.
test('sees the dashboard', { session: 'member' }, async ({ app }) => {});See test.setup.
agentContext
Extra context for agent steps. Layers are concatenated outermost first.
describe('pricing', { agentContext: 'Prices are shown in EUR.' }, () => {});agent
The configured agent (agents.<name>) this test or group runs with, in
place of the run’s agents.
test('checks out', { agent: ['fast', 'smart'] }, async ({ agent }) => {}); // one result per agent- A list runs the test once per agent named, as one result each.
- Innermost wins. A call’s own
agentoption wins over it. --agentnarrows a list to the names both name, and never overrides a pin the flag does not name.- A setup test runs once per target, so it pins at most one agent.
trace
Whether the test keeps a trace page, in place of the run’s.
test('checkout', { trace: 'retain-on-failure' }, async ({ agent }) => {});- Takes a recording mode, the same as the
config’s
trace:off,on,retain-on-failure,on-first-retry, oron-all-retries. - A test’s or group’s own value wins over
--trace, the target’s, and the config’s. One test can record on a run that records nothing, or opt out of one that records everything.
video
Which of the test’s attempts record a video, in place of the run’s.
test('checkout', { video: 'on' }, async ({ agent }) => {
await agent.act('Buy the first product in the catalog');
});- Takes the same recording modes as
traceand the config’svideo. - A test’s or group’s own value wins over
--video, the target’s, and the config’s.
serial
describe only. Runs the group as one ordered retry unit with shared app
state.
describe('checkout', { serial: true }, () => {
test('adds an item', async ({ screen }) => {});
test('pays', async ({ screen }) => {});
});- The group also shares secret state: a value one member resolves stays redacted for the rest of the group’s attempt. A retry starts fresh.
- Members take the
traceandvideoon the serialdescribeor a group around it. The group records one video per group attempt. - A group attempt may not start because its file fails to load or its session
fails to launch. Then the first member fails with that error, and the rest
skip with cause
serial-predecessor-failed. When the run is interrupted during the launch, every member skips instead. - If a retry is interrupted or never reaches its members, they keep the verdicts and durations of the last attempt that ran them.
- The exit code follows the error’s category, as for any other test.
sessions
test.setup only. The session names the setup test must save.
test.setup('authenticate', { sessions: ['member', 'admin'] }, async ({ session }) => {});A static, non-empty array of unique names. Each name matches
/^[A-Za-z0-9_.-]{1,128}$/. See test.setup.
Fixtures
agent, app, and screen reach test bodies, beforeEach, and
afterEach. platform reaches every hook too, and session only
test.setup bodies. TestFixtures describes each one.
Everything else is a fixture the target’s engine contributes, or one of
your own. @e2e-dev/web contributes
browser; a device engine contributes device.
The fixtures above are lazy. Destructuring in the parameter list acquires them before the body’s first statement. Your own fixtures are not lazy.
Your own fixtures
test.extend(fixtures) defines resources set up before each test and cleaned
up afterward, including after a failure. In each fixture function, code before
await use(value) sets up the resource. The test receives value, and code
after use tears it down. For a guide with a full suite, see
Writing fixtures.
import { test as base } from '@e2e-dev/web';
export const test = base.extend<{ workspace: Workspace }>({
workspace: async ({ browser }, use) => {
const workspace = await createWorkspace();
await signIn(browser, workspace);
await use(workspace); // the hooks and the body run here
await workspace.cleanup(); // teardown, after the body even when it failed
},
});
test('renames the workspace', async ({ workspace, screen }) => {
await screen.getByLabel('Name').fill(`${workspace.name} (renamed)`);
});A definition is typed against the fixtures of the test it extends, not its siblings in
the same call. A fixture that needs another goes in a chained second
extend: base.extend({ a }).extend({ b }) gives b a fixture object that
already has a.
Per attempt:
- Each definition in the
extendchain the test was registered through runs in declaration order, after the engine’s fixtures, until it callsuse. It runs whether or not the test names it. A fixture that opens a page or changes app state does so for every test of thattest. So a file whose tests need different setups registers them through differentextendchains. Setup counts against the testtimeout. A failure is reported in phasebeforeEach, before anybeforeEachhook has run. beforeEachhooks, the body, thenafterEachhooks run with the same fixture object. The fixture set is the test’s own chain: a hook that readsworkspacearound a test registered throughbasefails withUNSUPPORTED_CAPABILITY.- Teardowns run in reverse order after the last
afterEach, whether or not the body passed, each with its owncleanupTimeoutbudget. An error there fails a passing attempt in phaseafterEachand joinssecondaryErrorsafter a body failure.
A body or hook that hits the test timeout is abandoned, not cancelled, so
teardown starts while it may still be running. A setup abandoned this way
that reaches use later gets an immediate resolve. Its teardown runs
detached from the run, so what it allocated is still released. Later
fixtures, hooks, and the test body do not start after an abandoned setup or
hook finishes.
Types
TestAPI
export interface TestAPI<Fixtures = TestFixtures> {
/** Registers one test synchronously during module evaluation. */
(title: string, fn: TestFn<Fixtures>): TestCase;
/** Registers one configured test synchronously during module evaluation. */
(title: string, options: TestOptions, fn: TestFn<Fixtures>): TestCase;
/** Registers one skipped test. */
skip(title: string, fn: TestFn<Fixtures>): TestCase;
/**
* Inside a running test: skips it when `condition` is true (or always,
* with no condition) by throwing, so nothing after the call runs. The
* attempt is reported `skipped` with `reason`; steps that already ran stay
* in the report without deciding the status, and teardown still runs. A
* setup test cannot skip: its sessions are owed.
* Outside a test body this form is `COLLECTION_ERROR`; use the `skip`
* option to skip at collection.
*/
skip(condition: boolean, reason?: string): void;
skip(reason?: string): void;
/** Registers one test that is expected to fail. */
fail(title: string, fn: TestFn<Fixtures>): TestCase;
/**
* Inside a running test: marks it expected to fail when `condition` is
* true (or always, with no condition). The body keeps running. A test
* failure then passes the test, keeping the error and `reason` in the
* report; a pass fails it with `UNEXPECTED_PASS`. Infrastructure failures
* and interrupts are not covered. A setup test or a serial group member
* cannot be marked. Outside a test body this form is `COLLECTION_ERROR`;
* use `test.fail(title, fn)` or the `fail` option to mark at collection.
*/
fail(condition: boolean, reason?: string): void;
fail(reason?: string): void;
/** Registers one focused local test. CI rejects focused tests. */
only(title: string, fn: TestFn<Fixtures>): TestCase;
/** Registers one setup test with statically declared session outputs. */
setup(title: string, options: SetupOptions, fn: SetupFn<Fixtures>): TestCase;
/**
* Returns the same runtime `test`, typed with an engine's contributed
* fixtures. A pure type refinement, the fixtures still resolve from the
* target's engine at runtime, so a project types its device/desktop/web
* surface without a global `declare module` augmentation:
*
* export const test = base.extend<{ device: Device }>();
*/
extend<Extra>(): TestAPI<Fixtures & Extra>;
/**
* Returns a new `test` whose registrations carry these fixture
* definitions on top of the ones it already had. Each attempt sets them up
* in declaration order after the engine's fixtures, runs the hooks and the
* body with them, and tears them down in reverse order after `afterEach`:
*
* export const test = base.extend<{ workspace: Workspace }>({
* workspace: async ({ browser }, use) => {
* const workspace = await createWorkspace();
* await use(workspace);
* await workspace.cleanup();
* },
* });
*/
extend<Extra>(fixtures: FixtureDefinitions<Fixtures, Extra>): TestAPI<Fixtures & Extra>;
/** Declares a group synchronously. */
describe<Result>(title: string, body: SynchronousBody<Result>): void;
/** Declares a configured group synchronously. */
describe<Result>(
title: string,
options: DescribeOptions,
body: SynchronousBody<Result>,
): void;
/** Registers a test-attempt setup hook. */
beforeEach(fn: TestHookFn<Fixtures>): void;
/** Registers a test-attempt teardown hook. */
afterEach(fn: TestHookFn<Fixtures>): void;
/** Registers a suite-instance setup hook. */
beforeAll(fn: SuiteHookFn): void;
/** Registers a suite-instance teardown hook. */
afterAll(fn: SuiteHookFn): void;
}
export const test: TestAPI;
export const describe: TestAPI['describe'];
export const beforeEach: TestAPI['beforeEach'];
export const afterEach: TestAPI['afterEach'];
export const beforeAll: TestAPI['beforeAll'];
export const afterAll: TestAPI['afterAll'];TestOptions
export interface TestOptions {
/** Attempt deadline in milliseconds; defaults to `config.timeout`. Innermost wins. */
timeout?: number;
/** Retries, 0 through 10; defaults to `config.retries`. Inside a serial group the group's value applies. */
retries?: number;
/** Tags for `--tag`: distinct names, none blank, with no comma and no leading or trailing whitespace; every layer's tags are unioned. */
tags?: readonly string[];
/** Skips the test; a string is the reason. Any truthy layer skips. */
skip?: boolean | string;
/**
* Expects the test to fail; a string is the reason. A test failure then
* passes it, and a pass fails it with `UNEXPECTED_PASS`. Not allowed inside
* a serial group.
*/
fail?: boolean | string;
/** Focuses the test locally. CI rejects it with `ONLY_IN_CI`. */
only?: boolean;
/** Platforms the test runs on; other targets skip it. Innermost wins. */
platforms?: readonly string[];
/** Capabilities the target must have; otherwise the test is skipped at selection. Innermost wins. */
requires?: readonly Capability[];
/** Session a setup test saved, restored before the body runs. */
session?: string;
/** Extra context for agent steps; layers are concatenated outermost first. */
agentContext?: string;
/**
* The configured agent (`agents.<name>`) this test or group runs with, in
* place of the run's agents. A list runs the test once per agent named, as
* one result each. Innermost wins; a call's own `agent` option wins over
* it. `--agent` narrows a list to the names both name and never overrides
* a pin the flag does not name.
*/
agent?: string | readonly string[];
/**
* Which of the test's attempts keep a trace, in place of the run's: the
* same modes as the config's `trace`. Innermost wins, over `--trace` too;
* inside a serial group the group's value applies, since the group runs as
* one unit.
*/
trace?: RecordingMode;
/**
* Which of the test's attempts record a video, in place of the run's:
* the same modes as the config's `video`. Innermost wins, over `--video`
* too; inside a serial group the group's value applies, since the group
* records as one unit. A mode set here is required of the target's engine.
*/
video?: RecordingMode;
}
export interface DescribeOptions extends Omit<TestOptions, 'only' | 'fail'> {
/** Runs the group as one ordered retry unit with shared app state. Nesting one serial group in another is a `COLLECTION_ERROR`. */
serial?: boolean;
}
export interface SetupOptions extends Omit<TestOptions, 'session' | 'only' | 'skip' | 'fail' | 'agent'> {
/** Session names this setup test MUST save. */
sessions: readonly string[];
/** A setup test runs once per target, so it pins at most one agent. */
agent?: string;
}TestFixtures
export interface TestFixtures {
/** Agent steps. Acquiring the built-in agent without a configured model is `MODEL_UNAVAILABLE`. */
readonly agent: Agent;
/** App lifecycle: open, restart, clear state, back, screenshot, recording. */
readonly app: App;
/** Semantic queries and the actions on their matches. */
readonly screen: Screen;
/** The target's platform label: `web`, `ios`, `android`, or an engine's own string. */
readonly platform: string;
}
export interface SetupFixtures extends TestFixtures {
/** Saves the sessions the setup test declared. */
readonly session: SetupSession;
}
export interface SuiteFixtures {
/** The target's platform label: `web`, `ios`, `android`, or an engine's own string. */
readonly platform: string;
}FixtureDefinitions
/**
* Defines one fixture: everything before `await use(value)` is its setup,
* everything after is its teardown. The body, its hooks, and later fixtures
* run while `use` is pending; it resolves once they are done, whether or not
* the body failed.
*/
export type FixtureFn<Fixtures, Value> = (
fixtures: Fixtures,
use: (value: Value) => Promise<void>,
) => Promise<void>;
/**
* One definition per fixture `test.extend()` adds. A definition sees the
* fixtures of the `test` it extends, not its siblings: a fixture that needs
* another one goes in a chained `extend()`. A name the base already has is a
* type error (and a `COLLECTION_ERROR` at runtime).
*/
export type FixtureDefinitions<Base, Extra> = {
readonly [K in keyof Extra]: K extends keyof Base ? never : FixtureFn<Base, Extra[K]>;
};Function types
/** A test body. */
export type TestFn<Fixtures = TestFixtures> = (fixtures: Fixtures) => void | Promise<void>;
/** A setup test body; `session.save` is the extra fixture. */
export type SetupFn<Fixtures = TestFixtures> = (
fixtures: Fixtures & SetupFixtures,
) => void | Promise<void>;
/** A `beforeEach` or `afterEach` body. */
export type TestHookFn<Fixtures = TestFixtures> = (fixtures: Fixtures) => void | Promise<void>;
/** A `beforeAll` or `afterAll` body. */
export type SuiteHookFn = (fixtures: SuiteFixtures) => void | Promise<void>;
/** A `describe` body. An async body is a type error. */
export type SynchronousBody<Result> = Extract<Result, PromiseLike<unknown>> extends never
? () => Result
: never;
/** Opaque handle of a registered test. */
export interface TestCase {
readonly [testCaseBrand]: true;
}