Skip to content

Scoped Fixtures #6157

Open
Open
@V-Mann-Nick

Description

@V-Mann-Nick

Clear and concise description of the problem

When setting up a test, fixtures can have a different scope. Suppose we have two fixtures:

  1. db - connection to a database possibly with migrations and an initial seed (expensive setup) global to the test module at hand (beforeAll/afterAll)
  2. user - a user created in the db which should be setup and torn down on every test (beforeEach/afterEach)

Scope is also reflected in vitest-fixture. I don't know the exact relation to this project, but I was very happy to see that it was incorporated into vitest directly. But it does seem that there's no feature parity with vitest-fixture as I can't find a way to scope fixtures to the worker.

This makes it really hard to use if you have an expensive setup like described above that you want to only setup and tear down once per test module.

Suggested solution

I think the original vitest-fixture had a good approach at least in terms of API:

import { test as base } from "vitest-fixture";

export const test = base.extend<{}, {resource: string}>({
  resource: [async ({}, use) => {
    const resource = ...; // setup resource
    await use(resource, async () => {
      ...; // teardown resource
    });
  }, { scope: "worker" }],
});

I also would be interested in contributing this feature.

Alternative

No response

Additional context

There exists a similar issue with an overlapping scope:
#4953

@jakebiesinger-storyhealth writes:

Playwright has a notion of automatic fixtures, where the fixture is executed even if it is not part of the fixture dependency list in a test. This enables test writers to implicitly set up fixtures that are common to all tests of a type.

He writes about "common to all tests". While the { auto: true } option did solve this problem, it does not solve the issue that these fixtures are setup and torn down for each test (beforeEach/afterEach) which can potentially be costly.

Validations

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    Status

    Approved

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions