Generate comprehensive tests (unit, integration, E2E) for a component
Generates comprehensive test suites with framework auto-detection, coverage validation, and quality review.
/plugin marketplace add squirrelsoft-dev/agency/plugin install agency@squirrelsoft-dev-toolscomponent file pathGenerate comprehensive test suite with framework auto-detection and coverage validation.
Generate tests for: $ARGUMENTS
Create comprehensive test suite: analyze → strategy → generate → validate → review.
IMMEDIATELY activate the testing strategy skill:
Use the Skill tool to activate: testing-strategy
This skill contains critical testing patterns, frameworks, and best practices you MUST follow.
Resolve $ARGUMENTS to actual file path:
# If full path provided
[Use $ARGUMENTS directly]
# If filename only
Glob pattern="**/$ARGUMENTS"
# If component name (without extension)
Glob pattern="**/$ARGUMENTS.{ts,tsx,js,jsx,vue,svelte}"
<!-- Component: prompts/error-handling/scope-detection-failure.md -->
Use Glob tool to find the file. If multiple matches, ask user which one.
If component cannot be found:
❌ Unable to locate component: $ARGUMENTS
Please provide:
1. Full path to component file, OR
2. Component filename with extension, OR
3. More specific search criteria
Use Read tool to load the component file contents.
<!-- Component: prompts/context/framework-detection.md -->Analyze the code to determine component type:
React Component if contains:
import React or from 'react'export default function or export const<div>, <Component />)useState, useEffect, useCallback)API Endpoint if contains:
app.get(), app.post(), router.use()export default function handler(req, res)fastify.route().query(), .mutation()Utility Function if:
Service/Repository if contains:
Hook (React) if:
use prefixVue Component if contains:
<template>, <script>, <style>Svelte Component if contains:
<script>, <style> in .svelte file$:)Detect testing framework from package.json:
Jest if contains:
"jest""@types/jest""ts-jest"Vitest if contains:
"vitest""@vitest/ui"Mocha + Chai if contains:
"mocha" + "chai"Playwright (E2E) if contains:
"@playwright/test"Cypress (E2E) if contains:
"cypress"Testing Library if contains:
"@testing-library/react""@testing-library/vue""@testing-library/user-event"If no test framework detected, see prompts/context/testing-framework-detection.md for fallback strategy and recommendations.
Check if tests already exist:
# Common test file patterns
Glob pattern="**/$COMPONENT_NAME.{test,spec}.{ts,tsx,js,jsx}"
Glob pattern="**/__tests__/$COMPONENT_NAME.*"
If tests exist:
If no tests:
Analyze the component to understand:
For React Components:
For API Endpoints:
For Utility Functions:
For Services:
Based on component type:
React Component Tests:
Unit Tests (70%):
Integration Tests (20%):
E2E Tests (10%):
API Endpoint Tests:
Unit Tests (70%):
Integration Tests (20%):
E2E Tests (10%):
Utility Function Tests:
Service Tests:
Unit Tests (70%):
Integration Tests (30%):
Create comprehensive test scenario list based on component type:
For React Components (28 unit tests minimum):
For API Endpoints (12 integration tests minimum):
For Utility Functions (10+ unit tests):
Note: Detailed test scenario checklists are available in the testing-strategy skill (activated in Phase 1).
Set coverage goals:
New Components: 80%+ coverage
Existing Components: Improve by 20%+
Critical Components: 90%+ coverage
Use Task tool to spawn test generation agent:
Task tool with:
- subagent_type: [select based on component type]
* React: frontend-developer
* API: backend-architect
* Utility: senior-developer
* Service: backend-architect
- description: "Generate tests for $ARGUMENTS"
- prompt: "Generate comprehensive test suite for component at: $ARGUMENTS
**Component Type**: [React Component / API Endpoint / Utility Function / Service]
**Test Framework**: [Jest / Vitest / Mocha + Chai]
**Test Library**: [Testing Library / Supertest / None]
**Component Code**:
[Full component code from Phase 1]
**Test Requirements**:
1. **Unit Tests** (70% of test suite):
[List of unit test scenarios from Phase 2]
2. **Integration Tests** (20% of test suite):
[List of integration test scenarios from Phase 2]
3. **E2E Tests** (10% of test suite):
[List of E2E test scenarios if applicable]
**Test Structure**:
```typescript
import { describe, it, expect } from '[framework]'
// Additional imports
describe('ComponentName', () => {
describe('Rendering', () => {
it('should render without crashing', () => {
// Test implementation
})
// More rendering tests
})
describe('Interactions', () => {
it('should handle click events', () => {
// Test implementation
})
// More interaction tests
})
// Additional test groups
})
Testing Best Practices:
Coverage Target: 80%+
Output: Create test file at: [test file path]
src/components/Button.tsxsrc/components/Button.test.tsxFollow existing test patterns in the codebase if any exist."
### Monitor Test Generation
The specialist will:
1. Analyze component structure
2. Generate test file with all scenarios
3. Add necessary imports and setup
4. Create test utilities if needed (factories, fixtures)
5. Write clear, maintainable tests
---
<!-- Component: prompts/quality-gates/test-execution.md -->
## Phase 4: Test Validation (5-10 min)
### Run Generated Tests
Execute the test suite using framework-specific commands (see `prompts/quality-gates/test-execution.md` for full details):
```bash
# Run specific test file
npm test -- $TEST_FILE_PATH
# Or with pattern matching
npm test -- --testPathPattern=$COMPONENT_NAME
# With coverage
npm test -- --coverage --testPathPattern=$COMPONENT_NAME
Expected Result: All tests should PASS
If tests FAIL: See prompts/quality-gates/test-execution.md for:
Generate coverage report:
# Jest/Vitest with coverage
npm test -- --coverage $TEST_FILE_PATH
Coverage Metrics:
Target: All metrics ≥ 80%
Coverage Analysis: See prompts/quality-gates/coverage-validation.md for:
Check generated tests for quality:
Good Tests:
Bad Tests to avoid:
Analyze coverage gaps (see prompts/quality-gates/coverage-validation.md for detailed analysis):
npm test -- --coverage --testPathPattern=$COMPONENT_NAME
Gap Assessment:
Common gaps: Error handling, edge cases, conditional branches, async callbacks, event handlers
Check tests for common anti-patterns:
Detailed examples and fixes: See the testing-strategy skill for comprehensive anti-pattern examples with good/bad code comparisons.
Create test documentation in .agency/tests/:
TIMESTAMP=$(date +%Y%m%d-%H%M%S)
COMPONENT_NAME=[extracted from $ARGUMENTS]
REPORT_FILE=".agency/tests/test-report-${COMPONENT_NAME}-${TIMESTAMP}.md"
mkdir -p .agency/tests
Report Structure (adapted from prompts/reporting/summary-template.md):
# Test Report: [Component Name]
**Date**: [Current date]
**Component**: $ARGUMENTS
**Test File**: [Generated test file path]
**Framework**: [Jest/Vitest/Mocha]
---
## Test Suite Summary
**Total Tests**: [X]
- Unit Tests: [Y] (70%)
- Integration Tests: [Z] (20%)
- E2E Tests: [W] (10%)
**Test Results**: ✅ ALL PASS / ❌ FAILURES
- Passed: [X]
- Failed: [Y]
- Skipped: [Z]
**Execution Time**: [X]ms
---
## Coverage Report
**Overall Coverage**: [X]%
**Detailed Metrics**:
- Line Coverage: [X]% (target: 80%)
- Branch Coverage: [X]% (target: 80%)
- Function Coverage: [X]% (target: 80%)
- Statement Coverage: [X]% (target: 80%)
**Coverage Status**: ✅ MEETS TARGET / ⚠️ BELOW TARGET
**Coverage Gaps**: See `prompts/quality-gates/coverage-validation.md` for gap analysis
---
## Test Scenarios Covered
[List test scenarios by category: Rendering, Interaction, State Management, Props, etc.]
---
## Test Quality Assessment
**Quality Score**: [X]/10
**Strengths**: [List strengths]
**Areas for Improvement**: [List improvements]
**Anti-Patterns Found**: [List or "None"]
---
## Test Files Created
**Test File**: `[test file path]` ([X] lines, [Y] tests)
**Supporting Files**: [List utilities, fixtures, factories if any]
---
## Next Steps
[Based on coverage and test results - see `prompts/reporting/summary-template.md` for recommendations format]
---
## Test Commands
```bash
# Run tests
npm test -- [test file name]
# Run with coverage
npm test -- --coverage [test file name]
# Watch mode
npm test -- --watch [test file name]
### Present Summary to User
Status: ✅ SUCCESS / ⚠️ PARTIAL / ❌ FAILED
Test Suite: [X] total ([Y] unit, [Z] integration, [W] E2E) Coverage: Line [X]%, Branch [Y]%, Function [Z]%, Statement [W]% Test Results: [X/Y passed] Quality Score: [X]/10
Test File: [path] Detailed Report: $REPORT_FILE
Next Steps: [Recommendations]
<!-- Component: prompts/progress/todo-initialization.md -->
### Update TodoWrite
Mark all test generation tasks as completed.
---
<!-- Component: prompts/context/testing-framework-detection.md -->
## Framework-Specific Patterns
**Reference**: See `prompts/context/testing-framework-detection.md` for complete framework-specific patterns and examples.
**Key Patterns**:
- **Jest + Testing Library (React)**: `render`, `screen`, `userEvent`, `waitFor`
- **Vitest**: Similar to Jest, imports from `vitest`
- **Supertest (API Testing)**: `request(app).get().expect()`
- **Playwright (E2E)**: `page.goto()`, `page.fill()`, `expect(page).toHaveURL()`
- **Cypress (E2E)**: `cy.visit()`, `cy.get()`, `cy.contains()`
- **pytest (Python)**: fixtures, parametrize, markers
See the testing framework detection component for detailed syntax and best practices per framework.
---
<!-- Component: prompts/error-handling/scope-detection-failure.md -->
## Error Handling
### If Component Not Found
Use error handling pattern from `prompts/error-handling/scope-detection-failure.md`:
❌ Unable to locate component: $ARGUMENTS
Searched locations:
Please provide:
### If Test Framework Not Detected
❌ No test framework found in package.json
See prompts/context/testing-framework-detection.md for recommendations.
Common frameworks:
Please install a test framework first, or specify which framework to use.
### If Generated Tests Fail
See `prompts/quality-gates/test-execution.md` for comprehensive failure analysis:
⚠️ [X] generated tests are failing
Failure Analysis: See prompts/quality-gates/test-execution.md for:
Immediate Actions:
---
## Best Practices
**Core Principles** (from `testing-strategy` skill):
1. **Test Pyramid**: 70% unit, 20% integration, 10% E2E
2. **Coverage Target**: 80%+ (see `prompts/quality-gates/coverage-validation.md`)
3. **Test Behavior**: What users see, not implementation details
4. **Fast Tests**: Unit tests in milliseconds
5. **Independent Tests**: No shared state between tests
6. **Descriptive Names**: "should..." format describing expected behavior
7. **AAA Pattern**: Arrange, Act, Assert structure
8. **Mock External**: Mock HTTP, databases, external dependencies
**Detailed best practices**: Available in `testing-strategy` skill (activated in Phase 1).
---
## Example Usage
```bash
# Generate tests for a React component
/agency:test src/components/Button.tsx
# Generate tests for an API endpoint
/agency:test src/api/users.ts
# Generate tests for a utility function
/agency:test src/lib/formatDate.ts
# Using component name only (will search)
/agency:test Button
/agency:work [issue] - Full workflow with testing included/agency:implement [plan] - Implementation includes test validation/agency:review [pr] - Reviews test coverage and quality