The alternative: a worker fixture instead of a Singleton
Instead of a Singleton, Playwright uses a worker fixture with scope: 'worker': it gives one instance per worker but with a managed lifecycle. The code after await use(...) runs when the worker shuts down, so the resource is reliably closed and the dependency is visible in the test signature. Only an expensive resource is worth lifting to worker level, because its state becomes shared across that worker's tests.
Patterns · Singleton
A DB pool is created in every test or never closed. How to get one per worker?
Everything candidates write a Singleton for (a DB connection, an API client, a config) is better done in Playwright as a worker fixture. It gives the same “one instance per worker” but with a managed lifecycle: whoever created it closes it, and the dependency is visible in the test signature.
How it works and why. A fixture with scope: 'worker' is created once per worker, when the first test asks for it, and lives until the worker shuts down. Everything after await use(...) in the fixture code runs on shutdown, even if tests failed. So cleanup is guaranteed, while a module singleton has no shutdown hook.
There is a dependency rule: a test fixture may depend on a worker fixture, but a worker fixture cannot depend on a test fixture (the worker lives longer). In the base.extend<TestFixtures, WorkerFixtures> signature the second generic is exactly the worker fixtures.
The lifecycle of a worker fixture
Example: a pool as a worker fixture. Compare with the module getDb from the previous lesson. Four places:
1export const test = base.extend<{}, { db: Pool }>({
db: [
async ({}, use) => {
2 const pool = new Pool({ connectionString: process.env.DB_URL, max: 3 });
await use(pool);
3 await pool.end();
},
4 { scope: 'worker' },
],
});
- The second
extendparameter describes worker fixtures; the first (empty) one is test fixtures. - The pool is created once per worker, and
max: 3keeps the total number of connections under control. - The code after
usecloses the pool when the worker shuts down. - Without
scope: 'worker'the fixture would be created for every test.
What this gives in practice: an explicit dependency (a test declares { db } and it is visible who goes to the DB), guaranteed closing, and the implementation can be replaced with a separate extend.
Data per worker. The workerInfo parameter (the third argument of a worker fixture) has two indexes. workerIndex is unique for every process, so it changes after a worker restart. parallelIndex lies between 0 and workers - 1 and is kept across a restart, so it is handy for numbering pre-created accounts. This way parallel workers do not touch each other's accounts:
type Account = { id: string; email: string };
export const test = base.extend<{}, { db: Pool; account: Account }>({
db: [
async ({}, use) => {
const pool = new Pool({ connectionString: process.env.DB_URL, max: 3 });
await use(pool);
await pool.end();
},
{ scope: 'worker' },
],
account: [
async ({ db }, use, workerInfo) => {
// parallelIndex is stable across a worker restart
const email = 'qa+w' + workerInfo.parallelIndex + '@example.com';
const res = await db.query(
'insert into accounts(email) values ($1) returning id',
[email],
);
await use({ id: res.rows[0].id, email });
await db.query('delete from accounts where email = $1', [email]);
},
{ scope: 'worker' },
],
});
Limits and alternatives. A worker fixture lives across tests, so state they change becomes shared. If a test leaves junk in the account, the next test of this worker will see it. Keep cheap and isolated resources in a regular test fixture, and lift only what is expensive to create to the worker level.
A Singleton remains acceptable for an immutable config read from env once: there is no state that can be spoiled.
The browser: do not duplicate Playwright
A custom singleton browser
Duplicates the worker's browser, bypasses the project settings (browserName, launchOptions) and risks breaking isolation if tests share a context.
The built-in browser and context
One browser per worker, and isolation comes from a fresh context in every test.
Common mistakes.
- “I made a Singleton for the browser so it is not opened in every test”. Playwright already reuses the browser per worker, and isolation comes from a new
context. A custom singleton browser duplicates this mechanism, bypasses the project settings (browserName,launchOptions) and risks breaking isolation if tests share one context or page. - A worker fixture depends on a test fixture (for example
page): the worker lives longer, so Playwright rejects such a dependency. - Not closing the resource after
use: connections hang, and the worker fixture only hides the leak. - One account for all workers without
parallelIndex: parallel tests change the same data. - Lifting to the worker level what is created in milliseconds: the price of shared state is higher than the gain.
Check yourself
A worker fixture account wants to use page. Why will it not work and what to do?
Answer
page is a test fixture (it lives as long as a test), while a worker fixture lives longer and must exist before the first test. A dependency on a shorter-lived fixture is impossible. Prepare the account with the worker fixture db or an own API client from playwright.request.newContext() (the request fixture, like page, lives within a test), and leave page to the test.
How does parallelIndex differ from workerIndex and which fits a pool of pre-created accounts?
Answer
workerIndex is unique per process and changes when a worker restarts. parallelIndex is from 0 to workers - 1 and is kept across a restart. parallelIndex fits an account pool: the numbering does not grow without bound and the new worker gets the same account.