[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D7Y1F95AHTF88HP1THC1PK":3,"skill-same:01M7D7Y1F95AHTF88HP1THC1PK":90},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":68,"commitSha":69,"skillDirectory":70,"forksCount":14,"repositoryHtmlUrl":71,"repositoryHomepageUrl":6,"ownerHtmlUrl":72,"ownerBlogUrl":73,"ownerDescription":74,"updatedAt":75,"install":76,"resources":89},"01M7D7Y1F95AHTF88HP1THC1PK","AI Test Generation Patterns",null,"Systematic patterns for prompting AI coding agents to generate high-quality tests including prompt engineering for test creation, coverage-driven generation, mutation-aware testing, and review checklists for AI-generated test code.","GrupoANDevelopment-m\u002Falberto-ai","GrupoANDevelopment-m","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F257455179?v=4","01M7D69X2N2KEVN0SJF6WGM6SH","Antônio  Ndombe","01M7D69X3P5JTT8H8S904N3888",0,"MIT","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fai-test-generation\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: AI Test Generation Patterns\ndescription: Systematic patterns for prompting AI coding agents to generate high-quality tests including prompt engineering for test creation, coverage-driven generation, mutation-aware testing, and review checklists for AI-generated test code.\nversion: 1.0.0\nauthor: thetestingacademy\nlicense: MIT\ntags: [ai-testing, test-generation, prompt-engineering, coverage-driven, mutation-testing, code-review, automated-testing, llm-testing, ai-code-generation]\ntestingTypes: [unit, integration, e2e, api]\nframeworks: [vitest, jest, playwright, pytest, cypress]\nlanguages: [typescript, javascript, python]\ndomains: [web, backend, api, mobile]\nagents: [claude-code, cursor, github-copilot, windsurf, codex, aider, continue, cline, zed, bolt, gemini-cli, amp]\n---\n\n# AI Test Generation Patterns Skill\n\nYou are an expert in using AI coding agents to generate high-quality test code. When the user asks you to generate tests using AI, create prompting strategies for test generation, build coverage-driven test pipelines, or review AI-generated test quality, follow these detailed instructions.\n\n## Core Principles\n\n1. **Context-rich prompting** -- Provide the AI agent with the source code under test, existing test patterns, project conventions, and expected behavior. More context produces better tests.\n2. **Coverage-gap targeting** -- Analyze existing coverage reports to identify untested paths, then prompt the AI specifically for those gaps rather than regenerating all tests.\n3. **Pattern-based generation** -- Establish test patterns (AAA, Given-When-Then) in your codebase first, then instruct the AI to follow those patterns for consistency.\n4. **Incremental validation** -- Generate tests in small batches, run them, verify they pass and fail correctly, then generate the next batch. Never generate an entire suite without validation.\n5. **Mutation-aware testing** -- Use mutation testing results to identify weak test assertions and prompt the AI to strengthen them with more specific checks.\n6. **Human review gates** -- Every AI-generated test must pass human review. AI excels at generating structure but can miss business logic nuances.\n7. **Prompt versioning** -- Version your generation prompts alongside your code. When test patterns change, update prompts accordingly.\n\n## Project Structure\n\n```\ntest-generation\u002F\n  prompts\u002F\n    unit-test-prompt.md\n    integration-test-prompt.md\n    e2e-test-prompt.md\n    api-test-prompt.md\n    edge-case-prompt.md\n  templates\u002F\n    vitest-unit.template.ts\n    playwright-e2e.template.ts\n    api-test.template.ts\n  analyzers\u002F\n    coverage-analyzer.ts\n    mutation-analyzer.ts\n    complexity-analyzer.ts\n  generators\u002F\n    prompt-builder.ts\n    batch-generator.ts\n    test-validator.ts\n  review\u002F\n    quality-checker.ts\n    anti-pattern-detector.ts\n    assertion-strength-analyzer.ts\n  config\u002F\n    generation-config.ts\n    model-config.ts\n```\n\n## Prompt Builder for Test Generation\n\n```typescript\n\u002F\u002F test-generation\u002Fgenerators\u002Fprompt-builder.ts\nexport interface PromptContext {\n  sourceCode: string;\n  sourceFile: string;\n  existingTests?: string;\n  coverageReport?: string;\n  testPatterns?: string;\n  projectConventions?: string;\n  focusAreas?: string[];\n}\n\nexport interface GenerationPrompt {\n  system: string;\n  user: string;\n  expectedFormat: string;\n}\n\nexport class TestPromptBuilder {\n  buildUnitTestPrompt(context: PromptContext): GenerationPrompt {\n    const system = `You are a senior test engineer generating unit tests.\nFollow these rules strictly:\n1. Use the Arrange-Act-Assert (AAA) pattern for every test\n2. Name tests using the pattern: \"should [expected behavior] when [condition]\"\n3. Test one behavior per test function\n4. Mock all external dependencies\n5. Include edge cases: null, undefined, empty strings, boundary values\n6. Include error cases: invalid inputs, thrown exceptions\n7. Use TypeScript strict types for all test code\n8. Do NOT use any as a type\n9. Generate descriptive assertion messages\n10. Group related tests in describe blocks`;\n\n    const user = this.buildUserPrompt(context, 'unit');\n\n    return {\n      system,\n      user,\n      expectedFormat: 'typescript',\n    };\n  }\n\n  buildIntegrationTestPrompt(context: PromptContext): GenerationPrompt {\n    const system = `You are a senior test engineer generating integration tests.\nFollow these rules strictly:\n1. Test the interaction between two or more components\n2. Use real implementations for the components under test\n3. Mock only external services (APIs, databases, file systems)\n4. Set up realistic test data that represents production scenarios\n5. Test both success and failure paths for each integration point\n6. Verify side effects (database writes, cache updates, event emissions)\n7. Clean up test data in afterEach\u002FafterAll hooks\n8. Test timeout and retry behavior for network calls\n9. Use factories or builders for complex test data\n10. Assert on the complete response shape, not just one field`;\n\n    const user = this.buildUserPrompt(context, 'integration');\n\n    return {\n      system,\n      user,\n      expectedFormat: 'typescript',\n    };\n  }\n\n  buildE2ETestPrompt(context: PromptContext): GenerationPrompt {\n    const system = `You are a senior test engineer generating Playwright E2E tests.\nFollow these rules strictly:\n1. Use Page Object Model pattern\n2. Prefer getByRole, getByTestId, getByLabel over CSS selectors\n3. Use web-first assertions: expect(locator).toBeVisible()\n4. Never use page.waitForTimeout() - use proper wait conditions\n5. Handle loading states explicitly\n6. Test the complete user journey, not individual UI elements\n7. Include accessibility assertions where relevant\n8. Clean up test state (logout, clear data) in afterEach\n9. Capture screenshots on failure for debugging\n10. Test on at least desktop and mobile viewports`;\n\n    const user = this.buildUserPrompt(context, 'e2e');\n\n    return {\n      system,\n      user,\n      expectedFormat: 'typescript',\n    };\n  }\n\n  private buildUserPrompt(context: PromptContext, testType: string): string {\n    let prompt = `Generate ${testType} tests for the following code:\\n\\n`;\n    prompt += `### Source File: ${context.sourceFile}\\n`;\n    prompt += `\\`\\`\\`typescript\\n${context.sourceCode}\\n\\`\\`\\`\\n\\n`;\n\n    if (context.existingTests) {\n      prompt += `### Existing Tests (follow this pattern):\\n`;\n      prompt += `\\`\\`\\`typescript\\n${context.existingTests}\\n\\`\\`\\`\\n\\n`;\n    }\n\n    if (context.coverageReport) {\n      prompt += `### Coverage Gaps (focus on these):\\n${context.coverageReport}\\n\\n`;\n    }\n\n    if (context.projectConventions) {\n      prompt += `### Project Conventions:\\n${context.projectConventions}\\n\\n`;\n    }\n\n    if (context.focusAreas?.length) {\n      prompt += `### Focus Areas:\\n`;\n      for (const area of context.focusAreas) {\n        prompt += `- ${area}\\n`;\n      }\n      prompt += '\\n';\n    }\n\n    prompt += `Generate a complete test file. Include all imports. Do not skip any test cases.`;\n\n    return prompt;\n  }\n}\n```\n\n## Coverage-Driven Generation\n\n```typescript\n\u002F\u002F test-generation\u002Fanalyzers\u002Fcoverage-analyzer.ts\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\n\nexport interface CoverageGap {\n  file: string;\n  uncoveredLines: number[];\n  uncoveredBranches: Array\u003C{ line: number; branch: string }>;\n  uncoveredFunctions: string[];\n  currentCoverage: number;\n  targetCoverage: number;\n  priority: 'critical' | 'high' | 'medium' | 'low';\n}\n\nexport class CoverageAnalyzer {\n  analyzeCoverageReport(reportPath: string): CoverageGap[] {\n    if (!existsSync(reportPath)) {\n      throw new Error(`Coverage report not found: ${reportPath}`);\n    }\n\n    const report = JSON.parse(readFileSync(reportPath, 'utf-8'));\n    const gaps: CoverageGap[] = [];\n\n    for (const [file, data] of Object.entries(report) as [string, any][]) {\n      const uncoveredLines = this.findUncoveredLines(data.s);\n      const uncoveredBranches = this.findUncoveredBranches(data.b, data.branchMap);\n      const uncoveredFunctions = this.findUncoveredFunctions(data.f, data.fnMap);\n\n      if (uncoveredLines.length > 0 || uncoveredBranches.length > 0 || uncoveredFunctions.length > 0) {\n        const totalStatements = Object.keys(data.s).length;\n        const coveredStatements = Object.values(data.s as Record\u003Cstring, number>).filter((v) => v > 0).length;\n        const currentCoverage = totalStatements > 0 ? (coveredStatements \u002F totalStatements) * 100 : 0;\n\n        gaps.push({\n          file,\n          uncoveredLines,\n          uncoveredBranches,\n          uncoveredFunctions,\n          currentCoverage: Math.round(currentCoverage),\n          targetCoverage: 80,\n          priority: this.calculatePriority(file, currentCoverage, uncoveredFunctions),\n        });\n      }\n    }\n\n    return gaps.sort((a, b) => {\n      const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };\n      return priorityOrder[a.priority] - priorityOrder[b.priority];\n    });\n  }\n\n  buildCoveragePrompt(gap: CoverageGap): string {\n    let prompt = `The following areas in ${gap.file} need test coverage:\\n\\n`;\n\n    if (gap.uncoveredFunctions.length > 0) {\n      prompt += `**Uncovered functions:**\\n`;\n      for (const fn of gap.uncoveredFunctions) {\n        prompt += `- ${fn}\\n`;\n      }\n      prompt += '\\n';\n    }\n\n    if (gap.uncoveredBranches.length > 0) {\n      prompt += `**Uncovered branches:**\\n`;\n      for (const branch of gap.uncoveredBranches) {\n        prompt += `- Line ${branch.line}: ${branch.branch}\\n`;\n      }\n      prompt += '\\n';\n    }\n\n    if (gap.uncoveredLines.length > 0) {\n      prompt += `**Uncovered lines:** ${gap.uncoveredLines.join(', ')}\\n\\n`;\n    }\n\n    prompt += `Current coverage: ${gap.currentCoverage}%. Target: ${gap.targetCoverage}%.\\n`;\n    prompt += `Focus on testing the uncovered functions and branches above.`;\n\n    return prompt;\n  }\n\n  private findUncoveredLines(statements: Record\u003Cstring, number>): number[] {\n    return Object.entries(statements)\n      .filter(([, count]) => count === 0)\n      .map(([id]) => parseInt(id, 10));\n  }\n\n  private findUncoveredBranches(\n    branches: Record\u003Cstring, number[]>,\n    branchMap: Record\u003Cstring, any>\n  ): Array\u003C{ line: number; branch: string }> {\n    const uncovered: Array\u003C{ line: number; branch: string }> = [];\n    for (const [id, counts] of Object.entries(branches)) {\n      counts.forEach((count, index) => {\n        if (count === 0 && branchMap[id]) {\n          uncovered.push({\n            line: branchMap[id].loc?.start?.line || 0,\n            branch: `Branch ${index} of ${branchMap[id].type}`,\n          });\n        }\n      });\n    }\n    return uncovered;\n  }\n\n  private findUncoveredFunctions(\n    functions: Record\u003Cstring, number>,\n    fnMap: Record\u003Cstring, any>\n  ): string[] {\n    return Object.entries(functions)\n      .filter(([, count]) => count === 0)\n      .map(([id]) => fnMap[id]?.name || `anonymous@${id}`)\n      .filter((name) => name !== 'anonymous@undefined');\n  }\n\n  private calculatePriority(\n    file: string,\n    coverage: number,\n    uncoveredFunctions: string[]\n  ): CoverageGap['priority'] {\n    if (file.includes('auth') || file.includes('security') || file.includes('payment')) {\n      return 'critical';\n    }\n    if (coverage \u003C 30) return 'high';\n    if (coverage \u003C 60 || uncoveredFunctions.length > 5) return 'medium';\n    return 'low';\n  }\n}\n```\n\n## Test Quality Checker\n\n```typescript\n\u002F\u002F test-generation\u002Freview\u002Fquality-checker.ts\nexport interface QualityReport {\n  score: number;\n  issues: QualityIssue[];\n  suggestions: string[];\n  passesReview: boolean;\n}\n\nexport interface QualityIssue {\n  severity: 'error' | 'warning' | 'info';\n  message: string;\n  line?: number;\n  rule: string;\n}\n\nexport class TestQualityChecker {\n  check(testCode: string): QualityReport {\n    const issues: QualityIssue[] = [];\n    const suggestions: string[] = [];\n\n    \u002F\u002F Check for common anti-patterns\n    this.checkForEmptyTests(testCode, issues);\n    this.checkForWeakAssertions(testCode, issues);\n    this.checkForHardcodedValues(testCode, issues);\n    this.checkForMissingErrorTests(testCode, issues);\n    this.checkForProperMocking(testCode, issues);\n    this.checkForTestIsolation(testCode, issues);\n    this.checkForDescriptiveNames(testCode, issues);\n    this.checkForAsyncHandling(testCode, issues);\n    this.checkForMagicNumbers(testCode, issues);\n    this.checkForProperCleanup(testCode, issues);\n\n    \u002F\u002F Generate suggestions\n    if (!testCode.includes('describe(')) {\n      suggestions.push('Group related tests in describe blocks for better organization');\n    }\n    if (!testCode.includes('beforeEach') && !testCode.includes('beforeAll')) {\n      suggestions.push('Consider using setup hooks for common test initialization');\n    }\n    if ((testCode.match(\u002Fit\\(\u002Fg) || []).length \u003C 3) {\n      suggestions.push('Consider adding more test cases for better coverage');\n    }\n\n    const errorCount = issues.filter((i) => i.severity === 'error').length;\n    const warningCount = issues.filter((i) => i.severity === 'warning').length;\n    const score = Math.max(0, 100 - errorCount * 20 - warningCount * 5);\n\n    return {\n      score,\n      issues,\n      suggestions,\n      passesReview: score >= 60 && errorCount === 0,\n    };\n  }\n\n  private checkForEmptyTests(code: string, issues: QualityIssue[]): void {\n    const emptyTestRegex = \u002Fit\\([^)]+,\\s*(?:async\\s*)?\\(\\)\\s*=>\\s*\\{\\s*\\}\\)\u002Fg;\n    const matches = code.match(emptyTestRegex);\n    if (matches) {\n      issues.push({\n        severity: 'error',\n        message: `Found ${matches.length} empty test(s) with no assertions`,\n        rule: 'no-empty-tests',\n      });\n    }\n  }\n\n  private checkForWeakAssertions(code: string, issues: QualityIssue[]): void {\n    const weakPatterns = [\n      { pattern: \u002Fexpect\\(\\w+\\)\\.toBeTruthy\\(\\)\u002Fg, message: 'toBeTruthy() is too permissive - use specific assertion' },\n      { pattern: \u002Fexpect\\(\\w+\\)\\.toBeDefined\\(\\)\u002Fg, message: 'toBeDefined() only checks not-undefined - verify actual value' },\n      { pattern: \u002Fexpect\\(\\w+\\)\\.not\\.toBeNull\\(\\)\u002Fg, message: 'not.toBeNull() is weak - assert the expected value' },\n    ];\n\n    for (const { pattern, message } of weakPatterns) {\n      const matches = code.match(pattern);\n      if (matches && matches.length > 2) {\n        issues.push({ severity: 'warning', message: `${message} (found ${matches.length} instances)`, rule: 'strong-assertions' });\n      }\n    }\n  }\n\n  private checkForHardcodedValues(code: string, issues: QualityIssue[]): void {\n    if (code.includes('localhost:') && !code.includes('process.env')) {\n      issues.push({\n        severity: 'warning',\n        message: 'Hardcoded localhost URLs found. Use environment variables or config.',\n        rule: 'no-hardcoded-urls',\n      });\n    }\n  }\n\n  private checkForMissingErrorTests(code: string, issues: QualityIssue[]): void {\n    const hasErrorTests = code.includes('toThrow') || code.includes('rejects') || code.includes('error') || code.includes('invalid');\n    if (!hasErrorTests) {\n      issues.push({\n        severity: 'warning',\n        message: 'No error handling tests found. Add tests for invalid inputs and error cases.',\n        rule: 'error-coverage',\n      });\n    }\n  }\n\n  private checkForProperMocking(code: string, issues: QualityIssue[]): void {\n    if (code.includes('vi.fn()') || code.includes('jest.fn()')) {\n      const mockCalls = (code.match(\u002Fvi\\.fn\\(\\)|jest\\.fn\\(\\)\u002Fg) || []).length;\n      const mockVerifications = (code.match(\u002FtoHaveBeenCalled|toHaveBeenCalledWith\u002Fg) || []).length;\n      if (mockCalls > mockVerifications * 2) {\n        issues.push({\n          severity: 'warning',\n          message: 'Mocks created but not all verified. Ensure mocks are asserted.',\n          rule: 'verify-mocks',\n        });\n      }\n    }\n  }\n\n  private checkForTestIsolation(code: string, issues: QualityIssue[]): void {\n    if (code.includes('let ') && !code.includes('beforeEach')) {\n      const mutableVars = (code.match(\u002F^\\s*let\\s+\\w+\u002Fgm) || []).length;\n      if (mutableVars > 2) {\n        issues.push({\n          severity: 'warning',\n          message: 'Mutable variables without beforeEach reset. Tests may not be isolated.',\n          rule: 'test-isolation',\n        });\n      }\n    }\n  }\n\n  private checkForDescriptiveNames(code: string, issues: QualityIssue[]): void {\n    const shortTests = code.match(\u002Fit\\(['\"]([^'\"]{1,15})['\"]\u002Fg);\n    if (shortTests && shortTests.length > 0) {\n      issues.push({\n        severity: 'info',\n        message: `${shortTests.length} test(s) have very short names. Use descriptive names explaining expected behavior.`,\n        rule: 'descriptive-names',\n      });\n    }\n  }\n\n  private checkForAsyncHandling(code: string, issues: QualityIssue[]): void {\n    if (code.includes('Promise') || code.includes('async')) {\n      if (!code.includes('await') && !code.includes('.resolves') && !code.includes('.rejects')) {\n        issues.push({\n          severity: 'error',\n          message: 'Async code detected but no await or promise assertions found. Tests may not wait for async operations.',\n          rule: 'async-handling',\n        });\n      }\n    }\n  }\n\n  private checkForMagicNumbers(code: string, issues: QualityIssue[]): void {\n    const magicNumbers = code.match(\u002Fexpect\\([^)]+\\)\\.\\w+\\((?!['\"`true|false|null|undefined|0|1|-1)\\d{2,}\\)\u002Fg);\n    if (magicNumbers && magicNumbers.length > 3) {\n      issues.push({\n        severity: 'info',\n        message: 'Multiple magic numbers in assertions. Consider extracting to named constants.',\n        rule: 'no-magic-numbers',\n      });\n    }\n  }\n\n  private checkForProperCleanup(code: string, issues: QualityIssue[]): void {\n    const hasSetup = code.includes('beforeEach') || code.includes('beforeAll');\n    const hasCleanup = code.includes('afterEach') || code.includes('afterAll');\n    if (hasSetup && !hasCleanup) {\n      issues.push({\n        severity: 'warning',\n        message: 'Setup hooks found without cleanup hooks. Consider adding afterEach\u002FafterAll for cleanup.',\n        rule: 'proper-cleanup',\n      });\n    }\n  }\n}\n```\n\n## Batch Test Generator\n\n```typescript\n\u002F\u002F test-generation\u002Fgenerators\u002Fbatch-generator.ts\nimport Anthropic from '@anthropic-ai\u002Fsdk';\nimport { TestPromptBuilder, PromptContext } from '.\u002Fprompt-builder';\nimport { TestQualityChecker, QualityReport } from '..\u002Freview\u002Fquality-checker';\nimport { readFileSync } from 'fs';\n\nexport interface BatchResult {\n  file: string;\n  testCode: string;\n  quality: QualityReport;\n  tokensUsed: number;\n  generationTimeMs: number;\n}\n\nexport class BatchTestGenerator {\n  private client: Anthropic;\n  private promptBuilder: TestPromptBuilder;\n  private qualityChecker: TestQualityChecker;\n\n  constructor() {\n    this.client = new Anthropic();\n    this.promptBuilder = new TestPromptBuilder();\n    this.qualityChecker = new TestQualityChecker();\n  }\n\n  async generateBatch(\n    files: string[],\n    testType: 'unit' | 'integration' | 'e2e' | 'api',\n    conventions?: string\n  ): Promise\u003CBatchResult[]> {\n    const results: BatchResult[] = [];\n\n    for (const file of files) {\n      const sourceCode = readFileSync(file, 'utf-8');\n      const context: PromptContext = {\n        sourceCode,\n        sourceFile: file,\n        projectConventions: conventions,\n      };\n\n      const prompt = testType === 'unit'\n        ? this.promptBuilder.buildUnitTestPrompt(context)\n        : testType === 'e2e'\n          ? this.promptBuilder.buildE2ETestPrompt(context)\n          : this.promptBuilder.buildIntegrationTestPrompt(context);\n\n      const startTime = Date.now();\n\n      const response = await this.client.messages.create({\n        model: 'claude-sonnet-4-20250514',\n        max_tokens: 4096,\n        temperature: 0,\n        system: prompt.system,\n        messages: [{ role: 'user', content: prompt.user }],\n      });\n\n      const text = response.content[0].type === 'text' ? response.content[0].text : '';\n      const codeMatch = text.match(\u002F```typescript\\n([\\s\\S]*?)```\u002F);\n      const testCode = codeMatch ? codeMatch[1] : text;\n\n      const quality = this.qualityChecker.check(testCode);\n      const tokensUsed = (response.usage?.input_tokens || 0) + (response.usage?.output_tokens || 0);\n\n      results.push({\n        file,\n        testCode: testCode.trim(),\n        quality,\n        tokensUsed,\n        generationTimeMs: Date.now() - startTime,\n      });\n    }\n\n    return results;\n  }\n}\n```\n\n## Example: Using the Generation Pipeline\n\n```typescript\n\u002F\u002F example-usage.ts\nimport { TestPromptBuilder } from '.\u002Fgenerators\u002Fprompt-builder';\nimport { CoverageAnalyzer } from '.\u002Fanalyzers\u002Fcoverage-analyzer';\nimport { BatchTestGenerator } from '.\u002Fgenerators\u002Fbatch-generator';\n\nasync function generateTestsForProject() {\n  \u002F\u002F Step 1: Analyze coverage gaps\n  const coverageAnalyzer = new CoverageAnalyzer();\n  const gaps = coverageAnalyzer.analyzeCoverageReport('.\u002Fcoverage\u002Fcoverage-final.json');\n\n  console.log(`Found ${gaps.length} coverage gaps`);\n  const criticalGaps = gaps.filter((g) => g.priority === 'critical' || g.priority === 'high');\n  console.log(`${criticalGaps.length} critical\u002Fhigh priority gaps`);\n\n  \u002F\u002F Step 2: Generate tests for high-priority gaps\n  const generator = new BatchTestGenerator();\n  const results = await generator.generateBatch(\n    criticalGaps.map((g) => g.file),\n    'unit',\n    'Use vitest, follow AAA pattern, use vi.mock for dependencies'\n  );\n\n  \u002F\u002F Step 3: Review quality\n  for (const result of results) {\n    console.log(`${result.file}: Score ${result.quality.score}\u002F100`);\n    if (result.quality.passesReview) {\n      console.log('  PASS - Ready for human review');\n    } else {\n      console.log('  NEEDS WORK:', result.quality.issues.map((i) => i.message).join('; '));\n    }\n  }\n}\n```\n\n## Best Practices\n\n1. **Provide the source code in every generation prompt** -- AI agents cannot infer implementation details from function names alone. Always include the full source code being tested.\n2. **Include existing test patterns in context** -- Show the agent 2-3 examples of your existing tests so it matches your project's style and conventions.\n3. **Generate tests incrementally, not all at once** -- Generate tests for one file at a time, validate them, then move to the next. Batch generation without validation produces low-quality tests.\n4. **Use coverage reports to target generation** -- Do not regenerate tests that already exist. Analyze coverage gaps and generate only for uncovered code paths.\n5. **Review AI-generated assertions carefully** -- AI agents often generate assertions that are too loose (toBeDefined) or test implementation details rather than behavior.\n6. **Set up automated quality checks** -- Run the quality checker on all generated tests before human review to catch common anti-patterns automatically.\n7. **Keep prompts under version control** -- Store generation prompts in your repository so the entire team uses consistent prompts and changes are tracked.\n8. **Test the tests with mutation testing** -- After generating tests, run mutation testing to verify the generated assertions actually detect bugs.\n9. **Establish a generation budget** -- Set a maximum number of tokens or dollars per generation session to prevent runaway costs.\n10. **Document which tests are AI-generated** -- Add a comment or metadata to generated tests so reviewers know to scrutinize them more carefully.\n\n## Anti-Patterns\n\n1. **Generating tests without source code context** -- Prompting with only function signatures produces tests that compile but do not meaningfully verify behavior.\n2. **Accepting all generated tests without review** -- AI-generated tests can have incorrect assertions, hardcoded values, and logic errors. Always review before committing.\n3. **Using temperature > 0 for test generation** -- Non-deterministic generation produces inconsistent results. Use temperature 0 for reproducible test generation.\n4. **Generating tests for trivial code** -- Do not waste tokens generating tests for simple getters, setters, or pass-through functions. Focus on complex logic.\n5. **Ignoring the quality checker output** -- Automated quality checks catch 80% of common issues. Skipping them leads to low-quality tests entering the codebase.\n6. **Regenerating existing tests** -- Before generating, check if tests already exist. Duplicate tests waste resources and create maintenance burden.\n7. **Using AI-generated tests as the sole quality gate** -- AI-generated tests complement but do not replace human-written critical path tests.\n8. **Not validating that generated tests actually run** -- A test that does not compile or throws at runtime provides zero value. Always execute generated tests before committing.\n9. **Generating E2E tests for unstable UIs** -- If the UI is changing rapidly, generated E2E tests will break immediately. Wait for UI stabilization.\n10. **Trusting AI-generated mock implementations** -- AI agents often create mocks that do not accurately represent the real dependency behavior. Verify mocks against actual service contracts.\n","# AI Test Generation Patterns Skill\n\nYou are an expert in using AI coding agents to generate high-quality test code. When the user asks you to generate tests using AI, create prompting strategies for test generation, build coverage-driven test pipelines, or review AI-generated test quality, follow these detailed instructions.\n\n## Core Principles\n\n1. **Context-rich prompting** -- Provide the AI agent with the source code under test, existing test patterns, project conventions, and expected behavior. More context produces better tests.\n2. **Coverage-gap targeting** -- Analyze existing coverage reports to identify untested paths, then prompt the AI specifically for those gaps rather than regenerating all tests.\n3. **Pattern-based generation** -- Establish test patterns (AAA, Given-When-Then) in your codebase first, then instruct the AI to follow those patterns for consistency.\n4. **Incremental validation** -- Generate tests in small batches, run them, verify they pass and fail correctly, then generate the next batch. Never generate an entire suite without validation.\n5. **Mutation-aware testing** -- Use mutation testing results to identify weak test assertions and prompt the AI to strengthen them with more specific checks.\n6. **Human review gates** -- Every AI-generated test must pass human review. AI excels at generating structure but can miss business logic nuances.\n7. **Prompt versioning** -- Version your generation prompts alongside your code. When test patterns change, update prompts accordingly.\n\n## Project Structure\n\n```\ntest-generation\u002F\n  prompts\u002F\n    unit-test-prompt.md\n    integration-test-prompt.md\n    e2e-test-prompt.md\n    api-test-prompt.md\n    edge-case-prompt.md\n  templates\u002F\n    vitest-unit.template.ts\n    playwright-e2e.template.ts\n    api-test.template.ts\n  analyzers\u002F\n    coverage-analyzer.ts\n    mutation-analyzer.ts\n    complexity-analyzer.ts\n  generators\u002F\n    prompt-builder.ts\n    batch-generator.ts\n    test-validator.ts\n  review\u002F\n    quality-checker.ts\n    anti-pattern-detector.ts\n    assertion-strength-analyzer.ts\n  config\u002F\n    generation-config.ts\n    model-config.ts\n```\n\n## Prompt Builder for Test Generation\n\n```typescript\n\u002F\u002F test-generation\u002Fgenerators\u002Fprompt-builder.ts\nexport interface PromptContext {\n  sourceCode: string;\n  sourceFile: string;\n  existingTests?: string;\n  coverageReport?: string;\n  testPatterns?: string;\n  projectConventions?: string;\n  focusAreas?: string[];\n}\n\nexport interface GenerationPrompt {\n  system: string;\n  user: string;\n  expectedFormat: string;\n}\n\nexport class TestPromptBuilder {\n  buildUnitTestPrompt(context: PromptContext): GenerationPrompt {\n    const system = `You are a senior test engineer generating unit tests.\nFollow these rules strictly:\n1. Use the Arrange-Act-Assert (AAA) pattern for every test\n2. Name tests using the pattern: \"should [expected behavior] when [condition]\"\n3. Test one behavior per test function\n4. Mock all external dependencies\n5. Include edge cases: null, undefined, empty strings, boundary values\n6. Include error cases: invalid inputs, thrown exceptions\n7. Use TypeScript strict types for all test code\n8. Do NOT use any as a type\n9. Generate descriptive assertion messages\n10. Group related tests in describe blocks`;\n\n    const user = this.buildUserPrompt(context, 'unit');\n\n    return {\n      system,\n      user,\n      expectedFormat: 'typescript',\n    };\n  }\n\n  buildIntegrationTestPrompt(context: PromptContext): GenerationPrompt {\n    const system = `You are a senior test engineer generating integration tests.\nFollow these rules strictly:\n1. Test the interaction between two or more components\n2. Use real implementations for the components under test\n3. Mock only external services (APIs, databases, file systems)\n4. Set up realistic test data that represents production scenarios\n5. Test both success and failure paths for each integration point\n6. Verify side effects (database writes, cache updates, event emissions)\n7. Clean up test data in afterEach\u002FafterAll hooks\n8. Test timeout and retry behavior for network calls\n9. Use factories or builders for complex test data\n10. Assert on the complete response shape, not just one field`;\n\n    const user = this.buildUserPrompt(context, 'integration');\n\n    return {\n      system,\n      user,\n      expectedFormat: 'typescript',\n    };\n  }\n\n  buildE2ETestPrompt(context: PromptContext): GenerationPrompt {\n    const system = `You are a senior test engineer generating Playwright E2E tests.\nFollow these rules strictly:\n1. Use Page Object Model pattern\n2. Prefer getByRole, getByTestId, getByLabel over CSS selectors\n3. Use web-first assertions: expect(locator).toBeVisible()\n4. Never use page.waitForTimeout() - use proper wait conditions\n5. Handle loading states explicitly\n6. Test the complete user journey, not individual UI elements\n7. Include accessibility assertions where relevant\n8. Clean up test state (logout, clear data) in afterEach\n9. Capture screenshots on failure for debugging\n10. Test on at least desktop and mobile viewports`;\n\n    const user = this.buildUserPrompt(context, 'e2e');\n\n    return {\n      system,\n      user,\n      expectedFormat: 'typescript',\n    };\n  }\n\n  private buildUserPrompt(context: PromptContext, testType: string): string {\n    let prompt = `Generate ${testType} tests for the following code:\\n\\n`;\n    prompt += `### Source File: ${context.sourceFile}\\n`;\n    prompt += `\\`\\`\\`typescript\\n${context.sourceCode}\\n\\`\\`\\`\\n\\n`;\n\n    if (context.existingTests) {\n      prompt += `### Existing Tests (follow this pattern):\\n`;\n      prompt += `\\`\\`\\`typescript\\n${context.existingTests}\\n\\`\\`\\`\\n\\n`;\n    }\n\n    if (context.coverageReport) {\n      prompt += `### Coverage Gaps (focus on these):\\n${context.coverageReport}\\n\\n`;\n    }\n\n    if (context.projectConventions) {\n      prompt += `### Project Conventions:\\n${context.projectConventions}\\n\\n`;\n    }\n\n    if (context.focusAreas?.length) {\n      prompt += `### Focus Areas:\\n`;\n      for (const area of context.focusAreas) {\n        prompt += `- ${area}\\n`;\n      }\n      prompt += '\\n';\n    }\n\n    prompt += `Generate a complete test file. Include all imports. Do not skip any test cases.`;\n\n    return prompt;\n  }\n}\n```\n\n## Coverage-Driven Generation\n\n```typescript\n\u002F\u002F test-generation\u002Fanalyzers\u002Fcoverage-analyzer.ts\nimport { readFileSync, existsSync } from 'fs';\nimport { join } from 'path';\n\nexport interface CoverageGap {\n  file: string;\n  uncoveredLines: number[];\n  uncoveredBranches: Array\u003C{ line: number; branch: string }>;\n  uncoveredFunctions: string[];\n  currentCoverage: number;\n  targetCoverage: number;\n  priority: 'critical' | 'high' | 'medium' | 'low';\n}\n\nexport class CoverageAnalyzer {\n  analyzeCoverageReport(reportPath: string): CoverageGap[] {\n    if (!existsSync(reportPath)) {\n      throw new Error(`Coverage report not found: ${reportPath}`);\n    }\n\n    const report = JSON.parse(readFileSync(reportPath, 'utf-8'));\n    const gaps: CoverageGap[] = [];\n\n    for (const [file, data] of Object.entries(report) as [string, any][]) {\n      const uncoveredLines = this.findUncoveredLines(data.s);\n      const uncoveredBranches = this.findUncoveredBranches(data.b, data.branchMap);\n      const uncoveredFunctions = this.findUncoveredFunctions(data.f, data.fnMap);\n\n      if (uncoveredLines.length > 0 || uncoveredBranches.length > 0 || uncoveredFunctions.length > 0) {\n        const totalStatements = Object.keys(data.s).length;\n        const coveredStatements = Object.values(data.s as Record\u003Cstring, number>).filter((v) => v > 0).length;\n        const currentCoverage = totalStatements > 0 ? (coveredStatements \u002F totalStatements) * 100 : 0;\n\n        gaps.push({\n          file,\n          uncoveredLines,\n          uncoveredBranches,\n          uncoveredFunctions,\n          currentCoverage: Math.round(currentCoverage),\n          targetCoverage: 80,\n          priority: this.calculatePriority(file, currentCoverage, uncoveredFunctions),\n        });\n      }\n    }\n\n    return gaps.sort((a, b) => {\n      const priorityOrder = { critical: 0, high: 1, medium: 2, low: 3 };\n      return priorityOrder[a.priority] - priorityOrder[b.priority];\n    });\n  }\n\n  buildCoveragePrompt(gap: CoverageGap): string {\n    let prompt = `The following areas in ${gap.file} need test coverage:\\n\\n`;\n\n    if (gap.uncoveredFunctions.length > 0) {\n      prompt += `**Uncovered functions:**\\n`;\n      for (const fn of gap.uncoveredFunctions) {\n        prompt += `- ${fn}\\n`;\n      }\n      prompt += '\\n';\n    }\n\n    if (gap.uncoveredBranches.length > 0) {\n      prompt += `**Uncovered branches:**\\n`;\n      for (const branch of gap.uncoveredBranches) {\n        prompt += `- Line ${branch.line}: ${branch.branch}\\n`;\n      }\n      prompt += '\\n';\n    }\n\n    if (gap.uncoveredLines.length > 0) {\n      prompt += `**Uncovered lines:** ${gap.uncoveredLines.join(', ')}\\n\\n`;\n    }\n\n    prompt += `Current coverage: ${gap.currentCoverage}%. Target: ${gap.targetCoverage}%.\\n`;\n    prompt += `Focus on testing the uncovered functions and branches above.`;\n\n    return prompt;\n  }\n\n  private findUncoveredLines(statements: Record\u003Cstring, number>): number[] {\n    return Object.entries(statements)\n      .filter(([, count]) => count === 0)\n      .map(([id]) => parseInt(id, 10));\n  }\n\n  private findUncoveredBranches(\n    branches: Record\u003Cstring, number[]>,\n    branchMap: Record\u003Cstring, any>\n  ): Array\u003C{ line: number; branch: string }> {\n    const uncovered: Array\u003C{ line: number; branch: string }> = [];\n    for (const [id, counts] of Object.entries(branches)) {\n      counts.forEach((count, index) => {\n        if (count === 0 && branchMap[id]) {\n          uncovered.push({\n            line: branchMap[id].loc?.start?.line || 0,\n            branch: `Branch ${index} of ${branchMap[id].type}`,\n          });\n        }\n      });\n    }\n    return uncovered;\n  }\n\n  private findUncoveredFunctions(\n    functions: Record\u003Cstring, number>,\n    fnMap: Record\u003Cstring, any>\n  ): string[] {\n    return Object.entries(functions)\n      .filter(([, count]) => count === 0)\n      .map(([id]) => fnMap[id]?.name || `anonymous@${id}`)\n      .filter((name) => name !== 'anonymous@undefined');\n  }\n\n  private calculatePriority(\n    file: string,\n    coverage: number,\n    uncoveredFunctions: string[]\n  ): CoverageGap['priority'] {\n    if (file.includes('auth') || file.includes('security') || file.includes('payment')) {\n      return 'critical';\n    }\n    if (coverage \u003C 30) return 'high';\n    if (coverage \u003C 60 || uncoveredFunctions.length > 5) return 'medium';\n    return 'low';\n  }\n}\n```\n\n## Test Quality Checker\n\n```typescript\n\u002F\u002F test-generation\u002Freview\u002Fquality-checker.ts\nexport interface QualityReport {\n  score: number;\n  issues: QualityIssue[];\n  suggestions: string[];\n  passesReview: boolean;\n}\n\nexport interface QualityIssue {\n  severity: 'error' | 'warning' | 'info';\n  message: string;\n  line?: number;\n  rule: string;\n}\n\nexport class TestQualityChecker {\n  check(testCode: string): QualityReport {\n    const issues: QualityIssue[] = [];\n    const suggestions: string[] = [];\n\n    \u002F\u002F Check for common anti-patterns\n    this.checkForEmptyTests(testCode, issues);\n    this.checkForWeakAssertions(testCode, issues);\n    this.checkForHardcodedValues(testCode, issues);\n    this.checkForMissingErrorTests(testCode, issues);\n    this.checkForProperMocking(testCode, issues);\n    this.checkForTestIsolation(testCode, issues);\n    this.checkForDescriptiveNames(testCode, issues);\n    this.checkForAsyncHandling(testCode, issues);\n    this.checkForMagicNumbers(testCode, issues);\n    this.checkForProperCleanup(testCode, issues);\n\n    \u002F\u002F Generate suggestions\n    if (!testCode.includes('describe(')) {\n      suggestions.push('Group related tests in describe blocks for better organization');\n    }\n    if (!testCode.includes('beforeEach') && !testCode.includes('beforeAll')) {\n      suggestions.push('Consider using setup hooks for common test initialization');\n    }\n    if ((testCode.match(\u002Fit\\(\u002Fg) || []).length \u003C 3) {\n      suggestions.push('Consider adding more test cases for better coverage');\n    }\n\n    const errorCount = issues.filter((i) => i.severity === 'error').length;\n    const warningCount = issues.filter((i) => i.severity === 'warning').length;\n    const score = Math.max(0, 100 - errorCount * 20 - warningCount * 5);\n\n    return {\n      score,\n      issues,\n      suggestions,\n      passesReview: score >= 60 && errorCount === 0,\n    };\n  }\n\n  private checkForEmptyTests(code: string, issues: QualityIssue[]): void {\n    const emptyTestRegex = \u002Fit\\([^)]+,\\s*(?:async\\s*)?\\(\\)\\s*=>\\s*\\{\\s*\\}\\)\u002Fg;\n    const matches = code.match(emptyTestRegex);\n    if (matches) {\n      issues.push({\n        severity: 'error',\n        message: `Found ${matches.length} empty test(s) with no assertions`,\n        rule: 'no-empty-tests',\n      });\n    }\n  }\n\n  private checkForWeakAssertions(code: string, issues: QualityIssue[]): void {\n    const weakPatterns = [\n      { pattern: \u002Fexpect\\(\\w+\\)\\.toBeTruthy\\(\\)\u002Fg, message: 'toBeTruthy() is too permissive - use specific assertion' },\n      { pattern: \u002Fexpect\\(\\w+\\)\\.toBeDefined\\(\\)\u002Fg, message: 'toBeDefined() only checks not-undefined - verify actual value' },\n      { pattern: \u002Fexpect\\(\\w+\\)\\.not\\.toBeNull\\(\\)\u002Fg, message: 'not.toBeNull() is weak - assert the expected value' },\n    ];\n\n    for (const { pattern, message } of weakPatterns) {\n      const matches = code.match(pattern);\n      if (matches && matches.length > 2) {\n        issues.push({ severity: 'warning', message: `${message} (found ${matches.length} instances)`, rule: 'strong-assertions' });\n      }\n    }\n  }\n\n  private checkForHardcodedValues(code: string, issues: QualityIssue[]): void {\n    if (code.includes('localhost:') && !code.includes('process.env')) {\n      issues.push({\n        severity: 'warning',\n        message: 'Hardcoded localhost URLs found. Use environment variables or config.',\n        rule: 'no-hardcoded-urls',\n      });\n    }\n  }\n\n  private checkForMissingErrorTests(code: string, issues: QualityIssue[]): void {\n    const hasErrorTests = code.includes('toThrow') || code.includes('rejects') || code.includes('error') || code.includes('invalid');\n    if (!hasErrorTests) {\n      issues.push({\n        severity: 'warning',\n        message: 'No error handling tests found. Add tests for invalid inputs and error cases.',\n        rule: 'error-coverage',\n      });\n    }\n  }\n\n  private checkForProperMocking(code: string, issues: QualityIssue[]): void {\n    if (code.includes('vi.fn()') || code.includes('jest.fn()')) {\n      const mockCalls = (code.match(\u002Fvi\\.fn\\(\\)|jest\\.fn\\(\\)\u002Fg) || []).length;\n      const mockVerifications = (code.match(\u002FtoHaveBeenCalled|toHaveBeenCalledWith\u002Fg) || []).length;\n      if (mockCalls > mockVerifications * 2) {\n        issues.push({\n          severity: 'warning',\n          message: 'Mocks created but not all verified. Ensure mocks are asserted.',\n          rule: 'verify-mocks',\n        });\n      }\n    }\n  }\n\n  private checkForTestIsolation(code: string, issues: QualityIssue[]): void {\n    if (code.includes('let ') && !code.includes('beforeEach')) {\n      const mutableVars = (code.match(\u002F^\\s*let\\s+\\w+\u002Fgm) || []).length;\n      if (mutableVars > 2) {\n        issues.push({\n          severity: 'warning',\n          message: 'Mutable variables without beforeEach reset. Tests may not be isolated.',\n          rule: 'test-isolation',\n        });\n      }\n    }\n  }\n\n  private checkForDescriptiveNames(code: string, issues: QualityIssue[]): void {\n    const shortTests = code.match(\u002Fit\\(['\"]([^'\"]{1,15})['\"]\u002Fg);\n    if (shortTests && shortTests.length > 0) {\n      issues.push({\n        severity: 'info',\n        message: `${shortTests.length} test(s) have very short names. Use descriptive names explaining expected behavior.`,\n        rule: 'descriptive-names',\n      });\n    }\n  }\n\n  private checkForAsyncHandling(code: string, issues: QualityIssue[]): void {\n    if (code.includes('Promise') || code.includes('async')) {\n      if (!code.includes('await') && !code.includes('.resolves') && !code.includes('.rejects')) {\n        issues.push({\n          severity: 'error',\n          message: 'Async code detected but no await or promise assertions found. Tests may not wait for async operations.',\n          rule: 'async-handling',\n        });\n      }\n    }\n  }\n\n  private checkForMagicNumbers(code: string, issues: QualityIssue[]): void {\n    const magicNumbers = code.match(\u002Fexpect\\([^)]+\\)\\.\\w+\\((?!['\"`true|false|null|undefined|0|1|-1)\\d{2,}\\)\u002Fg);\n    if (magicNumbers && magicNumbers.length > 3) {\n      issues.push({\n        severity: 'info',\n        message: 'Multiple magic numbers in assertions. Consider extracting to named constants.',\n        rule: 'no-magic-numbers',\n      });\n    }\n  }\n\n  private checkForProperCleanup(code: string, issues: QualityIssue[]): void {\n    const hasSetup = code.includes('beforeEach') || code.includes('beforeAll');\n    const hasCleanup = code.includes('afterEach') || code.includes('afterAll');\n    if (hasSetup && !hasCleanup) {\n      issues.push({\n        severity: 'warning',\n        message: 'Setup hooks found without cleanup hooks. Consider adding afterEach\u002FafterAll for cleanup.',\n        rule: 'proper-cleanup',\n      });\n    }\n  }\n}\n```\n\n## Batch Test Generator\n\n```typescript\n\u002F\u002F test-generation\u002Fgenerators\u002Fbatch-generator.ts\nimport Anthropic from '@anthropic-ai\u002Fsdk';\nimport { TestPromptBuilder, PromptContext } from '.\u002Fprompt-builder';\nimport { TestQualityChecker, QualityReport } from '..\u002Freview\u002Fquality-checker';\nimport { readFileSync } from 'fs';\n\nexport interface BatchResult {\n  file: string;\n  testCode: string;\n  quality: QualityReport;\n  tokensUsed: number;\n  generationTimeMs: number;\n}\n\nexport class BatchTestGenerator {\n  private client: Anthropic;\n  private promptBuilder: TestPromptBuilder;\n  private qualityChecker: TestQualityChecker;\n\n  constructor() {\n    this.client = new Anthropic();\n    this.promptBuilder = new TestPromptBuilder();\n    this.qualityChecker = new TestQualityChecker();\n  }\n\n  async generateBatch(\n    files: string[],\n    testType: 'unit' | 'integration' | 'e2e' | 'api',\n    conventions?: string\n  ): Promise\u003CBatchResult[]> {\n    const results: BatchResult[] = [];\n\n    for (const file of files) {\n      const sourceCode = readFileSync(file, 'utf-8');\n      const context: PromptContext = {\n        sourceCode,\n        sourceFile: file,\n        projectConventions: conventions,\n      };\n\n      const prompt = testType === 'unit'\n        ? this.promptBuilder.buildUnitTestPrompt(context)\n        : testType === 'e2e'\n          ? this.promptBuilder.buildE2ETestPrompt(context)\n          : this.promptBuilder.buildIntegrationTestPrompt(context);\n\n      const startTime = Date.now();\n\n      const response = await this.client.messages.create({\n        model: 'claude-sonnet-4-20250514',\n        max_tokens: 4096,\n        temperature: 0,\n        system: prompt.system,\n        messages: [{ role: 'user', content: prompt.user }],\n      });\n\n      const text = response.content[0].type === 'text' ? response.content[0].text : '';\n      const codeMatch = text.match(\u002F```typescript\\n([\\s\\S]*?)```\u002F);\n      const testCode = codeMatch ? codeMatch[1] : text;\n\n      const quality = this.qualityChecker.check(testCode);\n      const tokensUsed = (response.usage?.input_tokens || 0) + (response.usage?.output_tokens || 0);\n\n      results.push({\n        file,\n        testCode: testCode.trim(),\n        quality,\n        tokensUsed,\n        generationTimeMs: Date.now() - startTime,\n      });\n    }\n\n    return results;\n  }\n}\n```\n\n## Example: Using the Generation Pipeline\n\n```typescript\n\u002F\u002F example-usage.ts\nimport { TestPromptBuilder } from '.\u002Fgenerators\u002Fprompt-builder';\nimport { CoverageAnalyzer } from '.\u002Fanalyzers\u002Fcoverage-analyzer';\nimport { BatchTestGenerator } from '.\u002Fgenerators\u002Fbatch-generator';\n\nasync function generateTestsForProject() {\n  \u002F\u002F Step 1: Analyze coverage gaps\n  const coverageAnalyzer = new CoverageAnalyzer();\n  const gaps = coverageAnalyzer.analyzeCoverageReport('.\u002Fcoverage\u002Fcoverage-final.json');\n\n  console.log(`Found ${gaps.length} coverage gaps`);\n  const criticalGaps = gaps.filter((g) => g.priority === 'critical' || g.priority === 'high');\n  console.log(`${criticalGaps.length} critical\u002Fhigh priority gaps`);\n\n  \u002F\u002F Step 2: Generate tests for high-priority gaps\n  const generator = new BatchTestGenerator();\n  const results = await generator.generateBatch(\n    criticalGaps.map((g) => g.file),\n    'unit',\n    'Use vitest, follow AAA pattern, use vi.mock for dependencies'\n  );\n\n  \u002F\u002F Step 3: Review quality\n  for (const result of results) {\n    console.log(`${result.file}: Score ${result.quality.score}\u002F100`);\n    if (result.quality.passesReview) {\n      console.log('  PASS - Ready for human review');\n    } else {\n      console.log('  NEEDS WORK:', result.quality.issues.map((i) => i.message).join('; '));\n    }\n  }\n}\n```\n\n## Best Practices\n\n1. **Provide the source code in every generation prompt** -- AI agents cannot infer implementation details from function names alone. Always include the full source code being tested.\n2. **Include existing test patterns in context** -- Show the agent 2-3 examples of your existing tests so it matches your project's style and conventions.\n3. **Generate tests incrementally, not all at once** -- Generate tests for one file at a time, validate them, then move to the next. Batch generation without validation produces low-quality tests.\n4. **Use coverage reports to target generation** -- Do not regenerate tests that already exist. Analyze coverage gaps and generate only for uncovered code paths.\n5. **Review AI-generated assertions carefully** -- AI agents often generate assertions that are too loose (toBeDefined) or test implementation details rather than behavior.\n6. **Set up automated quality checks** -- Run the quality checker on all generated tests before human review to catch common anti-patterns automatically.\n7. **Keep prompts under version control** -- Store generation prompts in your repository so the entire team uses consistent prompts and changes are tracked.\n8. **Test the tests with mutation testing** -- After generating tests, run mutation testing to verify the generated assertions actually detect bugs.\n9. **Establish a generation budget** -- Set a maximum number of tokens or dollars per generation session to prevent runaway costs.\n10. **Document which tests are AI-generated** -- Add a comment or metadata to generated tests so reviewers know to scrutinize them more carefully.\n\n## Anti-Patterns\n\n1. **Generating tests without source code context** -- Prompting with only function signatures produces tests that compile but do not meaningfully verify behavior.\n2. **Accepting all generated tests without review** -- AI-generated tests can have incorrect assertions, hardcoded values, and logic errors. Always review before committing.\n3. **Using temperature > 0 for test generation** -- Non-deterministic generation produces inconsistent results. Use temperature 0 for reproducible test generation.\n4. **Generating tests for trivial code** -- Do not waste tokens generating tests for simple getters, setters, or pass-through functions. Focus on complex logic.\n5. **Ignoring the quality checker output** -- Automated quality checks catch 80% of common issues. Skipping them leads to low-quality tests entering the codebase.\n6. **Regenerating existing tests** -- Before generating, check if tests already exist. Duplicate tests waste resources and create maintenance burden.\n7. **Using AI-generated tests as the sole quality gate** -- AI-generated tests complement but do not replace human-written critical path tests.\n8. **Not validating that generated tests actually run** -- A test that does not compile or throws at runtime provides zero value. Always execute generated tests before committing.\n9. **Generating E2E tests for unstable UIs** -- If the UI is changing rapidly, generated E2E tests will break immediately. Wait for UI stabilization.\n10. **Trusting AI-generated mock implementations** -- AI agents often create mocks that do not accurately represent the real dependency behavior. Verify mocks against actual service contracts.\n",{"name":5,"tags":24,"agents":34,"author":47,"domains":48,"license":15,"version":53,"languages":54,"frameworks":58,"description":7,"testingTypes":64},[25,26,27,28,29,30,31,32,33],"ai-testing","test-generation","prompt-engineering","coverage-driven","mutation-testing","code-review","automated-testing","llm-testing","ai-code-generation",[35,36,37,38,39,40,41,42,43,44,45,46],"claude-code","cursor","github-copilot","windsurf","codex","aider","continue","cline","zed","bolt","gemini-cli","amp","thetestingacademy",[49,50,51,52],"web","backend","api","mobile","1.0.0",[55,56,57],"typescript","javascript","python",[59,60,61,62,63],"vitest","jest","playwright","pytest","cypress",[65,66,67,51],"unit","integration","e2e","main","eac438ea9216a7cb8a570cab803eb01eeafc6793","skills\u002Fqa\u002Fai-test-generation","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m","https:\u002F\u002Fid-preview--d5bef06d-6c9e-4563-a3d4-a855b9d61610.lovable.app\u002F","Eu sou Antonio B. B. Ndombe \r\nEu sou um Pesquisador e desenvolvedor de sistema autonomia cognitivos, fundador de sistemas ODCs ( organismos digital conscientes)","2026-11-04 06:53:39",{"source":8,"skillName":5,"commands":77,"prompt":87,"zipAvailable":88},[78,81,84],{"tool":79,"command":80},"npx","npx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"AI Test Generation Patterns\"",{"tool":82,"command":83},"bunx","bunx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"AI Test Generation Patterns\"",{"tool":85,"command":86},"pnpm","pnpm dlx skills add GrupoANDevelopment-m\u002Falberto-ai --skill \"AI Test Generation Patterns\"","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fskills\u002Fqa\u002Fai-test-generation\u002FSKILL.md",true,[],[91,99,106,113,120,127],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":19},"01M7DASC6FSCJP49JZBSK0NY1Z","nemoclaw-user-reference","Describes the NemoClaw integration layer and blueprint architecture and how they orchestrate compatible agent sandboxes. Use when looking up architecture, agent integration, plugin structure, or blueprint design. Trigger keywords - nemoclaw architecture, nemoclaw agent architecture, nemoclaw plugin blueprint structure, nemoclaw vs openshell, which cli, nemoclaw cli, openshell cli, sandbox commands, nemoclaw cli commands, nemoclaw command reference, nemoclaw network policy, sandbox egress control operator approval, nemoclaw troubleshooting, nemoclaw debug sandbox issues.","Apache-2.0","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-reference\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":19},"01M7DAS5S79VK33XFGVAM2TFWF","nemoclaw-user-overview","Explains how OpenClaw, OpenShell, and NemoClaw form the ecosystem, NemoClaw's position in the stack, what NemoClaw adds beyond the community sandbox, and when to prefer NemoClaw versus integrating OpenShell and OpenClaw directly. Use when users ask about the relationship between OpenClaw, OpenShell, and NemoClaw, or when to use NemoClaw versus OpenShell. Trigger keywords - nemoclaw ecosystem, openclaw openshell, nemoclaw vs openshell, sandboxed openclaw, how nemoclaw works, nemoclaw sandbox lifecycle blueprint, nemoclaw overview, openclaw always-on assistants, nvidia openshell, nvidia nemotron, nemoclaw release notes, nemoclaw changelog.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-overview\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"publishedAt":19},"01M7DAS0PQEMET5MNGZ1ABSZVS","nemoclaw-user-monitor-sandbox","Inspects sandbox health, traces agent behavior, and diagnoses problems. Use when monitoring a running sandbox, debugging agent issues, or checking sandbox logs. Trigger keywords - monitor nemoclaw sandbox, debug nemoclaw agent issues.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-monitor-sandbox\u002FSKILL.md",[],[],{"skillNo":114,"name":115,"nameZh":6,"description":116,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":117,"categories":118,"keywords":119,"publishedAt":19},"01M7DARQYGF7E9A69VH6S3CGN9","nemoclaw-user-manage-sandboxes","Explains operational tasks after the quickstart: listing sandboxes, status and health checks, logs, diagnostics, port forwards, multiple sandboxes, credential reset, rebuilds, network presets, upgrades, and uninstall. Trigger keywords - manage nemoclaw sandboxes, nemoclaw status, nemoclaw list, nemoclaw dashboard port, nemoclaw rebuild, nemoclaw upgrade sandboxes, nemoclaw uninstall, sandbox mutability, sandbox runtime configuration, sandbox rebuild, nemoclaw backup, nemoclaw restore, workspace backup, openshell sandbox download upload, nemoclaw messaging channels, nemoclaw telegram, nemoclaw discord, nemoclaw slack, nemoclaw wechat, nemoclaw whatsapp, openshell channel messaging, nemoclaw workspace files, soul.md, user.md, identity.md, agents.md, sandbox persistence.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-sandboxes\u002FSKILL.md",[],[],{"skillNo":121,"name":122,"nameZh":6,"description":123,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":124,"categories":125,"keywords":126,"publishedAt":19},"01M7DARH8BRTG51TRCAB7YWDJ4","nemoclaw-user-manage-policy","Adds, removes, or modifies allowed endpoints in the sandbox policy. Use when customizing network policy, changing egress rules, or configuring sandbox endpoint access. Trigger keywords - customize nemoclaw network policy, sandbox egress policy configuration, nemoclaw integration policy examples, post-install policy setup, openshell approval workflow, policy preset, nemoclaw approve network requests, sandbox egress approval tui.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-manage-policy\u002FSKILL.md",[],[],{"skillNo":128,"name":129,"nameZh":6,"description":130,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":95,"licenseFileUrl":6,"sourceHtmlUrl":131,"categories":132,"keywords":133,"publishedAt":19},"01M7DARAT62M2VR37590VCZ5NS","nemoclaw-user-get-started","Installs NemoClaw, launches a sandbox, and runs the first agent prompt. Use when onboarding, installing, or launching a NemoClaw sandbox for the first time. Trigger keywords - nemoclaw quickstart, install nemoclaw openclaw sandbox, nemohermes quickstart, hermes agent nemoclaw, run hermes openshell sandbox, nemoclaw prerequisites, nemoclaw supported platforms, nemoclaw hardware software, nemoclaw windows wsl2 setup, nemoclaw install windows docker desktop.","https:\u002F\u002Fgithub.com\u002FGrupoANDevelopment-m\u002Falberto-ai\u002Fblob\u002Fmain\u002Fupstream\u002Fnemoclaw\u002Fskills\u002Fnemoclaw-user-get-started\u002FSKILL.md",[],[]]