95 / 139 · 13 Browser Automation with Playwright · Fixtures and Test Data← prev⊞ allnext →☰ Read as one page
10.5Test Data Management
API-Based Setup (Recommended)
Create test data through the API before UI tests — faster and more reliable than UI-based setup:
test.beforeEach(async ({ request }) => {
// Create test data via API
await request.post('/api/products', {
data: { name: 'Test Product', price: 29.99 },
});
});
test('product appears in catalog', async ({ page }) => {
await page.goto('/products');
await expect(page.getByText('Test Product')).toBeVisible();
});
test.afterEach(async ({ request }) => {
// Clean up via API
await request.delete('/api/products/test-product');
});
Fixture-Based Test Data
type TestData = {
testUser: { email: string; password: string };
testProduct: { name: string; price: number };
};
export const test = base.extend<TestData>({
testUser: async ({}, use) => {
await use({ email: 'test@example.com', password: 'password' });
},
testProduct: async ({ request }, use) => {
// Create product via API
const response = await request.post('/api/products', {
data: { name: `Product-${Date.now()}`, price: 29.99 },
});
const product = await response.json();
await use(product);
// Teardown: clean up after test
await request.delete(`/api/products/${product.id}`);
},
});