# 🧪 Complete Onboarding Flow Testing Guide

## Overview

This guide explains how to test the complete user registration and onboarding flow using **Playwright with Chrome** (or any browser) in your Bakery-IA application.

## 📦 Prerequisites

1. **Install dependencies** (if not already done):
```bash
cd frontend
npm install
```

2. **Install Playwright browsers** (including Chrome):
```bash
npx playwright install chromium
# Or install all browsers
npx playwright install
```

3. **Set up environment variables** (optional):
```bash
# Create .env file in frontend directory
echo "TEST_USER_EMAIL=ualfaro@gmail.com" >> .env
echo "TEST_USER_PASSWORD=Admin123" >> .env
```

## 🚀 Running the Tests

### Option 1: Run All Onboarding Tests in Chrome (Headless)

```bash
npm run test:e2e -- --project=chromium tests/onboarding/
```

### Option 2: Run with Visible Browser Window (Headed Mode)

**This is the best option to see what's happening!**

```bash
npm run test:e2e:headed -- --project=chromium tests/onboarding/
```

### Option 3: Run in Debug Mode (Step-by-Step)

```bash
npm run test:e2e:debug -- tests/onboarding/complete-registration-flow.spec.ts
```

This will:
- Open Playwright Inspector
- Allow you to step through each test action
- Pause on failures

### Option 4: Run with Interactive UI Mode

```bash
npm run test:e2e:ui -- --project=chromium
```

This opens Playwright's UI where you can:
- Select specific tests to run
- Watch tests in real-time
- Time-travel through test steps
- See screenshots and traces

### Option 5: Run Specific Test

```bash
# Run only the complete registration flow test
npx playwright test tests/onboarding/complete-registration-flow.spec.ts --headed --project=chromium

# Run only wizard navigation tests
npx playwright test tests/onboarding/wizard-navigation.spec.ts --headed --project=chromium

# Run only file upload tests
npx playwright test tests/onboarding/file-upload.spec.ts --headed --project=chromium
```

## 🎯 What Gets Tested

### 1. Complete Registration Flow (`complete-registration-flow.spec.ts`)

**Phase 1: User Registration**
- ✅ Navigate to registration page
- ✅ Fill basic information (name, email, password)
- ✅ Password validation (strength requirements)
- ✅ Password confirmation matching
- ✅ Terms and conditions acceptance
- ✅ Marketing and analytics consent
- ✅ Subscription plan selection
- ✅ Payment information entry
- ✅ Redirect to onboarding

**Phase 2: Onboarding Wizard**
- ✅ Bakery type selection (Production/Retail/Mixed)
- ✅ Tenant setup (bakery registration)
- ✅ Sales data upload (or skip)
- ✅ Inventory review
- ✅ Initial stock entry
- ✅ Suppliers setup
- ✅ Recipes setup (conditional)
- ✅ ML training
- ✅ Completion and redirect to dashboard

**Validation Tests**
- ✅ Weak password rejection
- ✅ Invalid email format
- ✅ Password mismatch detection
- ✅ Required terms acceptance

### 2. Wizard Navigation (`wizard-navigation.spec.ts`)

- ✅ Step progression
- ✅ Backward navigation
- ✅ Progress indicator visibility
- ✅ Skip functionality
- ✅ Step validation

### 3. File Upload (`file-upload.spec.ts`)

- ✅ CSV file upload
- ✅ Drag and drop
- ✅ File type validation
- ✅ Invalid file rejection

## 📁 Test File Structure

```
frontend/tests/
├── auth.setup.ts                                    # Authentication setup
├── helpers/
│   └── utils.ts                                     # Test utilities
└── onboarding/
    ├── complete-registration-flow.spec.ts           # ⭐ Full flow test (NEW)
    ├── wizard-navigation.spec.ts                    # Wizard step navigation
    └── file-upload.spec.ts                          # File upload tests
```

## 🎬 Step-by-Step: How to Test Manually with Playwright

### Method 1: Using Playwright Codegen (Record Your Actions)

This is perfect for creating new tests or understanding the flow:

```bash
# Start the dev server first
npm run dev

# In another terminal, start Playwright codegen
npm run test:e2e:codegen
```

Then:
1. Navigate to `http://localhost:5173/register`
2. Go through the registration process manually
3. Playwright will record all your actions
4. Copy the generated code to create new tests

### Method 2: Run Existing Test in Headed Mode

```bash
# Make sure your dev server is running
npm run dev

# In another terminal, run the test with Chrome visible
npm run test:e2e:headed -- --project=chromium tests/onboarding/complete-registration-flow.spec.ts
```

You'll see Chrome open and automatically:
1. Navigate to registration
2. Fill in the form
3. Select a plan
4. Complete payment
5. Go through onboarding steps
6. Reach the dashboard

## 🐛 Debugging Failed Tests

### View Test Report

After tests run, view the HTML report:

```bash
npx playwright show-report
```

### View Screenshots

Failed tests automatically capture screenshots:

```
frontend/test-results/
├── screenshots/
│   └── onboarding-stuck-step-X.png
└── onboarding-completed.png
```

### View Test Traces

For detailed debugging with timeline:

```bash
# Run with trace enabled
npx playwright test --trace on

# View trace
npx playwright show-trace trace.zip
```

## 🔧 Configuration

### Change Base URL

Edit `frontend/playwright.config.ts`:

```typescript
use: {
  baseURL: 'http://localhost:5173', // Change this
}
```

Or set environment variable:

```bash
export PLAYWRIGHT_BASE_URL=http://your-app.com
npm run test:e2e
```

### Run Against Different Environment

