Part 05 · Operations & Advanced Card 33
Worker-Scoped Fixtures
Card 33: Worker-Scoped Fixtures
What This Pattern Solves
All current fixtures are test-scoped. For expensive setup (database connection, server start), creating it per test wastes time. Worker-scoped fixtures run once per worker process and are shared across all tests in that worker.
How It Works
- Define a fixture with
scope: 'worker'. Setup runs once per worker, teardown once when the worker exits. - Tests in the same worker receive the same fixture value.
- Test-scoped fixtures can depend on worker-scoped fixtures.
- Worker-scoped fixtures cannot depend on test-scoped fixtures (no
{ page }in worker scope).
Code Example
const test = base.extend<{ db: Database }, { dbPool: Pool }>({
dbPool: [async ({}, use) => {
const pool = new Pool({ maxConnections: 5 });
await use(pool);
await pool.close();
}, { scope: 'worker' }],
db: async ({ dbPool }, use) => {
const conn = await dbPool.acquire();
await use(new Database(conn));
await dbPool.release(conn);
},
});
Run This Example
pnpm test src/33-worker-scoped-fixtures
Key Concepts
scope: 'worker': Setup once per worker, teardown once per worker exit.scope: 'test'(default): Setup/teardown for every test.- Use cases: DB pools, API servers, Docker containers, auth token caches.
Common Mistakes
- Using
pagein a worker fixture (not available at worker scope). - Sharing mutable state between tests via worker fixture.
- Forgetting teardown after
use().
Related Patterns
- Previous: Card 32 (Mobile & Emulation)
- Next: Card 34 (Retries & Soft Assertions)
- Complementary: Card 21 (App Driver Fixture), Card 26 (Full Architecture)
Live Demo
👇 This component is what the Playwright test interacts with:
Loading…
Run This Example
pnpm test src/33-worker-scoped-fixtures