r/softwaretesting • u/Expensive_Test8661 • Nov 11 '25
Best practices for Playwright E2E testing with database reset between tests? (FastAPI + React + PostgreSQL)
Best practices for Playwright E2E testing with database reset between tests? (FastAPI + React + PostgreSQL)
Hey everyone! I'm setting up E2E testing for our e-commerce web app for my company and want to make sure I'm following best practices. Would love your feedback on my approach.
Current Setup
Stack:
- Frontend: React (deployed via AWS Amplify)
- Backend: FastAPI on ECS with Cognito auth
- Database: PostgreSQL and Redis on EC2
- Separate environments: dev, staging, prod (each has its own ECS cluster and EC2 database)
What I'm Testing:
- End-to-end user flows with Playwright
- Tests create data (users, products, shopping carts, orders, etc.)
- Need clean database state for each test case to avoid flaky tests
The Problem
When running Playwright tests, I need to:
- Reset the database to a known "golden seed" state before each test (e.g., with pre-existing product categories, shipping rules).
- Optionally seed test-specific data for certain test cases (e.g., a user with a specific coupon code).
- Keep tests isolated and repeatable.
Example test flow:
test('TC502: Create a new product', async ({ page }) => {
// Need: Fresh database with golden seed (e.g., categories exist)
// Do: Create a product via the admin UI
// Verify: Product appears in the public catalog
});
test('TC503: Duplicate product SKU error', async ({ page }) => {
// Need: Fresh database + seed a product with SKU "TSHIRT-RED"
// Do: Try to create a duplicate product with the same SKU
// Verify: Error message shows
});My Proposed Solution
Create a dedicated test environment running locally via Docker Compose:
version: '3.8'
services:
postgres:
image: postgres:15
volumes:
- ./seeds/golden_seed.sql:/docker-entrypoint-initdb.d/01-seed.sql
ports:
- "5432:5432"
redis:
image: redis:7
ports:
- "6379:6379"
backend:
build: ./backend
ports:
- "8000:8000"
depends_on: [postgres, redis]
frontend:
build: ./frontend
ports:
- "5173:5173"
test-orchestrator: # Separate service for test operations
build: ./test-orchestrator
ports:
- "8001:8001"
depends_on: [postgres, redis]Test Orchestrator Service (separate from main backend):
# test-orchestrator/main.py
from fastapi import FastAPI, Header, HTTPException
import asyncpg
app = FastAPI()
.post("/reset-database")
async def reset_db(x_test_token: str = Header(...)):
# Validate token
# Truncate all tables (users, products, orders, etc.)
# Re-run golden seed SQL
# Clear Redis (e.g., cached sessions, carts)
return {"status": "reset"}
.post("/seed-data")
async def seed_data(data: dict, x_test_token: str = Header(...)):
# Insert test-specific data (e.g., a specific user or product)
return {"status": "seeded"}Playwright Test Fixture:
// Automatically reset DB before each test
export const test = base.extend({
cleanDatabase: [async ({}, use, testInfo) => {
await fetch('http://localhost:8001/reset-database', {
method: 'POST',
headers: { 'X-Test-Token': process.env.TEST_SECRET }
});
await use();
}, { auto: true }]
});
// Usage
test('create product', async ({ page, cleanDatabase }) => {
// DB is already reset automatically
// Run test...
});Questions for the Community
I've put this solution together, but I'm honestly not sure if it's a good idea or just over-engineering. My main concern is creating a reliable testing setup without making it too complex to maintain.
What I've Researched
From reading various sources, I understand that:
- Test environments should be completely isolated from dev/staging/prod
- Each test should start with a clean, predictable state
- Avoid putting test-only code in production codebases
But I'm still unsure about the implementation details for Playwright specifically.
Any feedback, suggestions, or war stories would be greatly appreciated! Especially if you've dealt with similar challenges in E2E testing.
Thanks in advance! 🙏
15
u/ResolveResident118 Nov 11 '25
I'm confused why you need to reset the database before every test. This will slow down the tests and automatically mean that you would never be able to run them in parallel.
You should be able to design your tests with unique data per test to stop tests from interfering with each other.
6
u/strangelyoffensive Nov 11 '25
Test environments should be completely isolated from dev/staging/prod
Each test should start with a clean, predictable state
Avoid putting test-only code in production codebases
4
u/Additional-Drummer20 Nov 11 '25
If you are not needing to test that the post actually puts items in your database, you could do an route fulfill and test the ui and not the data.
https://playwright.dev/docs/api/class-route#route-fulfill
4
u/grafix993 Nov 11 '25
You shouldnt be messing up with direct database handling on a E2E test suite. Thats an awful practice.
2
u/LongDistRid3r Nov 12 '25
Containers. Use the force.
1
u/Charkles09 Nov 25 '25
We had the same problem at my company. For us it was more a question of QA. We're a startup so test processes are not 100% defined and automated. But we needed a way to quickly recover test data. So much that I built a tool to automate the seeding process.
Aside from the best practices of isolation like everybody said, maybe that is something you would like to explore.
1
u/kettanaito Jan 06 '26
Hi!
Playwright is generally not suited for the kind of isolation you want here. It's a shame, I know. A full isolation on the test level means you spawn an app instance per test case, otherwise you cannot benefit from test parallelism as rightfully pointed out in this thread. Sadly, Playwright is really bad with that. There's no way to run any logic before `webServer`. This type of isolation doesn't seem to be the team's priority and I can understand that.
Your best bet is isolation on the data level. This means that all tests share the same app instance and the same database, and the only thing that prevents them from stepping on each other's toes is that they operate on completely different data. This should get you far in UI testing.
1
u/Strict_Illustrator95 May 03 '26
I think the idea makes sense, but I wouldn’t reset the entire DB before every test by default.
I’d probably keep a small golden seed for stable data, then create scenario-specific data per test.
Full DB/Redis reset is useful for tests that depend on global state, but unique test data per test is usually better for speed and parallel execution.
For Playwright, fixtures are a good place for setup, but I’d make the reset strategy explicit per test instead of automatic for every test.
1
u/agsuy Nov 11 '25
Separation of concerns.
Your approach is wrong. Your Lead should be able to provide a more comprehensive answer, but it seems like basic concepts like the test pyramid are alien to you.
Try to understand your own stack and how your application works. Then focus on testing API interactions, not UI.