A test.beforeAll that creates one user and shares it across multiple tests is a race condition: when the delete test runs first in a parallel worker, the view and edit tests fail with a 404. Each test needs its own data, created before it runs and deleted after. This article covers five patterns for managing test data in Playwright, from a constants file for stable reference data to API fixtures that create and delete records per test, including when database seeding is the right call and how to handle environment-specific credentials without committing them to source.
The Problem with Hard-Coded Data
// Fragile — breaks when the user is deleted or password changes
test('user can log in', async ({ page }) => {
await page.fill('[data-testid="email"]', 'admin@test.com');
await page.fill('[data-testid="password"]', 'AdminPass1');
});Problems:
- Depends on specific data existing in the database
- Multiple tests sharing one account cause conflicts in parallel runs
- Test can only run in one environment unless you remember to change the email
Pattern 1: Constants File
The simplest step up from hard-coded values — centralize all test data in one file.
// data/users.ts
export const TEST_USERS = {
admin: {
email: 'admin@test.com',
password: 'AdminPass1',
name: 'Test Admin',
role: 'admin' as const,
},
member: {
email: 'member@test.com',
password: 'MemberPass1',
name: 'Test Member',
role: 'member' as const,
},
viewer: {
email: 'viewer@test.com',
password: 'ViewerPass1',
name: 'Test Viewer',
role: 'viewer' as const,
},
} as const;
export const TEST_PRODUCTS = {
basic: { id: 1, name: 'Basic Plan', price: 9.99 },
pro: { id: 2, name: 'Pro Plan', price: 29.99 },
enterprise: { id: 3, name: 'Enterprise', price: 99.99 },
} as const;// In tests
import { TEST_USERS, TEST_PRODUCTS } from '../data/users';
test('admin can access dashboard', async ({ loginPage }) => {
await loginPage.login(TEST_USERS.admin.email, TEST_USERS.admin.password);
});Better than scattered hard-coded values, but still depends on those specific users existing.
Pattern 2: Factory Functions
Factory functions generate unique test data per test:
// data/factories.ts
let counter = 0;
export function generateUser(overrides: Partial<User> = {}): CreateUserRequest {
counter++;
return {
email: `test_user_${Date.now()}_${counter}@example.com`,
password: 'ValidPass1!',
name: `Test User ${counter}`,
role: 'member',
...overrides,
};
}
export function generateProduct(overrides: Partial<Product> = {}): CreateProductRequest {
return {
name: `Test Product ${Date.now()}`,
price: Math.floor(Math.random() * 100) + 10,
category: 'electronics',
description: 'A test product for automated testing',
inStock: true,
...overrides,
};
}// In tests
import { generateUser } from '../data/factories';
test('create a new user', async ({ request }) => {
const userData = generateUser({ role: 'admin' });
const response = await request.post('/api/users', {
data: userData,
});
expect(response.status()).toBe(201);
const created = await response.json();
expect(created.email).toBe(userData.email);
});Each test gets a unique email — no more collisions.
Pattern 3: API Setup in Fixtures
Create fresh data via API before each test, delete it after:
// fixtures/index.ts
import { test as base } from '@playwright/test';
import { generateUser } from '../data/factories';
interface TestFixtures {
testUser: { id: number; email: string; password: string; token: string };
adminToken: string;
}
export const test = base.extend<TestFixtures>({
// Admin token — shared, worker scope (created once per worker)
adminToken: [async ({ request }, use) => {
const response = await request.post('/api/auth/login', {
data: { email: 'admin@test.com', password: 'AdminPass1' },
});
const { token } = await response.json();
await use(token);
}, { scope: 'worker' }],
// Test user — unique per test
testUser: async ({ request, adminToken }, use) => {
const userData = generateUser();
// CREATE: new user before test
const createResp = await request.post('/api/users', {
data: userData,
headers: { Authorization: `Bearer ${adminToken}` },
});
const user = await createResp.json();
// Login to get token
const loginResp = await request.post('/api/auth/login', {
data: { email: userData.email, password: userData.password },
});
const { token } = await loginResp.json();
// Give the test what it needs
await use({
id: user.id,
email: userData.email,
password: userData.password,
token
});
// TEARDOWN: delete after test
await request.delete(`/api/users/${user.id}`, {
headers: { Authorization: `Bearer ${adminToken}` },
});
},
});// tests/profile.spec.ts
import { test, expect } from '../fixtures';
test('user can update their profile', async ({ page, testUser }) => {
// testUser is a fresh user, created just for this test
await page.goto(`/login`);
await page.fill('[data-testid="email"]', testUser.email);
await page.fill('[data-testid="password"]', testUser.password);
await page.click('[data-testid="submit"]');
await page.click('[data-testid="edit-profile"]');
await page.fill('[data-testid="name"]', 'Updated Name');
await page.click('[data-testid="save"]');
await expect(page.getByTestId('profile-name')).toHaveText('Updated Name');
// After test: user is automatically deleted
});Pattern 4: Database Seeding
For complex data scenarios, seed the database directly:
// setup/seed.ts
import { chromium } from '@playwright/test';
async function seed() {
const response = await fetch('http://localhost:3000/api/seed', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Seed-Secret': process.env.SEED_SECRET || 'dev-seed-secret',
},
body: JSON.stringify({
users: [
{ email: 'admin@test.com', password: 'AdminPass1', role: 'admin' },
{ email: 'member@test.com', password: 'MemberPass1', role: 'member' },
],
products: [
{ name: 'Basic Plan', price: 9.99, category: 'subscription' },
{ name: 'Pro Plan', price: 29.99, category: 'subscription' },
],
}),
});
if (!response.ok) {
throw new Error(`Seed failed: ${response.status}`);
}
console.log('Database seeded successfully');
}
seed();Run before tests: node setup/seed.ts && npx playwright test
Pattern 5: Saved Auth State
Avoid logging in at the start of every test. Log in once, save the browser state, reuse it:
// auth.setup.ts
import { test as setup } from '@playwright/test';
import path from 'path';
const authFile = path.join(__dirname, '../playwright/.auth/user.json');
setup('authenticate', async ({ page }) => {
await page.goto('/login');
await page.fill('[data-testid="email"]', 'member@test.com');
await page.fill('[data-testid="password"]', 'MemberPass1');
await page.click('[data-testid="submit"]');
await page.waitForURL('/dashboard');
// Save storage state (cookies, localStorage)
await page.context().storageState({ path: authFile });
});// playwright.config.ts
projects: [
{
name: 'setup',
testMatch: /auth\.setup\.ts/,
},
{
name: 'authenticated',
use: {
storageState: 'playwright/.auth/user.json', // Already logged in
},
dependencies: ['setup'],
},
],Tests in the authenticated project skip the login flow — they start with an already-authenticated session.
Managing Data for Different Environments
Use environment variables to point to the right data:
// data/config.ts
export const ENV_USERS = {
local: {
admin: { email: 'admin@local.test', password: 'LocalAdmin1' },
},
staging: {
admin: { email: 'admin@staging.test', password: process.env.STAGING_ADMIN_PASS! },
},
production: {
// Read-only user for production smoke tests
reader: { email: process.env.PROD_READER_EMAIL!, password: process.env.PROD_READER_PASS! },
},
};
const env = (process.env.TEST_ENV || 'local') as keyof typeof ENV_USERS;
export const USERS = ENV_USERS[env];TEST_ENV=staging npx playwright test --project=chromiumHandling Test Isolation
When tests run in parallel, they must not share mutable state.
Bad — shared state:let userId: number;
test.beforeAll(async ({ request }) => {
const user = await request.post('/api/users', { data: generateUser() });
userId = (await user.json()).id;
});
// Multiple tests use the same userId — race conditions!
test('view user', async ({ page }) => { await page.goto(`/users/${userId}`); });
test('edit user', async ({ page }) => { /* edits the same user */ });
test('delete user', async ({ page }) => { /* deletes it! */ });// Use fixtures so each test gets its own user
test('view user', async ({ page, testUser }) => {
await page.goto(`/users/${testUser.id}`);
});
test('edit user', async ({ page, testUser }) => {
// This testUser is different from the one above
});Cleaning Up After Tests
Always clean up data your tests create:
test('creates a product', async ({ request, adminToken }) => {
let productId: number;
try {
const response = await request.post('/api/products', {
data: { name: 'Test Product', price: 19.99 },
headers: { Authorization: `Bearer ${adminToken}` },
});
const product = await response.json();
productId = product.id;
expect(response.status()).toBe(201);
expect(product.name).toBe('Test Product');
} finally {
// Always runs, even if test fails
if (productId!) {
await request.delete(`/api/products/${productId}`, {
headers: { Authorization: `Bearer ${adminToken}` },
});
}
}
});Better: put cleanup in fixture teardown (after await use(...)) so it always runs.
Summary
| Pattern | Best for |
|---------|----------|
| Constants file | Stable reference data (roles, categories) |
| Factory functions | Generating unique test data |
| API fixture setup/teardown | Fresh isolated data per test |
| Database seeding | Complex initial state before test suite |
| Saved auth state | Skipping login in every test |
The most robust approach combines them: factory functions to generate unique data, API fixture to create and delete it per test, saved auth state for the base authenticated session. Each test is completely isolated — no shared state, no race conditions, no test order dependencies.
→ See also: Reusable Test Data: Factories, Fixtures, and Faker.js in Playwright | Test Isolation: Why Each Playwright Test Should Be Stateless | Handling Auth in Playwright with storageState (No Logging In Every Test) | API Testing with Playwright's APIRequestContext (No Postman Required)