mirror of
https://github.com/tester-army/e2e.git
synced 2026-11-25 02:24:26 +08:00
341 lines
13 KiB
Plaintext
341 lines
13 KiB
Plaintext
---
|
|
title: test
|
|
description: Tests, setup tests, groups, hooks, options, and fixtures.
|
|
---
|
|
|
|
Every `test` member registers synchronously while the test file is imported.
|
|
|
|
```ts
|
|
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;
|
|
/** 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 ({ web }, 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;
|
|
```
|
|
|
|
Calling any member outside collection, or after module evaluation finished,
|
|
throws `COLLECTION_ERROR`.
|
|
|
|
## Members
|
|
|
|
A skipped test never affects the exit code. With `test.only`, other tests
|
|
are reported as `filtered`, and a CI run fails with `ONLY_IN_CI`.
|
|
`test.setup` must be top-level, not inside `test.describe`. An `async`
|
|
`describe` body is a type error and a `COLLECTION_ERROR`.
|
|
|
|
```ts
|
|
import { test } from '@e2edev/playwright';
|
|
import { expect } from 'e2e';
|
|
|
|
test('app opens', async ({ app, web }) => {
|
|
await app.open();
|
|
await expect(web).toHaveURL('/');
|
|
});
|
|
|
|
test('checks out', { tags: ['billing'], retries: 2, timeout: 60_000 }, async ({ app }) => {
|
|
await app.open('/checkout');
|
|
});
|
|
|
|
test.describe('checkout', { tags: ['smoke'], serial: true }, () => {
|
|
test('adds an item', async ({ screen }) => {});
|
|
test('pays', async ({ screen }) => {});
|
|
});
|
|
```
|
|
|
|
`test.setup` declares the sessions it saves, and must save each exactly once:
|
|
|
|
```ts
|
|
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', { name: 'Sign in' }).tap();
|
|
await session.save('member');
|
|
});
|
|
```
|
|
|
|
Session names must match `/^[A-Za-z0-9_.-]{1,128}$/` and be unique.
|
|
Not saving a declared session, or saving one twice, throws `SESSION_CONTRACT`
|
|
at runtime.
|
|
|
|
```ts
|
|
export interface SetupSession {
|
|
/** Saves state under a setup-declared name. */
|
|
save(name: string): Promise<void>;
|
|
}
|
|
```
|
|
|
|
## Hooks
|
|
|
|
`beforeEach` hooks run outermost group first, then in declaration order
|
|
within a group. `afterEach` hooks run innermost first, in reverse declaration
|
|
order, after a failure or timeout too. `beforeAll` runs once per suite
|
|
instance on first entry into the scope; `afterAll` when the scope's last test
|
|
in the realm finishes. Hook order follows scope nesting, not position in the
|
|
file, so a hook declared after a test still applies to it.
|
|
|
|
The module is re-imported for every retry, serial group, and setup test, so
|
|
`beforeAll` runs again in each. A scope's `afterAll` runs as soon as its last
|
|
test in that realm is done. A realm that a failure discards runs `afterAll`
|
|
for every scope whose `beforeAll` started.
|
|
|
|
`beforeEach` and the body share the test timeout. Each `afterEach` hook gets
|
|
its own `cleanupTimeout` budget with working fixtures, so teardown can still
|
|
drive the app after the body timed out.
|
|
|
|
A throw inside `beforeAll` or `afterAll` is `HOOK_FAILED` and skips the
|
|
suite's tests with cause `hook-failed`. Inside a serial group it skips every
|
|
remaining member and fails the group without a retry.
|
|
|
|
## Options
|
|
|
|
```ts
|
|
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`; every layer's tags are unioned. */
|
|
tags?: readonly string[];
|
|
/** Skips the test; a string is the reason. Any truthy layer skips. */
|
|
skip?: 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 Platform[];
|
|
/** 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[];
|
|
}
|
|
|
|
export interface DescribeOptions extends Omit<TestOptions, 'only'> {
|
|
/** 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' | '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;
|
|
}
|
|
```
|
|
|
|
Every numeric option is a positive safe integer. `only` is not accepted on a
|
|
group. `sessions` is required on `test.setup`: a static, non-empty array of
|
|
unique names.
|
|
|
|
Resolution order: test, nearest group, outer groups, config, built-in default.
|
|
|
|
`serial: true` makes the group one ordered retry unit with shared app state
|
|
and shared secret state: a secret fill withholds pixels for the rest of the
|
|
group's attempt. A retry starts fresh. Inside it, `retries`, `session`,
|
|
`platforms`, `requires`, `skip`, `only`, and a nested `serial` on a member
|
|
are collection errors. Set them on the group.
|
|
|
|
## Fixtures
|
|
|
|
```ts
|
|
export interface TestFixtures {
|
|
/** Agent steps. Acquiring it without a configured model is `MODEL_UNAVAILABLE`. */
|
|
readonly agent: Agent;
|
|
/** App lifecycle: open, restart, clear state, back, screenshot. */
|
|
readonly app: App;
|
|
/** Semantic queries and the actions on their matches. */
|
|
readonly screen: Screen;
|
|
/** The target's label: `web`, `ios`, `android`, or an engine's own string. */
|
|
readonly platform: Platform;
|
|
}
|
|
|
|
export interface SetupFixtures extends TestFixtures {
|
|
/** Saves the sessions the setup test declared. */
|
|
readonly session: SetupSession;
|
|
}
|
|
|
|
export interface SuiteFixtures {
|
|
/** The target's label: `web`, `ios`, `android`, or an engine's own string. */
|
|
readonly platform: Platform;
|
|
}
|
|
```
|
|
|
|
Everything else is a fixture the target's engine contributes, or one of
|
|
[your own](#your-own-fixtures). `@e2edev/playwright` contributes
|
|
[`web`](/reference/playwright) and exports a `test` typed with it; a device
|
|
engine contributes `device`. Reaching for a fixture the engine does not
|
|
contribute fails with `UNSUPPORTED_CAPABILITY`; declare `requires: ['web']`
|
|
to skip such tests at selection instead.
|
|
|
|
Fixtures are lazy. Destructuring in the parameter list acquires them before
|
|
the body's first statement.
|
|
|
|
### Your own fixtures
|
|
|
|
`test.extend(fixtures)` defines a resource set up before each test and
|
|
cleaned up after, however the body ended. Each definition is one function in
|
|
Playwright's shape: everything before `await use(value)` is setup, `value` is
|
|
what the test receives, everything after is teardown.
|
|
|
|
```ts
|
|
import { test as base } from '@e2edev/playwright';
|
|
|
|
export const test = base.extend<{ workspace: Workspace }>({
|
|
workspace: async ({ web }, use) => {
|
|
const workspace = await createWorkspace();
|
|
await signIn(web, 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)`);
|
|
});
|
|
```
|
|
|
|
```ts
|
|
/**
|
|
* 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]>;
|
|
};
|
|
```
|
|
|
|
`extend` returns a new `test`; the one it was called on is unchanged. 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:
|
|
|
|
1. Each definition runs in declaration order until it calls `use`. Setup
|
|
counts against the test `timeout`; a failure is reported in phase
|
|
`beforeEach`, before any `beforeEach` hook has run.
|
|
2. `beforeEach` hooks, the body, then `afterEach` hooks run with the same
|
|
fixture object. The fixture set is the test's own chain: a hook that reads
|
|
`workspace` around a test registered through `base` fails with
|
|
`UNSUPPORTED_CAPABILITY`.
|
|
3. Teardowns run in reverse order after the last `afterEach`, whether or not
|
|
the body passed, each with its own `cleanupTimeout` budget. An error there
|
|
fails a passing attempt in phase `afterEach` and joins `secondaryErrors`
|
|
after a body failure.
|
|
|
|
What fails, and where:
|
|
|
|
| Mistake | Fails |
|
|
| --- | --- |
|
|
| A value that is not a plain object of functions, an empty name, a core name (`agent`, `app`, `screen`, `platform`, `session`), or a name an earlier `extend` in the chain defined | At import, `COLLECTION_ERROR` naming the fixture |
|
|
| A name the target's engine contributes (`web` on a Playwright target) | The attempt, in `beforeEach`, `TEST_SETUP_FAILED` |
|
|
| A definition that returns without calling `use` | The attempt, in `beforeEach`, `TEST_SETUP_FAILED` |
|
|
| A definition that calls `use` twice | The attempt, at teardown, `TEST_SETUP_FAILED` |
|
|
| A definition that throws before `use` | The attempt, in `beforeEach`, with that error |
|
|
| A definition that throws after `use` | The attempt, in `afterEach`, with that error |
|
|
|
|
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, and its teardown runs
|
|
detached from the run, so what it allocated is still released.
|
|
|
|
## Function types
|
|
|
|
```ts
|
|
/** 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;
|
|
}
|
|
```
|