| | |

Vitest 30 🧪 Test Fixtures — test.extend and Scoped Fixtures

⏱️ Estimated read: 16 min | |

Vitest’s test.extend API is the fixture system inherited from Playwright’s test runner, and it solves a specific problem: setting up and tearing down the resources a test needs without repeating that setup in every test body. A fixture is a function that receives a use callback, performs the setup, calls use(value) to hand the value to the test, and runs the teardown after the test finishes. The test declares the fixture by name in its callback parameters, and Vitest resolves it from the extended test instance’s fixture registry.

The difference from beforeEach and afterEach is granularity. A hook runs for every test in the suite whether the test uses the resource or not, while a fixture runs only when a test requests it by name. A fixture can also depend on other fixtures, so the graph of setup is explicit and lazy: the database fixture pulls in the connection fixture, the connection fixture pulls in the config fixture, and a test that only needs the config never opens the database connection.

This chapter covers the test.extend call that builds a fixture-bearing test instance, the use callback that separates setup from teardown, the scope: "worker" option that promotes a fixture from per-test to per-worker, and the mergeTests helper that composes multiple extended test instances. The sections that follow walk through the basic fixture, the dependency graph between fixtures, the scoping options, and the merge pattern.

Key point: A fixture is an async function that takes a use callback, does the setup before use, and does the teardown after use returns; the test requests it by declaring it in the callback parameters, and a fixture that is never requested never runs its setup, so the fixture registry is a lazy dependency graph rather than an eager hook list.


Why fixtures exist

The unused setup problem. A beforeEach hook that creates a database connection runs for every test in the file, including the tests that only assert on a pure function. The connection is opened, the pool is warmed, and the test never touches it. A fixture inverts the control: the test asks for the connection by name, and the setup runs at that moment. The unused test pays nothing.

The teardown pairing problem. The beforeEach and afterEach hooks are separate functions, and the pairing between them is a convention rather than a guarantee. A fixture puts the setup and the teardown in the same function, around the use call, so the teardown cannot be forgotten and cannot run for a setup that never happened.

The dependency problem. A test that needs a database needs a connection, and a connection needs a config. With hooks the order is the declaration order, which is implicit and fragile. With fixtures the dependency is declared: the database fixture lists the connection fixture in its own callback parameters, and Vitest resolves the order from that graph.

The composition problem. A large codebase has fixtures shared across suites: the auth fixture, the database fixture, the request fixture. The test.extend call returns a new test instance, and the instances compose with mergeTests without re-declaring the fixtures. The alternative is a single global setup file that every suite imports and that grows without bound.

The override problem. A test that needs a fixture with a different value—a read-only database, a mocked clock, a different user role—overrides the fixture locally. The test.extend on the inner suite replaces the named fixture, and the rest of the fixture graph is unchanged. Hooks do not have a clean override mechanism.

The trade-off. Fixtures add indirection: a test that reads test("...", async ({ db }) => ...) requires a reader to find the test.extend call that defined db, and the lazy resolution can surprise a reader who expects setup to have happened before the test file runs. For a small suite the hooks are simpler, and fixtures earn their place when the setup is conditional or the fixtures are shared.


a. The basic fixture and the use callback

The test.extend call takes an object of fixture functions and returns a new test instance that carries them. Each fixture is an async function that receives a context object, destructures the fixtures it depends on, and takes a use callback as the last parameter.

// fixtures.ts
import { test as base } from "vitest";

type Fixtures = {
  db: Database;
  user: User;
};

export const test = base.extend<Fixtures>({
  // Fixture that creates the database connection
  db: async ({}, use) => {
    const db = await createDatabase(); // setup before use
    await use(db);                    // hand the value to the test
    await db.close();                 // teardown after use returns
  },

  // Fixture that depends on `db`
  user: async ({ db }, use) => {
    const user = await db.createUser({ name: "Alice" });
    await use(user);
    await db.deleteUser(user.id); // teardown: undo the insert
  },
});

