> ## Documentation Index
> Fetch the complete documentation index at: https://e2e.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Writing fixtures

> Write test fixtures with test.extend to create test data and other resources before each test and clean them up after it, even when the test fails.

A fixture is a value a test receives, set up before the test and torn down
after it, even when the test fails. Use one to create test data. To sign in,
use a [saved session](https://e2e.com/docs/authentication) instead.

## Define fixtures in one file

Extend your engine's `test` and export it. A fixture can use `agent`, so it
can create its data through the app with [goals](https://e2e.com/docs/core-concepts#goals):

```ts title="tests/fixtures.ts" expandable

export const test = base.extend<{ project: string; task: string }>({
  /** A fresh project, created and deleted through the app. */
  project: async ({ app, agent, screen }, use) => {
    const name = `Launch plan ${Date.now()}`;
    await app.open('/projects');
    await agent.act('create a project named {name}', { params: { name: unique(name) } });
    await expect(screen.getByRole('heading', name)).toBeVisible();
    await use(name);
    await app.open('/projects');
    await agent.act('delete the project {name}', { params: { name: unique(name) } });
    await expect(screen.getByRole('link', name)).toBeHidden();
  },
  /** One task in that project. Deleting the project deletes it too. */
  task: async ({ project, agent, screen }, use) => {
    const title = 'Write the announcement';
    await agent.act('add a task {title} to the project {project}', { params: { title, project } });
    await expect(screen.getByRole('checkbox', title)).toBeVisible();
    await use(title);
  },
});
```

Code before `await use(value)` is the setup, and code after it is the
teardown. Import the extended `test` in your test files:

```ts title="tests/tasks.e2e.ts"

test('completes a task', { session: 'admin' }, async ({ screen, task }) => {
  await screen.getByRole('checkbox', task).check();
  await expect(screen.getByRole('checkbox', task)).toBeChecked();
});
```

The saved session is restored before the fixtures run.

<Note>
Agent steps in a fixture run for every test that uses it. If your app has a
test API, a `fetch` call is faster.
</Note>

## Build one fixture on another

A fixture names the fixtures it needs in its first parameter, and e2e sets
those up first. `task` names `project`, so a test that names `task` gets a
project too. Teardown runs in reverse order.

A fixture can name the fixtures of the `test` it extends and the ones
declared beside it, in any order. One that needs none takes `({}, use)`.

## Set up only what a test names

e2e sets a fixture up only for a test that names it: in the test body, in a
`beforeEach` or `afterEach` hook, or in another fixture the test uses. A test
that names no fixture sets none up, so one `test` can hold every fixture of
the suite.

Name fixtures by destructuring the first parameter. e2e reads the names from
it, so `async (fixtures) => {}` and a rest property (`{ app, ...rest }`)
fail when the file is collected.

## Run a fixture for every test

Set `auto: true` on a fixture that tests need and don't name, such as one
that resets data:

```ts title="tests/fixtures.ts"
export const test = base.extend<{ cleanData: void }>({
  cleanData: [async ({ app }, use) => {
    await fetch(`${app.baseUrl}/api/test/reset`, { method: 'POST' });
    await use();
  }, { auto: true }],
});
```

With `{ scope: 'worker', auto: true }` it runs once per worker.

## Extend a built-in fixture

Give a fixture the name of a built-in fixture, such as `app` or `device`, to
run code around it. Inside the function the name is the built-in. Tests and
hooks that name it get the value you pass to `use`:

```ts title="tests/fixtures.ts"
export const test = base.extend({
  device: async ({ device }, use) => {
    await device?.setPermission('camera', 'deny');
    await use(device);
  },
});
```

This override is a test fixture, so it runs for each test that uses `device`.
To run it once per worker and use it in `beforeAll`, define it as
`[fn, { scope: 'worker' }]`. See
[Extending a fixture](https://e2e.com/docs/reference/test#extending-a-fixture).

## Run one test on web and mobile

You can run the same test on targets whose engines have different fixtures.
For example, in a config with web and iOS targets, `device` is `undefined` on
web.

```ts title="e2e.config.ts"

export default {
  targets: [
    { engine: web(), app: { url: 'http://localhost:3000' } },
    { engine: mobile({ platform: 'ios' }), app: { bundleId: 'com.example.app' } },
  ],
} as const satisfies E2EConfig;
```

Use `as const satisfies E2EConfig` or
[`defineConfig`](https://e2e.com/docs/reference/config#defineconfig) to keep the config's inferred
type. With a type annotation such as `const config: E2EConfig`,
`typeof config` is plain `E2EConfig`, so the target types aren't inferred. If
you pass that type to `test.extend<{}, {}, typeof config>()`, you get a type
error.

Pass `typeof config` as the third type argument of `test.extend`. Check
`platform === 'ios'` to narrow `device` to `Device`:

```ts title="tests/fixtures.ts"

export const test = base.extend<{ signedOut: void }, {}, typeof config>({
  /** Signs the app out. On iOS, the keychain is cleared first, since `app.clearState()` doesn't clear it. */
  signedOut: async ({ app, platform, device }, use) => {
    if (platform === 'ios') {
      await device.clearKeychain();
    }

    await app.clearState();
    await use();
  },
});
```

With `platforms` on a test, its fixtures are typed for the targets that run
it:

```ts title="tests/menu.e2e.ts"

test('closes the menu with Escape', { platforms: ['web'] }, async ({ browser }) => {
  await browser.keyboard.press('Escape');
});
```

If you [extend `device`](#extend-a-built-in-fixture), your override is called
on web too, with `device` set to `undefined`.

## Share a fixture across a worker

A worker fixture is set up once per worker and target (on the first test or
suite hook that uses it) and torn down when the worker exits. Use it for a
database, server, or API client shared across many tests. Declare it with
`{ scope: 'worker' }` and type it in the second type argument:

```ts title="tests/fixtures.ts"
export const test = base.extend<{}, { database: Database }>({
  database: [async ({}, use) => {
    const database = await startDatabase();
    await use(database);
    await database.stop();
  }, { scope: 'worker' }],
});
```

A worker fixture outlives every test, so it sees worker fixtures only: its
own kind, and the [built-in fixtures](https://e2e.com/docs/reference/test#fixtures) whose scope is
worker on the target.

Declare shared worker fixtures in a module your test files import. The
runner reloads a test file after a failed test and for each serial group and
setup test, and on Node.js reloads a module to register its hooks. Each
runtime handles these reloads differently:

- On Node.js, keep fixture registration synchronous. A top-level `await` in
  the fixture module or one of its dependencies can cause another setup on
  reload while the earlier instance is still active. Await asynchronous
  setup inside the fixture function.
- On Node.js, ES module imports with different URL queries or fragments each
  get their own fixture instance. If an older version of e2e in the same
  process registered the module loader first, worker fixtures go by file
  path, and those imports can share one instance.
  [Worker fixtures](https://e2e.com/docs/reference/test#worker-fixtures) lists the mixed-version
  cases.
- On Node.js, another module `resolve` hook that changes a module's URL
  differently from one load to the next can set the fixture up again while
  the earlier instance is still active.
  [Worker fixtures](https://e2e.com/docs/reference/test#worker-fixtures) has the case to avoid.
- On Bun, a worker fixture declared in a test file gets a new instance each
  time Bun reloads the file. The old instance stays set up until the worker
  ends.

## Read fixtures in hooks

Register the hook on your extended `test` to get the fixture types. A hook
names its fixtures like a test does:

```ts
test.beforeEach(async ({ screen, project }) => {
  await expect(screen.getByRole('heading', project)).toBeVisible();
});
```

`beforeAll` and `afterAll` get worker fixtures only. A device keeps its state
between tests, so on mobile the built-in fixtures `device`, `app`, and
`screen` are worker fixtures too. A browser test gets a new context, so put UI
setup in `beforeEach`. See the scope of each
[built-in fixture](https://e2e.com/docs/reference/test#fixtures).

## When a fixture fails

An error in setup fails the test in `beforeEach`, and an `afterEach` hook
that names the failed fixture is skipped. An error in teardown is reported in
`afterEach`. See the [full list of mistakes](https://e2e.com/docs/reference/test#your-own-fixtures).

## Next

<CardGroup cols={2}>
  <Card title="Test reference" icon="code" href="/reference/test#your-own-fixtures">
    The fixture contract, types, and every failure.
  </Card>
  <Card title="Authentication" icon="key" href="/authentication">
    Save a session once and restore it in each test.
  </Card>
</CardGroup>
