# Testing Guide - Premium Blocks for Gutenberg

This document describes the testing infrastructure for the `useBlockId` hook and its helper functions.

## Test Stack

### Jest (Unit Tests)
- **Purpose**: Test pure JavaScript logic (`generateBlockId` function and hook logic isolation)
- **Framework**: Jest with React Testing Library
- **Location**: `tests/unit/`

### Playwright (E2E Tests)
- **Purpose**: Test block behavior in WordPress block editor (WP 6.x & 7.0+)
- **Framework**: Playwright Test with wp-env
- **Location**: `tests/e2e/`

### GitHub Actions (CI/CD)
- **Purpose**: Automated testing on every push and PR
- **Runs**: Jest unit tests + Playwright E2E against WP 6.7 and latest

---

## Local Setup

### Prerequisites
```bash
# Node.js 18+
node --version

# Install dependencies
npm install
```

### WordPress Environment Setup

The plugin uses `@wordpress/env` (wp-env) for a local WordPress environment:

```bash
# Start WordPress environment (uses .wp-env.json)
npm run env:start

# Access WordPress at: http://localhost:8889
# Admin: admin / password

# Stop environment
npm run env:stop

# Destroy environment
npx wp-env destroy
```

**Optional**: Use Local by Flywheel or another tool for custom WP versions.

---

## Running Tests

### Unit Tests (Jest)

```bash
# Run all unit tests
npm run test:unit

# Run tests in watch mode (re-run on file changes)
npm run test:unit:watch

# Run with coverage report
npm run test:unit:coverage

# Run specific test file
npm run test:unit -- tests/unit/generateBlockId.test.js

# Run tests matching a pattern
npm run test:unit -- --testNamePattern="generateBlockId"
```

**Test Files**:
- `tests/unit/generateBlockId.test.js` - Tests for block ID extraction logic
- `tests/unit/useBlockId.test.js` - Tests for the custom hook (mocked)
- `tests/unit/setup.js` - Jest configuration and WordPress mocks

### E2E Tests (Playwright)

```bash
# Start WordPress environment first
npm run env:start

# Run all E2E tests
npm run test:e2e

# Run E2E tests with UI (visual debugging)
npm run test:e2e:ui

# Run E2E tests in headed mode (see browser)
npm run test:e2e:headed

# Debug mode (pause and inspect)
npm run test:e2e:debug

# Run specific test file
npx playwright test tests/e2e/useBlockId.spec.js

# Run tests matching a pattern
npx playwright test --grep "Save button"
```

**Test Files**:
- `tests/e2e/useBlockId.spec.js` - Block editor integration tests

### Combined

```bash
# Run all tests (unit + E2E)
npm run test

# This also runs in GitHub Actions on every push/PR
```

---

## Test Coverage

### Unit Tests - `generateBlockId`

✅ **ID Extraction**
- Extracts 5th segment from WordPress clientId
- Handles various clientId formats
- Returns consistent results

✅ **Edge Cases**
- Empty/malformed clientIds
- Simple one-segment IDs
- IDs with multiple hyphens in segments

✅ **Uniqueness**
- Different clientIds produce different IDs
- Same clientId always produces same ID

✅ **WordPress Patterns**
- Real WordPress v5+ UUID-style clientIds
- Custom block namespace formats
- Nested block clientIds

### Unit Tests - `useBlockId` Hook

✅ **ID Generation**
- Generates ID with default prefix
- Respects custom prefix
- Uses custom attribute key (e.g., `block_id` for container)

✅ **Duplicate Detection**
- Regenerates ID if already claimed by another block
- Keeps valid registered IDs
- Handles ID conflicts

✅ **Registry Management**
- Registers blockId in Redux store
- Unregisters old ID when changed
- Cleans up on component unmount

✅ **Class Migration**
- Sets `classMigrate: true` when applicable
- Handles missing/existing attributes

✅ **Dependencies**
- Updates when clientId changes
- Updates when prefix changes
- Proper cleanup on unmount

### E2E Tests - Block Editor Behavior

✅ **Save Button Fix** (Primary Goal)
- Block inserted → save → reload → button should NOT be active
- No dirty state triggered by blockId generation alone

✅ **Duplicate Detection**
- Copy/paste block → new unique blockId
- Duplicated block gets different ID than original
- No CSS class collisions