The use call is where the setup ends and the teardown begins. Everything before use is the setup, everything after use returns is the teardown, and the use call is awaited because the test body runs inside it. If the test throws, the teardown still runs, and the fixture’s exception handling wraps the whole sequence.

A test that uses the fixture declares it in the callback parameters. The parameter name is the fixture name, and the value is what the fixture passed to use.

// user.test.ts
import { test } from "./fixtures";
import { expect } from "vitest";

test("creates a user", async ({ db, user }) => {
  // `db` and `user` are resolved before this line runs
  const found = await db.getUser(user.id);
  expect(found?.name).toBe("Alice");
});

test("does not use the database", async ({ user }) => {
  // `db` is resolved because `user` depends on it
  expect(user.name).toBe("Alice");
});

The second test does not name db, but the user fixture depends on db, so Vitest resolves the dependency and runs both. A test that names no fixture runs no fixture. The resolution is a graph walk from the requested names.

A test can override a fixture’s value for its own scope with test.extend on an inner instance. The override replaces the fixture for the tests in that instance and leaves the parent untouched.

// Override the `user` fixture for a read-only test suite
const readOnlyTest = test.extend<{ user: ReadOnlyUser }>({
  user: async ({}, use) => {
    const user = Object.freeze({ id: 1, name: "Bob", role: "reader" });
    await use(user);
  },
});

readOnlyTest("cannot mutate", async ({ user }) => {
  expect(() => { (user as any).role = "admin"; }).toThrow();
});

b. The dependency graph and the resolution order

A fixture’s first parameter is the fixture context, and destructuring a name from it declares a dependency. The context contains the fixtures the instance already knows about, plus the built-in fixtures Vitest provides. The resolution walks the graph depth-first from the requested test parameters, so a fixture runs after its dependencies and before the test.

import { test as base } from "vitest";

export const test = base.extend({
  // Level 1: no dependencies
  config: async ({}, use) => {
    const config = loadConfig(); // read from env or file
    await use(config);
  },

  // Level 2: depends on `config`
  connection: async ({ config }, use) => {
    const conn = await connect(config.databaseUrl);
    await use(conn);
    await conn.close();
  },

  // Level 3: depends on `connection`
  repo: async ({ connection }, use) => {
    const repo = new UserRepository(connection);
    await use(repo);
  },
});

The chain config → connection → repo runs in that order for a test that requests repo. A test that requests only config never opens the connection, and a test that requests connection and repo runs connection once and shares it between the two. The sharing is per-test by default: each test gets its own connection fixture instance.

The dependency graph is also the teardown order, in reverse. When the test finishes, repo‘s teardown runs first, then connection‘s, then config‘s. The nesting mirrors the setup, so a fixture can rely on its dependencies being alive during its teardown.

A fixture that throws during setup fails the test, and the fixtures that already resolved have their teardown run. The failure is reported at the fixture that threw, and the test body never runs. A fixture that throws during teardown fails the test after the body, and the report distinguishes the two.

export const test = base.extend({
  failingSetup: async ({}, use) => {
    throw new Error("could not open resource"); // fails the test, no body runs
  },

  failingTeardown: async ({}, use) => {
    await use("value");
    throw new Error("could not release resource"); // fails the test after the body
  },
});

The use call is optional to await when the fixture is synchronous, but the async form is the recommended one because it keeps the teardown paired with the setup. A synchronous fixture that returns a value without calling use is treated as a fixture that never runs its teardown, which is almost never the intent.


c. The scoping options and mergeTests

A fixture runs once per test by default. The scope: "worker" option promotes it to once per worker process, so every test file that the worker runs shares the same fixture instance. The worker-scoped fixture is for expensive resources that are safe to share: a connection pool, a compiled template, a started server.

import { test as base } from "vitest";

export const test = base.extend<{}, { server: TestServer }>({
  // The first type is test-scoped, the second is worker-scoped
  server: [
    async ({}, use) => {
      const server = await startTestServer();
      await use(server); // same server for every test in the worker
      await server.stop();
    },
    { scope: "worker" }, // promote to worker scope
  ],

  // Test-scoped fixture that uses the worker-scoped server
  client: async ({ server }, use) => {
    const client = server.createClient();
    await use(client);
    await client.disconnect();
  },
});

