> ## 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 it in a module your test files import, not in a test file. A test
file loads again after a failed test and for each serial group and setup test,
and a worker fixture it declares gets a
new instance each time. 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>