✅ **Block Removal**
- Removed block unregisters from pbg/data store
- No orphaned registry entries

✅ **Copy/Paste**
- Copy block → paste → new blockId generated
- Different blockId for each instance

✅ **Undo/Redo**
- Undo block insertion → removed correctly
- Redo → blockId preserved
- Registry state maintained

✅ **Multiple Blocks**
- Multiple PBG blocks on same page have unique IDs
- No ID collisions
- All IDs properly registered

✅ **Custom Attribute Key**
- Container block uses `block_id` instead of `blockId`
- Custom key is respected and generates correct ID

---

## WordPress Compatibility

Tests run against multiple WordPress versions:

| Version | Status | Notes |
|---------|--------|-------|
| WP 6.7 | ✅ Tested in CI | Standard Gutenberg |
| WP Latest | ✅ Tested in CI | Current version |
| WP 7.0 | ✅ Manual testing | React 19, new editor changes |

**To test against specific WP version locally**:

```bash
# Test with specific WordPress version
npx wp-env start --wp=6.7

# Or WP 7.0 when released
npx wp-env start --wp=7.0
```

---

## CI/CD Pipeline

Triggered on:
- Push to `main` or `develop` branches
- Pull requests to `main` or `develop`

**Workflow**: `.github/workflows/test.yml`

**Steps**:
1. Unit tests (Jest) - Node 18 & 20
2. E2E tests (Playwright) - WP 6.7 & Latest
3. Coverage report uploaded to Codecov
4. Test reports archived for 30 days

**Artifacts**:
- `playwright-report-*/` - Playwright HTML report (interactive)
- `test-results-*/` - JUnit XML test results

---

## Debugging Tests

### Jest Debugging

```bash
# Run tests with verbose output
npm run test:unit -- --verbose

# Run single test with console logs visible
npm run test:unit -- --no-coverage tests/unit/generateBlockId.test.js

# Watch mode with interactive menu
npm run test:unit:watch
# Press 'a' to run all tests
# Press 'p' to filter by filename pattern
```

### Playwright Debugging

```bash
# Debug mode - pauses and opens inspector
npm run test:e2e:debug

# Headed mode - see the browser
npm run test:e2e:headed

# See video of failures
npm run test:e2e
# Check: test-results/results.json and playwright-report/
```

### WordPress Debugging

```bash
# Check logs while wp-env is running
npx wp-env logs

# SSH into WordPress container
npx wp-env run wordpress bash

# Check PHP errors
npx wp-env run cli wp debug-bar

# Perform WP-CLI commands
npx wp-env run cli wp plugin list
npx wp-env run cli wp user list
```

---

## Common Issues & Solutions

### Issue: Jest can't find modules
**Solution**: Ensure `.babelrc` and `jest.config.js` are present at project root

### Issue: wp-env port already in use
**Solution**: Stop existing environment
```bash
npx wp-env destroy
```

### Issue: WordPress not ready during E2E tests
**Solution**: GitHub Actions waits 60s. If CI is slow, increase timeout in `.github/workflows/test.yml`

### Issue: Playwright tests fail with "element not found"
**Solution**: Increase wait times or use `page.waitForTimeout(1000)` for slower environments

### Issue: Tests hang on `npm run test:e2e`
**Solution**: Ensure `npm run env:start` completed successfully first

---

## Performance

- **Unit tests**: ~5-10 seconds
- **E2E tests**: ~2-3 minutes per WordPress version
- **Full test suite (CI)**: ~10 minutes

---

## Resources

- [Jest Documentation](https://jestjs.io/)
- [Playwright Documentation](https://playwright.dev/)
- [WordPress Block Editor Handbook](https://developer.wordpress.org/block-editor/)
- [wp-env Documentation](https://developer.wordpress.org/cli/commands/wp-env/)

---

## Contributing Tests

When adding new features to `useBlockId`:

1. Add unit tests to `tests/unit/useBlockId.test.js`
2. Add E2E tests to `tests/e2e/useBlockId.spec.js`
3. Run locally: `npm run test`
4. CI runs automatically on PR

**Test Naming Convention**:
- Describe what should happen: `test('generates blockId with prefix', ...)`
- Use `describe()` to group related tests
- Include both happy path and edge cases