The tuple form is how a fixture gets options. The first element is the fixture function and the second is the options object. The scope: "worker" option is the main one, and the auto: true option runs the fixture for every test without the test naming it—the auto fixture replaces the beforeEach hook for unconditional setup.

export const test = base.extend({
  // Runs for every test, even ones that do not name it
  trace: [
    async ({}, use) => {
      const trace = startTracing();
      await use(trace);
      await trace.stop();
    },
    { auto: true },
  ],
});

The mergeTests helper composes multiple extended instances into one. The fixtures from all the instances are available to the merged instance, and a name collision is a type error rather than a silent override.

import { mergeTests } from "vitest";
import { test as dbTest } from "./db-fixtures";
import { test as authTest } from "./auth-fixtures";

// Both `db` and `user` are available on the merged instance
export const test = mergeTests(dbTest, authTest);

test("uses both", async ({ db, user }) => {
  expect(await db.getUser(user.id)).toBeDefined();
});

The mergeTests is the composition path for fixtures from different domains. It does not merge the types, so the merged instance’s fixture types are inferred from the two inputs, and the test’s callback parameters are type-checked against the union.

The test.extend call can also be chained. base.extend(a).extend(b) produces the same result as mergeTests(base.extend(a), base.extend(b)) for non-overlapping fixtures, and the chain is the shorter form when the extensions are local to one file.

export const test = base
  .extend(dbFixtures)   // adds `db` and `connection`
  .extend(authFixtures); // adds `user` and `token`

Complete Example Session

// ============================================
// PART 1: THE BASE FIXTURES
// ============================================
import { test as base } from "vitest";

export const test = base.extend({
  config: async ({}, use) => {
    const config = loadConfig();
    await use(config);
  },

  connection: async ({ config }, use) => {
    const conn = await connect(config.databaseUrl);
    await use(conn);
    await conn.close();
  },
});

// ============================================
// PART 2: THE DEPENDENT FIXTURE
// ============================================
export const dbTest = test.extend({
  repo: async ({ connection }, use) => {
    await use(new UserRepository(connection));
  },

  user: async ({ repo }, use) => {
    const user = await repo.create({ name: "Alice" });
    await use(user);
    await repo.delete(user.id);
  },
});

// ============================================
// PART 3: THE WORKER-SCOPED FIXTURE
// ============================================
export const serverTest = dbTest.extend<{}, { server: TestServer }>({
  server: [
    async ({}, use) => {
      const server = await startTestServer();
      await use(server);
      await server.stop();
    },
    { scope: "worker" },
  ],
});

// ============================================
// PART 4: THE AUTO FIXTURE
// ============================================
export const tracedTest = serverTest.extend({
  trace: [
    async ({}, use) => {
      const trace = startTracing();
      await use(trace);
      await trace.stop();
    },
    { auto: true },
  ],
});

// ============================================
// PART 5: THE OVERRIDE
// ============================================
export const readOnlyTest = tracedTest.extend({
  user: async ({}, use) => {
    await use(Object.freeze({ id: 1, name: "Bob", role: "reader" }));
  },
});

// ============================================
// PART 6: THE MERGE
// ============================================
import { mergeTests } from "vitest";
import { test as authTest } from "./auth-fixtures";

export const appTest = mergeTests(tracedTest, authTest);

// ============================================
// PART 7: THE TEST THAT USES THE GRAPH
// ============================================
appTest("creates a user with auth", async ({ repo, user, token }) => {
  const created = await repo.create({ name: "Carol", token });
  expect(created.name).toBe("Carol");
  expect(user.role).toBe("reader");
});

// ============================================
// PART 8: THE TEST THAT SKIPS THE GRAPH
// ============================================
appTest("does not touch the database", async ({ token }) => {
  // Only `token` is requested; `connection` never opens
  expect(token).toBeDefined();
});

// ============================================
// PART 9: THE FIXTURE WITH SETUP FAILURE
// ============================================
const failingTest = base.extend({
  broken: async ({}, use) => {
    throw new Error("setup failed"); // test body never runs
  },
});