```bash
# Test against staging
PLAYWRIGHT_BASE_URL=https://staging.bakery-ia.com npm run test:e2e:headed

# Test against production (careful!)
PLAYWRIGHT_BASE_URL=https://app.bakery-ia.com npm run test:e2e
```

### Test with Different Browsers

```bash
# Firefox
npm run test:e2e:headed -- --project=firefox

# Safari (WebKit)
npm run test:e2e:headed -- --project=webkit

# Mobile Chrome
npm run test:e2e:headed -- --project="Mobile Chrome"

# All browsers
npm run test:e2e
```

## 💡 Tips & Best Practices

### 1. Run Dev Server First

The tests expect the app to be running. Start it with:

```bash
npm run dev
```

Or let Playwright auto-start it (configured in `playwright.config.ts`):

```typescript
webServer: {
  command: 'npm run dev',
  url: 'http://localhost:5173',
  reuseExistingServer: !process.env.CI,
}
```

### 2. Use Headed Mode for Debugging

Always use `--headed` when developing tests:

```bash
npm run test:e2e:headed
```

### 3. Use `.only` for Single Test

Temporarily run just one test:

```typescript
test.only('should complete onboarding', async ({ page }) => {
  // ...
});
```

### 4. Use `.skip` to Skip Tests

Skip flaky tests temporarily:

```typescript
test.skip('flaky test', async ({ page }) => {
  // ...
});
```

### 5. Slow Down Tests for Visibility

Add `page.setDefaultTimeout()` or use `slow`:

```typescript
test('my test', async ({ page }) => {
  test.slow(); // Triples the timeout
  await page.waitForTimeout(1000); // Wait 1 second
});
```

## 🔐 Testing with Authentication

The tests use authenticated state stored in `tests/.auth/user.json`. This is created by `auth.setup.ts`.

To update test credentials:

```bash
# Edit the file
vim frontend/tests/auth.setup.ts

# Or set environment variables
export TEST_USER_EMAIL=your.email@example.com
export TEST_USER_PASSWORD=YourPassword123
```

## 📊 Test Data

### Default Test User (for existing tests)

```
Email: ualfaro@gmail.com
Password: Admin123
```

### New Test Users (auto-generated)

The `complete-registration-flow.spec.ts` test creates unique users on each run:

```javascript
const testUser = {
  fullName: `Test User ${Date.now()}`,
  email: `test.user.${Date.now()}@bakery-test.com`,
  password: 'SecurePass123!@#'
};
```

### Stripe Test Cards

For payment testing, use Stripe test cards:

```
Success: 4242 4242 4242 4242
Decline: 4000 0000 0000 0002
3D Secure: 4000 0027 6000 3184

Expiry: Any future date (e.g., 12/34)
CVC: Any 3 digits (e.g., 123)
```

## 🎯 Common Test Scenarios

### Test 1: Complete Happy Path

```bash
# Run the complete flow test
npx playwright test tests/onboarding/complete-registration-flow.spec.ts:6 --headed
```

Line 6 is the "should complete full registration and onboarding flow for starter plan" test.

### Test 2: Test Validation Errors

```bash
# Run validation test
npx playwright test tests/onboarding/complete-registration-flow.spec.ts -g "validation errors" --headed
```

### Test 3: Test Backward Navigation

```bash
# Run backward navigation test
npx playwright test tests/onboarding/wizard-navigation.spec.ts -g "backward navigation" --headed
```

## 📹 Recording Test Videos

Videos are automatically recorded on failure. To record all tests:

Edit `playwright.config.ts`:

```typescript
use: {
  video: 'on', // or 'retain-on-failure', 'on-first-retry'
}
```

## 🌐 Testing in Different Languages

The app supports multiple languages. Test with different locales:

```bash
# Test in Spanish (default)
npm run test:e2e:headed

# Test in English
# You'd need to click the language selector in the test
```

## ❓ Troubleshooting

### Issue: "Timed out waiting for webServer"

**Solution:** Your dev server isn't starting. Run it manually:

```bash
npm run dev
```

Then run tests with:

```bash
PLAYWRIGHT_BASE_URL=http://localhost:5173 npm run test:e2e -- --config=playwright.config.ts
```

Or edit `playwright.config.ts` and set:

```typescript
webServer: {
  reuseExistingServer: true, // Use already running server
}
```

### Issue: "Test failed: element not found"

**Solutions:**
1. Increase timeout: `await element.waitFor({ timeout: 10000 })`
2. Check selectors are correct for your language
3. Run in headed mode to see what's happening
4. Use Playwright Inspector: `npm run test:e2e:debug`

### Issue: "Authentication failed"

**Solution:** Update test credentials in `tests/auth.setup.ts` or use environment variables.

### Issue: "Payment test fails"

**Solution:**
- Check if bypass payment toggle is enabled in your test environment
- Verify Stripe is configured with test keys
- Use valid Stripe test card numbers

## 📚 Additional Resources

- [Playwright Documentation](https://playwright.dev)
- [Playwright Best Practices](https://playwright.dev/docs/best-practices)
- [Playwright Debugging](https://playwright.dev/docs/debug)
- [Playwright CI/CD](https://playwright.dev/docs/ci)

## 🎓 Next Steps

1. **Run the existing tests** to understand the flow
2. **Use Playwright Codegen** to record additional test scenarios
3. **Add more test cases** for edge cases (enterprise tier, production bakery, etc.)
4. **Set up CI/CD** to run tests automatically on pull requests
5. **Monitor test flakiness** and improve reliability

---

Happy Testing! 🚀

For questions or issues, check the [Playwright Discord](https://discord.gg/playwright-807756831384403968) or create an issue in the repository.
