# Test Generator

Analyzes source code and generates comprehensive unit tests. Auto-detects framework (Vitest/Jest/pytest/Go), handles mocking, covers edge cases.

## Quick Reference

# Test Generator

> **Purpose:** Analyze source code and generate comprehensive unit tests following the project's testing conventions.

---

## Invocation

```
/test-gen <file_path> [--framework vitest|jest|pytest|go]
```

---

## Process

### Step 1: Analyze the Target

Read the source file and identify:
- All exported functions/classes/methods
- Input types and return types
- Edge cases from conditional branches
- Dependencies that need mocking
- Existing test file (if any) to avoid duplicates

### Step 2: Determine Testing Framework

Auto-detect from project config:
- `vitest.config.*` → Vitest
- `jest.config.*` or `package.json[jest]` → Jest
- `pytest.ini` or `pyproject.toml[tool.pytest]` → pytest
- `*_test.go` files → Go testing

### Step 3: Generate Test Cases

For each function, generate:

1. **Happy path** — typical valid input → expected output
2. **Edge cases** — empty input, zero, null/undefined, boundary values
3. **Error paths** — invalid input → expected error/exception
4. **Type variations** — different valid types if function accepts union types

### Step 4: Structure the Test File

```typescript
import { describe, it, expect, vi } from 'vitest'
import { targetFunction } from '../path/to/source'

describe('targetFunction', () => {
  it('returns expected result for valid input', () => {
    expect(targetFunction('valid')).toBe('expected')
  })

  it('throws on null input', () => {
    expect(() => targetFunction(null)).toThrow()
  })

  it('handles empty string', () => {
    expect(targetFunction('')).toBe('')
  })
})
```

---

## Mocking Strategy

- **External APIs**: Always mock with `vi.mock()` or `jest.mock()`
- **Database calls**: Mock the client/ORM, not the database
- **File system**: Mock `fs` operations, never touch real files
- **Time**: Use `vi.useFakeTimers()` for time-dependent logic
- **Environment variables**: Set via `vi.stubEnv()` or test setup

---

## Rules

- Match the project's existing test style (describe/it vs test, assertion style)
- Place test files adjacent to source (`*.test.ts`) or in `tests/` mirror
- Never generate snapshot tests unless explicitly asked
- Aim for branch coverage, not just line coverage
- Each test should be independent — no shared mutable state
- Test names should describe behavior, not implementation
