---
name: write-tests
description: Intelligent test generation that asks about testing requirements, then automatically writes and runs comprehensive test suites until 100% coverage.
isolation: worktree
---

# write-tests

Intelligent test generation that asks about testing requirements, then automatically writes and runs comprehensive test suites until 100% coverage.

## Usage

Ask me to write tests for your code. I'll understand your testing needs, generate appropriate tests, and ensure they all pass.

## Interactive Requirements Phase

### Testing Strategy Questions

```
Q1: What type of tests do you need?
   - Unit tests only
   - Integration tests
   - E2E tests
   - All types

Q2: Which testing framework?
   - Jest (detected)
   - Vitest
   - Playwright
   - Cypress

Q3: Coverage requirements?
   - 100% (recommended)
   - 90%+
   - 80%+
   - Custom threshold

Q4: Test specific features?
   - All features
   - New code only
   - Critical paths
   - Specific components

Q5: Mock requirements?
   - Mock all external calls
   - Mock databases
   - Mock APIs
   - Use real services
```

## Automatic Test Generation

### Phase 1: Analysis

```javascript
// Analyze codebase structure
const analysis = {
  components: findReactComponents(),
  apis: findAPIEndpoints(),
  utils: findUtilityFunctions(),
  hooks: findCustomHooks(),
  services: findServices(),
};

// Calculate what needs testing
const testableUnits =
  analysis.components.length + analysis.apis.length + analysis.utils.length;
console.log(`Found ${testableUnits} units to test`);
```

### Phase 2: Generate Tests

```typescript
// Example: Auto-generated component test
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { MessagesPage } from '@/app/[lang]/features/messages/page';

describe('MessagesPage', () => {
  const mockParams = { lang: 'en' };

  beforeEach(() => {
    jest.clearAllMocks();
  });

  describe('Rendering', () => {
    it('should render without crashing', () => {
      render(<MessagesPage params={mockParams} />);
      expect(screen.getByRole('main')).toBeInTheDocument();
    });

    it('should display all tabs', () => {
      render(<MessagesPage params={mockParams} />);
      expect(screen.getByText('Appointment Reminders')).toBeInTheDocument();
      expect(screen.getByText('Two-Way Chat')).toBeInTheDocument();
      expect(screen.getByText('Broadcast Messages')).toBeInTheDocument();
      expect(screen.getByText('Status Updates')).toBeInTheDocument();
    });
  });

  describe('Interactions', () => {
    it('should switch tabs on click', async () => {
      render(<MessagesPage params={mockParams} />);
      const chatTab = screen.getByText('Two-Way Chat');

      fireEvent.click(chatTab);
      await waitFor(() => {
        expect(screen.getByText(/Real-time patient communication/)).toBeInTheDocument();
      });
    });
  });

  describe('Localization', () => {
    it('should render in Arabic with RTL', () => {
      const arabicParams = { lang: 'ar' };
      const { container } = render(<MessagesPage params={arabicParams} />);
      expect(container.querySelector('[dir="rtl"]')).toBeInTheDocument();
    });
  });

  describe('Error Handling', () => {
    it('should handle missing params gracefully', () => {
      const { container } = render(<MessagesPage params={{}} />);
      expect(container.querySelector('.error-boundary')).not.toBeInTheDocument();
    });
  });

  describe('Performance', () => {
    it('should render within acceptable time', () => {
      const startTime = performance.now();
      render(<MessagesPage params={mockParams} />);
      const renderTime = performance.now() - startTime;
      expect(renderTime).toBeLessThan(100); // 100ms threshold
    });
  });
});
```

### Phase 3: E2E Tests

