To build an end-to-end (E2E) testing suite for an Angular frontend and a FastAPI backend, use Playwright for browser automation paired with an isolated test database. Playwright integrates directly with the Angular CLI (ng e2e) and can automatically orchestrate both servers before running tests. Step 1: Set Up an Isolated Test Environment (FastAPI & Database) E2E tests should never touch production or shared development data. Configure FastAPI to accept a test environment flag that switches to a dedicated test database (e.g. an in-memory SQLite database or a separate PostgreSQL container). 1A. Create a test configuration (backend/config.py) import os from pydantic_settings import BaseSettings class Settings(BaseSettings): DATABASE_URL: str = os.getenv("DATABASE_URL", "postgresql://user:pass@localhost/dev_db") ENV: str = os.getenv("ENV", "dev") settings = Settings() 1B. Add a database reset/seed endpoint (only active in test mode) Expose a helper endpoint in FastAPI so Playwright can wipe and re-seed data before each test run. # backend/main.py from fastapi import FastAPI, HTTPException from config import settings app = FastAPI() @app.post("/api/test/reset-db")def reset_test_db(): if settings.ENV != "test": raise HTTPException( status_code=403, detail="Not allowed outside test environment" ) # Drop tables, recreate schema, and insert baseline test user recreate_tables() seed_default_user() return {"status": "reset complete"} Step 2: Install and Configure Playwright in Angular Modern Angular versions support adding Playwright directly through Angular CLI. 2A. Run the schematic inside your Angular project root: ng e2e Select Playwright when prompted. This generates playwright.config.ts and an e2e/ directory. 2B. Configure playwright.config.ts to auto-start both servers Update the webServer array so Playwright spins up FastAPI and Angular automatically before executing tests, and tears them down afterward: import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ testDir: './e2e', fullyParallel: false, // Run sequentially if sharing one test DB use: { baseURL: 'http://localhost:4200', trace: 'on-first-retry', }, projects: [ { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, ], webServer: [ { command: 'ENV=test DATABASE_URL=sqlite:///./test.db uvicorn main:app --port 8000', cwd: '../backend', url: 'http://localhost:8000/docs', reuseExistingServer: !process.env.CI, }, { command: 'npm run start', url: 'http://localhost:4200', reuseExistingServer: !process.env.CI, }, ], }); Step 3: Map Critical User Journeys Avoid testing every UI edge case in E2E tests (save those for unit tests). Focus on end-to-end flows that verify Angular, FastAPI, and the database communicate properly: * Authentication: Logging in via Angular, receiving a JWT from FastAPI, and storing it. * Data Persistence (CRUD): Submitting a form in Angular, saving it via a FastAPI POST endpoint, reloading the page, and verifying the data renders from a GET endpoint. * Error Handling: Submitting invalid data and confirming FastAPI's 422/400 response displays an error banner in Angular. Step 4: Write the E2E Test Script Use semantic locators (getByRole, getByLabel) rather than brittle CSS classes or XPaths. Call the FastAPI reset endpoint in 'beforeEach' to guarantee a clean state. Create e2e/item-workflow.spec.ts: import { test, expect } from '@playwright/test'; test.describe('Full-Stack Item Management Flow', () => { // 1. Reset backend database before every test test.beforeEach(async ({ request }) => { const response = await request.post('http://localhost:8000/api/test/reset-db'); expect(response.ok()).toBeTruthy(); }); test('user can log in, create an item, and see it persisted after reload', async ({ page }) => { // 2. Navigate to Angular app await page.goto('/login'); // 3. Authenticate (Angular -> FastAPI /auth/login) await page.getByLabel('Email').fill('testuser@example.com'); await page.getByLabel('Password').fill('TestPass123!'); await page.getByRole('button', { name: 'Sign In' }).click(); // Verify redirect to dashboard await expect(page).toHaveURL('/dashboard'); // 4. Create a new record (Angular -> FastAPI POST /api/items) await page.getByRole('button', { name: 'New Item' }).click(); await page.getByLabel('Title').fill('Quarterly Report'); // Intercept the API response to verify backend status code const createResponsePromise = page.waitForResponse( (res) => res.url().includes('/api/items') && res.request().method() === 'POST' ); await page.getByRole('button', { name: 'Save' }).click(); const createResponse = await createResponsePromise; expect(createResponse.status()).toBe(201); // 5. Reload browser to confirm database persistence (FastAPI GET /api/items) await page.reload(); await expect(page.getByText('Quarterly Report')).toBeVisible(); }); }); Step 5: Execute and Debug Locally Run the tests using the Angular CLI or Playwright CLI: * Headless mode (for fast execution): ng e2e * Headed/UI mode (for watching the browser step-by-step): npx playwright test --ui Playwright's UI mode lets you time-travel through every DOM snapshot, inspect network payloads sent between Angular and FastAPI, and view console logs. Step 6: Integrate into CI/CD (GitHub Actions Example) Automate E2E suite on every pull request by adding .github/workflows/e2e.yml: name: E2E Tests on: [push, pull_request] jobs: e2e: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 # Setup Python and FastAPI - uses: actions/setup-python@v5 with: python-version: '3.11' - run: pip install -r backend/requirements.txt # Setup Node and Angular - uses: actions/setup-node@v4 with: node-version: '20' - run: npm ci working-directory: ./frontend # Install Playwright browsers and run tests - run: npx playwright install --with-deps chromium working-directory: ./frontend - run: npx playwright test working-directory: ./frontend =============================================================================== To handle PostgreSQL and SSO authentication cleanly in your Angular + FastAPI E2E suite, use isolated PostgreSQL schema/table truncation for fast resets and Playwright's storageState paired with a FastAPI test-auth bypass so you don't automate third-party login screens (Auth0, Okta, Entra ID) on every test. Step 1: Fast PostgreSQL Reset Endpoint (FastAPI + SQLAlchemy) Dropping and recreating PostgreSQL tables on every test is slow. Instead, connect FastAPI to a dedicated test_db and use PostgreSQL's TRUNCATE ... RESTART IDENTITY CASCADE command to wipe data and reset auto-incrementing IDs in milliseconds. # backend/main.py from fastapi import FastAPI, Depends, HTTPException from sqlalchemy import text from sqlalchemy.orm import Session from database import get_db, Base from config import settings from models import User app = FastAPI() @app.post("/api/test/reset-db") def reset_postgres_db(db: Session = Depends(get_db)): if settings.ENV != "test": raise HTTPException( status_code=403, detail="Forbidden outside test environment" ) # Dynamically collect all table names from SQLAlchemy metadata table_names = [table.name for table in Base.metadata.sorted_tables] if table_names: tables_str = ", ".join(f'"{name}"' for name in table_names) db.execute( text(f"TRUNCATE TABLE {tables_str} RESTART IDENTITY CASCADE;") ) # Seed your baseline SSO user test_user = User( email="e2e.tester@company.com", sso_subject_id="sso-sub-12345", role="admin" ) db.add(test_user) db.commit() return {"status": "PostgreSQL test DB truncated and seeded"} Step 2: Bypass External SSO Providers in Test Mode Automating live third-party SSO UIs (Google, Microsoft Entra, Okta) causes flaky tests due to MFA prompts, CAPTCHAs, and rate limits. Instead, add a test-only login endpoint in FastAPI that mints the exact same session cookie or internal JWT your real SSO callback generates. # backend/auth.py from fastapi import APIRouter, Response, HTTPException from config import settings router = APIRouter() @router.post("/api/test/sso-login") def test_sso_login(response: Response, email: str = "e2e.tester@company.com"): if settings.ENV != "test": raise HTTPException( status_code=403, detail="Forbidden outside test environment" ) # Generate the same internal token/session your SSO callback produces internal_jwt = create_internal_jwt(email=email) # Option A: If your Angular app uses HttpOnly cookies response.set_cookie( key="access_token", value=internal_jwt, httponly=True, samesite="lax" ) # Option B: Also return it in JSON if Angular stores it in localStorage/sessionStorage return {"access_token": internal_jwt} Step 3: Save Auth State Once via Playwright Setup Project Rather than logging in before every test, create a Playwright setup file that hits your test SSO endpoint once, saves the browser's cookies/localStorage to a JSON file, and reuses that authenticated session across all tests. 1. Create e2e/auth.setup.ts:typescript import { test as setup, expect } from '@playwright/test'; const authFile = 'playwright/.auth/user.json'; setup('authenticate via test SSO endpoint', async ({ page, request }) => { // 1. Ensure clean PostgreSQL state await request.post('http://localhost:8000/api/test/reset-db'); // 2. Call FastAPI test SSO endpoint const loginRes = await request.post('http://localhost:8000/api/test/sso-login'); expect(loginRes.ok()).toBeTruthy(); const { access_token } = await loginRes.json(); // 3. Load Angular app & inject token (skip if FastAPI sets an HttpOnly cookie) await page.goto('http://localhost:4200'); await page.evaluate((token) => { localStorage.setItem('access_token', token); // Match your Angular auth key }, access_token); // 4. Verify Angular recognizes the authenticated session await page.goto('http://localhost:4200/dashboard'); await expect(page.getByText('e2e.tester@company.com')).toBeVisible(); // 5. Save cookies & localStorage snapshot await page.context().storageState({ path: authFile }); }); 2. Add .gitignore entry so test auth tokens aren't committed: playwright/.auth/ Step 4: Wire PostgreSQL & Auth Setup into playwright.config.ts Update playwright.config.ts so the setup project runs first, passes storageState to Chromium, and connects FastAPI to your PostgreSQL test instance. import { defineConfig, devices } from '@playwright/test'; export default defineConfig({ testDir: './e2e', fullyParallel: false, // Prevents race conditions on shared PostgreSQL test DB use: { baseURL: 'http://localhost:4200', trace: 'on-first-retry', }, projects: [ // Step 1: Run SSO setup once { name: 'setup', testMatch: /.*\.setup\.ts/ }, // Step 2: Run E2E tests already logged in { name: 'chromium', use: { ...devices['Desktop Chrome'], storageState: 'playwright/.auth/user.json', }, dependencies: ['setup'], }, ], webServer: [ { command: 'ENV=test DATABASE_URL=postgresql://postgres:postgres@localhost:5432/test_db uvicorn main:app --port 8000', cwd: '../backend', url: 'http://localhost:8000/docs', reuseExistingServer: !process.env.CI, }, { command: 'npm run start', url: 'http://localhost:4200', reuseExistingServer: !process.env.CI, }, ], }); Step 5: Write Clean, Pre-Authenticated E2E Tests Your feature tests now start directly on protected routes without repeating login logic: typescript // e2e/orders.spec.ts import { test, expect } from '@playwright/test'; test.beforeEach(async ({ request }) => { // Reset PostgreSQL tables & re-seed the SSO user before each test await request.post('http://localhost:8000/api/test/reset-db'); }); test('authenticated SSO user can create a PostgreSQL record', async ({ page }) => { await page.goto('/orders'); // Already authenticated via storageState await page.getByRole('button', { name: 'Create Order' }).click(); await page.getByLabel('Reference Code').fill('ORD-9001'); await page.getByRole('button', { name: 'Submit' }).click(); await page.reload(); await expect(page.getByText('ORD-9001')).toBeVisible(); });