Playwright creates a fresh BrowserContext for every test, so browser state (cookies, localStorage, session) is already isolated. Application state isn't. Workers are separate processes that share no global variables, so a module-level let testUserId written by one test is undefined in any test that lands in another worker.
Key takeaways
- Playwright resets browser state for every test but not application state, so each test should create its own data through the API and remove it when it ends.
- A fixture such as
createUserrecords the ids it creates and deletes them after the test, even when the test fails, and atry/finallydoes the same inline. Date.now()alone can repeat when two workers act in the same millisecond, so add a random suffix to emails and usernames.- A setup project logs in once per run and saves
storageState, and every test then starts authenticated in its own browser context. - A suite that passes with
--workers=1and fails with more workers has shared state, and so does a suite that gets flakier as workers are added.
What test isolation actually means
Isolation means a test makes no assumptions about the world before it runs and leaves no trace after it finishes. Each test provisions whatever it needs, does its work, and removes what it created.
State comes in three kinds: browser state (cookies, localStorage, session data), application state (database records, user accounts, feature flags), and test code state (module-level variables, shared fixtures with side effects). Any of them can leak between tests.
A test that uses the page fixture gets its own BrowserContext with no cookies, no localStorage and nothing carried over from other tests. This is the default and needs no setup.
// Each test gets a completely fresh browser context. This is automatic.
test('anonymous user sees login button', async ({ page }) => {
await page.goto('/dashboard');
// No cookies, no session. Truly fresh.
await expect(page.getByRole('link', { name: 'Log in' })).toBeVisible();
});
test('also anonymous, previous test left no trace', async ({ page }) => {
await page.goto('/dashboard');
// Same clean state, regardless of what ran before
await expect(page.getByRole('link', { name: 'Log in' })).toBeVisible();
});Playwright can't isolate your database, so application state is yours to handle.
Classic isolation failures
A test file has a setup test that creates data, a few tests that use it, and a teardown test that removes it. Someone wrote it this way to avoid repeating the creation code.
// tests/user-profile.spec.ts
import { test, expect } from '@playwright/test';
// This is the shared state, the root of the problem
let testUserId: number;
test('setup: create test user', async ({ request }) => {
const response = await request.post('/api/users', {
data: { name: 'Test User', email: 'testuser@example.com' }
});
testUserId = (await response.json()).id;
});
test('can view user profile', async ({ page }) => {
await page.goto(`/users/${testUserId}`);
await expect(page.getByRole('heading', { name: 'Test User' })).toBeVisible();
});
test('can edit user name', async ({ page }) => {
await page.goto(`/users/${testUserId}/edit`);
// ...
});
test('teardown: delete test user', async ({ request }) => {
await request.delete(`/api/users/${testUserId}`);
});This works when the tests run in file order in one worker. It breaks in four ways. You enable fullyParallel. Another test file deletes your test user. The setup test fails and leaves testUserId as undefined for every later test. Or you split the run with --shard while fullyParallel is on, and the setup and teardown land on different machines.
The second failure is an email collision. A test creates a user with email: 'alice@test.com' and passes. On the next run the user still exists because the previous teardown never ran (a browser crash, a CI timeout). The app may then answer with a 409 Conflict that looks like a bug in your registration form.
// BAD: hardcoded email will conflict on re-run
test('register new user', async ({ page }) => {
await page.goto('/register');
await page.getByLabel('Email').fill('alice@test.com');
await page.getByLabel('Password').fill('Password123!');
await page.getByRole('button', { name: 'Create account' }).click();
await expect(page.getByText('Welcome, alice')).toBeVisible();
});
// GOOD: a different email on every run
test('register new user', async ({ page }) => {
const email = `alice-${Date.now()}@test.com`;
await page.goto('/register');
await page.getByLabel('Email').fill(email);
await page.getByLabel('Password').fill('Password123!');
await page.getByRole('button', { name: 'Create account' }).click();
await expect(page.getByText('Welcome, alice')).toBeVisible();
});Date.now() repeats when two workers create a user in the same millisecond, so add a random suffix, as in `alice-${Date.now()}-${Math.random().toString(36).slice(2, 6)}@test.com`. Any format works if it cannot collide.
Data isolation through the API
Each test creates everything it needs through the API at the start and deletes it at the end, in afterEach or a cleanup fixture. No test depends on another test having created anything.
import { test, expect } from '@playwright/test';
test('admin can deactivate a user account', async ({ page, request }) => {
// Create the data this test needs, owned entirely by this test
const createResponse = await request.post('/api/users', {
data: {
name: 'Temporary User',
email: `temp-${Date.now()}@example.com`,
role: 'member'
}
});
expect(createResponse.ok()).toBeTruthy();
const { id: userId } = await createResponse.json();
try {
// The actual test
await page.goto(`/admin/users/${userId}`);
await page.getByRole('button', { name: 'Deactivate account' }).click();
await page.getByRole('button', { name: 'Confirm' }).click();
await expect(page.getByTestId('account-status')).toHaveText('Inactive');
} finally {
// Cleanup runs even if the test fails
await request.delete(`/api/users/${userId}`);
}
});Without finally, a failed assertion skips the cleanup and leaves orphaned records in the database. They pile up over runs and cause failures in other tests.
A custom fixture can take creation and cleanup out of the tests.
// fixtures/api-fixtures.ts
import { test as base, expect } from '@playwright/test';
type ApiFixtures = {
createUser: (overrides?: Partial<{ name: string; email: string; role: string }>) => Promise<{ id: number; email: string }>;
};
export const test = base.extend<ApiFixtures>({
createUser: async ({ request }, use) => {
const createdIds: number[] = [];
const factory = async (overrides = {}) => {
const response = await request.post('/api/users', {
data: {
name: 'Test User',
email: `test-${Date.now()}-${Math.random().toString(36).slice(2, 6)}@example.com`,
role: 'member',
...overrides
}
});
const user = await response.json();
createdIds.push(user.id);
return user;
};
await use(factory);
// Cleanup all users created by this test, runs after every test automatically
for (const id of createdIds) {
await request.delete(`/api/users/${id}`);
}
}
});Any test can now use createUser, and the fixture deletes the created users after the test, even when the test fails.
import { test } from '../fixtures/api-fixtures';
import { expect } from '@playwright/test';
test('editor can update user profile', async ({ page, createUser }) => {
const user = await createUser({ name: 'Jane', role: 'editor' });
await page.goto(`/users/${user.id}`);
await page.getByRole('button', { name: 'Edit profile' }).click();
await page.getByLabel('Display name').fill('Jane Updated');
await page.getByRole('button', { name: 'Save' }).click();
await expect(page.getByRole('heading', { name: 'Jane Updated' })).toBeVisible();
});Creating two users in one test means calling createUser twice, and the fixture deletes both.
createUser, createOrder and createProduct as fixtures from the start, so no test carries its own setup and cleanup code.storageState and auth isolation
Authentication is a separate concern. A full browser login in every test is slow, but tests that share one live session break each other when one of them logs out or changes account settings.
Log in once in a setup project, save the authenticated storageState to a file, and load that file in every test. Each test then gets its own browser context that starts authenticated.
// tests/auth.setup.ts runs once per run, before the projects that depend on it
import { test as setup, expect } from '@playwright/test';
import path from 'path';
const authFile = path.join(__dirname, '../.auth/user.json');
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Email').fill(process.env.TEST_USER_EMAIL!);
await page.getByLabel('Password').fill(process.env.TEST_USER_PASSWORD!);
await page.getByRole('button', { name: 'Sign in' }).click();
// Wait until we're past the login page
await page.waitForURL('/dashboard');
await expect(page.getByRole('navigation')).toBeVisible();
// Save the authentication state
await page.context().storageState({ path: authFile });
});// playwright.config.ts
import { defineConfig } from '@playwright/test';
import path from 'path';
export default defineConfig({
projects: [
{
name: 'setup',
testMatch: '**/auth.setup.ts',
},
{
name: 'authenticated tests',
dependencies: ['setup'],
use: {
storageState: path.join(__dirname, '.auth/user.json'),
},
testMatch: '**/*.spec.ts',
},
],
});Each test now starts authenticated without the login flow, in a new BrowserContext filled from the file. Browser state stays isolated, but every test holds the same server-side login. If tests change server-side state of that account, such as its settings, they can still interfere. For that case the Playwright authentication guide recommends one account per parallel worker.
storageState file for each role during setup. Your fixtures can then load the right state based on what a test needs. This is much faster than logging in with different credentials inside individual tests.Isolation is what makes parallelism safe
Tests that share state Parallel Execution in Playwright: Workers, Shards, and Sharding for Speed.
Workers run simultaneously, with no ordering between them. If test A in worker 1 and test B in worker 2 both create a user with email: 'admin@test.com', one fails with a uniqueness violation, and which one depends on a timing race. That is Flaky Tests: Why They Happen and How to Eliminate Them.
// playwright.config.ts. This only works if tests are truly isolated.
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './tests',
fullyParallel: true, // Every test in every file runs concurrently
workers: process.env.CI ? 4 : '50%',
retries: process.env.CI ? 1 : 0,
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000',
trace: 'on-first-retry',
},
});fullyParallel: true runs individual tests in parallel instead of only whole files. In the ideal case, 150 tests at 3 seconds each take 7.5 minutes on one worker and about 2 minutes on four. What limits the gain is how well your tests are isolated.
If raising the worker count makes the suite flakier, you almost certainly have shared state somewhere, because more workers means more tests overlapping in time.
Finding isolation leaks in an existing suite
Step 1. Run with --workers=1 and compare. If the suite passes with one worker and fails with more, you have shared state. The failing tests are the victims, and the tests that break them are harder to find.
# Does the suite pass sequentially?
npx playwright test --workers=1
# Does it still pass with parallelism?
npx playwright test --workers=4Step 2. Shuffle the order. Some isolation bugs appear only when test B runs before test A, and a fixed order hides them. Run npx playwright test --shuffle to schedule tests in random order. Playwright prints the seed at the start of the run, and passing it back as --shuffle <seed> reproduces the same order.
Step 3. Search for these patterns. Module-level variables that tests write to are a common culprit.
// Grep your test files for these patterns. Each is a potential isolation leak.
// Module-level variable being assigned inside a test
let userId: number;
let authToken: string;
let createdRecord: any;
// test.beforeAll creating data used by multiple tests
test.beforeAll(async ({ request }) => {
// If anything here creates shared mutable state, you have a leak
});
// Hardcoded email addresses, user names, or any fixed unique identifiers
data: { email: 'fixed@test.com' }
data: { username: 'testadmin' }
data: { id: 1 }Step 4. Check the cleanup paths. Search for test.afterAll. It runs once per worker, after all tests of its group, so a failed test can leave half-created data for it to trip over. Move per-test cleanup into afterEach or a fixture teardown.
Step 5. Put the test title in the data. Name test records after the test that creates them.
const user = await createUser({
name: `Test user for: ${test.info().title}`,
email: `test-${Date.now()}@example.com`
});Ten leftover rows that carry the title of the "admin can deactivate a user account" test point to failed cleanup in that test.
Where to start
In an existing suite, fix the problems in this order.
First 30 minutes. Audit test files for module-level variables. Any let or var declared at module level and written inside a test() block is a leak. Move the declaration inside the test, use beforeEach to create fresh state, and check that the tests still pass.
Next hour. Replace hardcoded Test Data Management in Playwright: Strategies and Patterns. Email addresses, usernames, phone numbers and every other field with a uniqueness constraint should come from Date.now() plus a random suffix. That ends the tests that fail on the second run.
This week. Build a createUser fixture, or one for whichever entity your tests create most. Put creation and deletion in one place and move the five most problematic test files to it.
This sprint. Enable fullyParallel: true with two workers and watch the failure count. Each new failure is probably an isolation leak that was hiding, so fix it as it surfaces. Once the suite is clean at two workers, go to four, and keep going until you reach the machine's limit.
Run npx playwright test --shuffle --workers=4 on your suite today. Any test that fails there and passes with --workers=1 is your first candidate for a createUser fixture.
FAQ
When do I use a setup project and when one account per worker?
A setup project with one shared storageState is enough while tests do not change the account's state on the server. If they do, for example by editing its settings, give each parallel worker its own account, as the Playwright authentication guide recommends.
Is afterAll the right place to clean up a test's data?
No. afterAll runs once per worker, after all tests of its group, so a test that failed halfway leaves partial data for it to work on. Put per-test cleanup in afterEach, a finally block or a fixture teardown.
Do retries fix an isolation failure?
No. A test that fails because another one changed its data often passes on the retry, so the suite stays green while the shared state remains. Fix the isolation first and keep retries for network timeouts and third-party noise.
When does --shard split one test file across machines?
Only when fullyParallel is on. By default Playwright gives whole files to a shard, so a setup test and its teardown in the same file stay together.
→ See also: Custom Fixtures in Playwright: The Pattern That Makes Tests Read Like Prose | Flaky Tests: Why They Happen and How to Eliminate Them | Parallel Execution in Playwright: Workers, Shards, and Sharding for Speed | Flaky Tests: Why They Happen and How to Eliminate Them | Test Data Management in Playwright: Strategies and Patterns