failingTest("reports setup failure", async ({ broken }) => {
  expect(broken).toBeDefined(); // unreachable
});

// ============================================
// PART 10: THE FIXTURE WITH TEARDOWN FAILURE
// ============================================
const teardownTest = base.extend({
  leaking: async ({}, use) => {
    await use("value");
    throw new Error("teardown failed"); // fails after the body
  },
});

teardownTest("reports teardown failure", async ({ leaking }) => {
  expect(leaking).toBe("value"); // body passes, teardown fails the test
});

The ten parts covered the base fixtures, the dependent fixture chain, the worker-scoped fixture, the auto fixture, the override, the merge, a test that uses the graph, a test that skips it, and the two failure modes.


Quick Reference

Fixture Definition

FormMeaning
fixture: async ({ dep }, use) => { ... }Test-scoped fixture
fixture: [fn, { scope: "worker" }]Worker-scoped fixture
fixture: [fn, { auto: true }]Runs for every test
test.extend<TestFixtures, WorkerFixtures>({...})Typed instance

Resolution and Teardown

StageWhat Happens
Test requests repoGraph walk: config → connection → repo
Setup runsEach fixture before its use call
Test bodyRuns inside the innermost use
Teardown runsEach fixture after use, reverse order
Setup throwsTest fails, prior teardowns run
Teardown throwsTest fails after the body

Composition

HelperEffect
test.extend(a).extend(b)Chain, non-overlapping names
mergeTests(a, b)Compose two instances
Override name in extendReplace fixture locally
auto: trueReplace beforeEach

Best Practices

✅ Do This:

// Put setup before `use` and teardown after
db: async ({}, use) => { const d = await open(); await use(d); await d.close(); } // ✅

// Declare dependencies in the fixture context
repo: async ({ connection }, use) => { await use(new Repo(connection)); } // ✅

// Use worker scope for expensive shared resources
server: [async ({}, use) => { ... }, { scope: "worker" }]              // ✅

// Override a fixture for a specialized suite
const ro = test.extend({ user: readOnlyUser });                        // ✅

// Compose with mergeTests for cross-domain fixtures
export const test = mergeTests(dbTest, authTest);                      // ✅

❌ Don’t Do This:

// Forget the `use` call
db: async ({}, use) => { const d = await open(); }                     // ❌

// Put teardown outside the fixture
let db; beforeEach(() => { db = open(); });                            // ❌

// Share a test-scoped resource across tests
cache: async ({}, use) => { await use(globalCache); }                  // ❌

// Name-collide in mergeTests without a type check
mergeTests(a, b); // both define `user`                               // ❌

// Use a worker fixture for per-test state
counter: [async ({}, use) => { ... }, { scope: "worker" }]             // ❌

Common Pitfalls

PitfallWhy It HappensFix
Fixture never runsTest does not name itName it or use auto: true
Teardown skippeduse not awaitedawait use(value)
Shared state leaksTest-scoped fixture reusedUse scope: "worker" deliberately
Dependency cycleA depends on B, B on ABreak the cycle with a third fixture
Override ignoredExtended the wrong instanceExtend the instance the test imports
Merge collisionTwo instances define the same nameRename or drop one
Type error on callbackWrong generic on extendDeclare TestFixtures and WorkerFixtures

Real-World Examples

1. Database fixture

db: async ({}, use) => { const d = await open(); await use(d); await d.close(); }

2. User fixture

user: async ({ db }, use) => { const u = await db.insert(); await use(u); await db.delete(u.id); }

3. Worker-scoped server

server: [async ({}, use) => { const s = await start(); await use(s); await s.stop(); }, { scope: "worker" }]

4. Auto fixture

trace: [async ({}, use) => { const t = start(); await use(t); await t.stop(); }, { auto: true }]

5. Local override

const ro = test.extend({ user: async ({}, use) => { await use(readOnlyUser); } });

6. Merge two instances

export const test = mergeTests(dbTest, authTest);

7. Chain extensions