```typescript
// Auto-generated Playwright test
import { test, expect } from "@playwright/test";

test.describe("Messages Feature E2E", () => {
  test.beforeEach(async ({ page }) => {
    await page.goto("/en/features/messages");
  });

  test("complete user journey", async ({ page }) => {
    // Verify page loads
    await expect(page).toHaveTitle(/Messages.*Mawidi/);

    // Test tab navigation
    await page.click("text=Two-Way Chat");
    await expect(page.locator(".chat-interface")).toBeVisible();

    // Test interactions
    await page.fill('[data-testid="message-input"]', "Test message");
    await page.click('[data-testid="send-button"]');

    // Verify response
    await expect(page.locator(".message-sent")).toBeVisible();
  });

  test("responsive design", async ({ page }) => {
    // Desktop view
    await page.setViewportSize({ width: 1920, height: 1080 });
    await expect(page.locator(".desktop-layout")).toBeVisible();

    // Mobile view
    await page.setViewportSize({ width: 375, height: 667 });
    await expect(page.locator(".mobile-layout")).toBeVisible();
  });

  test("accessibility", async ({ page }) => {
    const accessibilitySnapshot = await page.accessibility.snapshot();
    expect(accessibilitySnapshot.violations).toHaveLength(0);
  });
});
```

## Verification Loop

```bash
#!/bin/bash
# test-verification.sh

echo "🧪 Running Test Verification Loop..."

# Keep running until 100% pass rate
while true; do
  # Run tests
  npm test -- --coverage > test-results.txt 2>&1

  # Check results
  if grep -q "All tests passed" test-results.txt; then
    coverage=$(grep "All files" test-results.txt | awk '{print $4}')
    if [[ ${coverage%\%} -ge 90 ]]; then
      echo "✅ All tests passing with ${coverage} coverage!"
      break
    else
      echo "📝 Adding more tests for better coverage..."
      npm run generate:tests -- --missing-only
    fi
  else
    echo "🔧 Fixing failing tests..."
    # Auto-fix test issues
    npm run test:fix
  fi
done
```

## Smart Test Features

### 1. Intelligent Mocking

```javascript
// Automatically generate mocks
function generateMock(service) {
  const methods = Object.getOwnPropertyNames(service.prototype);
  const mock = {};

  methods.forEach((method) => {
    mock[method] = jest.fn().mockResolvedValue({
      success: true,
      data: generateMockData(method),
    });
  });

  return mock;
}
```

### 2. Snapshot Testing

```javascript
// Auto-generate snapshots
it("should match snapshot", () => {
  const component = render(<Component />);
  expect(component).toMatchSnapshot();

  // Auto-update if needed
  if (process.env.UPDATE_SNAPSHOTS) {
    expect(component).toMatchSnapshot();
  }
});
```

### 3. Performance Benchmarks

```javascript
// Generate performance tests
describe("Performance", () => {
  it("should meet performance budget", async () => {
    const metrics = await measurePerformance();
    expect(metrics.renderTime).toBeLessThan(100);
    expect(metrics.memoryUsage).toBeLessThan(50 * 1024 * 1024);
    expect(metrics.bundleSize).toBeLessThan(200 * 1024);
  });
});
```

## Test Configuration

Auto-generated based on project:

```javascript
// jest.config.js
module.exports = {
  preset: "ts-jest",
  testEnvironment: "jsdom",
  roots: ["<rootDir>/src"],
  collectCoverageFrom: [
    "src/**/*.{ts,tsx}",
    "!src/**/*.d.ts",
    "!src/**/index.ts",
  ],
  coverageThreshold: {
    global: {
      branches: 90,
      functions: 90,
      lines: 90,
      statements: 90,
    },
  },
  setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
  moduleNameMapper: {
    "^@/(.*)$": "<rootDir>/src/$1",
    "\\.(css|less|scss|sass)$": "identity-obj-proxy",
  },
};
```

## Output Example

```
🧪 Test Generation Started

Analyzing codebase...
✓ Found 23 components
✓ Found 12 API endpoints
✓ Found 8 utility functions
✓ Found 5 custom hooks

Generating tests...
✓ Created 43 unit tests
✓ Created 12 integration tests
✓ Created 8 E2E tests

Running tests...
✓ 63/63 tests passing
✓ Coverage: 94.2%

Improving coverage...
✓ Added 7 edge case tests
✓ Added 3 error handling tests

Final Results:
✅ 73/73 tests passing
✅ Coverage: 98.6%
✅ Performance benchmarks met
✅ No accessibility violations
✅ All snapshots updated

Test suite ready for CI/CD!
```

## Success Criteria

- All tests passing
- Coverage meets threshold
- No flaky tests
- Performance benchmarks met
- Accessibility compliant
- Snapshots current
- Mocks working correctly