export const test = base.extend(dbFixtures).extend(authFixtures);

8. Typed extend

base.extend<{ db: Database }, { server: Server }>({ db, server });

9. Fixture dependency

repo: async ({ connection }, use) => { await use(new Repo(connection)); }

10. Setup failure

broken: async ({}, use) => { throw new Error("setup failed"); }

Visual

The Fixture Lifecycle

┌─────────────────────────────────────────────────────────┐
│  FIXTURE FUNCTION                                       │
│                                                         │
│  setup code            ──►  await use(value)            │
│  (opens resource)            │                          │
│                              ▼                          │
│                         test body runs                  │
│                              │                          │
│  teardown code         ◄──  use returns                 │
│  (closes resource)                                      │
│                                                         │
│  Setup throws   ──► test fails, no body                 │
│  Teardown throws ──► body passed, test fails            │
└─────────────────────────────────────────────────────────┘

The Dependency Graph

┌─────────────────────────────────────────────────────────┐
│  config                                                 │
│    │                                                    │
│    ▼                                                    │
│  connection                                             │
│    │                                                    │
│    ▼                                                    │
│  repo                                                   │
│    │                                                    │
│    ▼                                                    │
│  user                                                   │
│                                                         │
│  test({ repo })      → config, connection, repo         │
│  test({ config })    → config only                      │
│  teardown order      → user, repo, connection, config   │
└─────────────────────────────────────────────────────────┘

Test Scope versus Worker Scope

┌─────────────────────────────────────────────────────────┐
│  WORKER PROCESS                                         │
│                                                         │
│  server fixture ──► created once, shared                │
│    │                                                    │
│    ├── test 1 ──► client fixture ──► connect            │
│    ├── test 2 ──► client fixture ──► connect            │
│    └── test 3 ──► client fixture ──► connect            │
│                                                         │
│  test-scoped fixtures run per test                      │
│  worker-scoped fixture runs once per worker             │
└─────────────────────────────────────────────────────────┘

Composition

┌─────────────────────────────────────────────────────────┐
│  base                                                   │
│    │                                                    │
│    ├── extend(dbFixtures)   ──► db, connection          │
│    ├── extend(authFixtures) ──► user, token             │
│    │                                                    │
│    └── mergeTests(dbTest, authTest)                     │
│          │                                              │
│          ▼                                              │
│        db, connection, user, token                      │
│                                                         │
│  Name collision ──► type error, explicit rename         │
└─────────────────────────────────────────────────────────┘

Summary

ItemValue
Fixture functionasync ({ deps }, use) => { ... }
SetupBefore use(value)
TeardownAfter await use(value)
RequestName in test callback params
Test scopeDefault, per test
Worker scope{ scope: "worker" }
Auto fixture{ auto: true }
Overridetest.extend({ name: fn })
CompositionmergeTests(a, b) or chained extend
DependencyDestructure from fixture context

Key takeaways:

  • A fixture is a function around use. Everything before await use(value) is setup, everything after is teardown, and the pairing is enforced by the single function body rather than by two separate hooks.
  • Fixtures are lazy. A test runs only the fixtures it names, plus their dependencies. A test that requests config never opens the connection, and the unused setup costs nothing.
  • Dependencies are the first parameter. Destructuring connection from the fixture context declares the edge in the graph, and the resolution order is the graph walk, with teardown in reverse.
  • The scope option promotes a fixture to the worker. A server or a connection pool that is expensive and safe to share uses { scope: "worker" }, and the instance lives for the whole worker process rather than a single test.
  • mergeTests and chained extend compose instances. The fixtures from multiple extended instances are combined, and a name collision is a type error rather than a silent override.

Remember: The fixture system replaces the beforeEach and afterEach pair with a single function whose setup and teardown are paired around the use call, and it replaces the implicit hook order with an explicit dependency graph declared in the fixture parameters. A test names the fixtures it needs, the graph resolves lazily, and the teardown runs in reverse. Use the worker scope for expensive shared resources, the auto option for the unconditional setup that beforeEach used to do, and mergeTests when the fixtures come from different domains.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!