generate_tests_for_coverage
Generate targeted test cases to achieve 80%+ coverage for a file, supporting Jest, Vitest, or Mocha. Include edge cases and accessibility tests for components to enhance code quality and reliability.
Instructions
Generate intelligent tests to achieve 80%+ coverage
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| coverageTarget | No | Target coverage percentage (default: 80) | |
| includeAccessibility | No | Include accessibility tests for components | |
| includeEdgeCases | No | Include edge case tests | |
| targetFile | Yes | File to generate tests for | |
| testFramework | No | Test framework to use |
Input Schema (JSON Schema)
{
"properties": {
"coverageTarget": {
"description": "Target coverage percentage (default: 80)",
"type": "number"
},
"includeAccessibility": {
"description": "Include accessibility tests for components",
"type": "boolean"
},
"includeEdgeCases": {
"description": "Include edge case tests",
"type": "boolean"
},
"targetFile": {
"description": "File to generate tests for",
"type": "string"
},
"testFramework": {
"description": "Test framework to use",
"enum": [
"jest",
"vitest",
"mocha"
],
"type": "string"
}
},
"required": [
"targetFile"
],
"type": "object"
}
Implementation Reference
- The main handler function `generateTestsForCoverage` that parses the target file AST, analyzes structure, generates test code for various categories, estimates coverage, and provides suggestions.export async function generateTestsForCoverage( config: TestGenerationConfig ): Promise<TestGenerationResult> { const result: TestGenerationResult = { success: false, testCode: '', coverage: { estimated: 0, functions: 0, branches: 0, lines: 0, }, testCategories: { unit: 0, integration: 0, edgeCases: 0, errorHandling: 0, accessibility: 0, }, suggestions: [], }; try { // Read target file if (!existsSync(config.targetFile)) { throw new Error(`Target file not found: ${config.targetFile}`); } const fileContent = readFileSync(config.targetFile, 'utf-8'); const fileType = detectFileType(fileContent); // Parse the file to understand structure const ast = parseCode(fileContent); const analysis = analyzeCode(ast, fileType); // Generate tests based on analysis const testFramework = config.testFramework || detectTestFramework(); const tests = generateTests(analysis, testFramework, config); // Calculate coverage estimation const coverage = estimateCoverage(analysis, tests); // Generate suggestions for reaching target coverage const suggestions = generateSuggestions( coverage, config.coverageTarget || 80, analysis ); result.success = true; result.testCode = tests.code; result.coverage = coverage; result.testCategories = tests.categories; result.suggestions = suggestions; } catch (error) { result.success = false; result.suggestions = [`Error generating tests: ${error}`]; } return result;
- The tool schema definition specifying input parameters like targetFile, testFramework, coverageTarget, etc.name: 'generate_tests_for_coverage', description: 'Generate intelligent tests to achieve 80%+ coverage', inputSchema: { type: 'object', properties: { targetFile: { type: 'string', description: 'File to generate tests for', }, testFramework: { type: 'string', enum: ['jest', 'vitest', 'mocha'], description: 'Test framework to use', }, coverageTarget: { type: 'number', description: 'Target coverage percentage (default: 80)', }, includeEdgeCases: { type: 'boolean', description: 'Include edge case tests', }, includeAccessibility: { type: 'boolean', description: 'Include accessibility tests for components', }, }, required: ['targetFile'], }, },
- src/tools/index.ts:165-183 (registration)Registration in the tool dispatcher switch case: parses arguments with Zod schema matching the tool schema, calls the handler, and returns JSON result.case 'generate_tests_for_coverage': { const params = z.object({ targetFile: z.string(), testFramework: z.enum(['jest', 'vitest', 'mocha']).optional(), coverageTarget: z.number().optional(), includeEdgeCases: z.boolean().optional(), includeAccessibility: z.boolean().optional(), }).parse(args); const result = await generateTestsForCoverage(params); return { content: [ { type: 'text', text: JSON.stringify(result, null, 2), }, ], }; }
- Key helper function `analyzeCode` that traverses the AST to extract exports, imports, state, effects, conditionals, loops, and error handlers for test generation.function analyzeCode(ast: any, fileType: FileType): CodeAnalysis { const analysis: CodeAnalysis = { exports: [], imports: [], stateVariables: [], effects: [], conditionals: 0, loops: 0, errorHandlers: 0, }; traverse(ast, { ImportDeclaration(path: NodePath<t.ImportDeclaration>) { analysis.imports.push(path.node.source.value); }, ExportNamedDeclaration(path: NodePath<t.ExportNamedDeclaration>) { if (path.node.declaration) { if (t.isFunctionDeclaration(path.node.declaration)) { analysis.exports.push({ name: path.node.declaration.id?.name || 'anonymous', type: 'function', params: path.node.declaration.params.map(() => 'param'), hasAsync: path.node.declaration.async, complexity: calculateComplexity(path.node.declaration), }); } } }, ExportDefaultDeclaration(path: NodePath<t.ExportDefaultDeclaration>) { if (t.isFunctionDeclaration(path.node.declaration)) { analysis.exports.push({ name: path.node.declaration.id?.name || 'default', type: fileType.type === 'component' ? 'component' : 'function', params: path.node.declaration.params.map(() => 'param'), hasAsync: path.node.declaration.async, complexity: calculateComplexity(path.node.declaration), }); } }, CallExpression(path: NodePath<t.CallExpression>) { if (t.isIdentifier(path.node.callee)) { if (path.node.callee.name === 'useState') { analysis.stateVariables.push('state'); } if (path.node.callee.name === 'useEffect') { analysis.effects.push('effect'); } } }, IfStatement() { analysis.conditionals++; }, ConditionalExpression() { analysis.conditionals++; }, ForStatement() { analysis.loops++; }, WhileStatement() { analysis.loops++; }, TryStatement() { analysis.errorHandlers++; }, }); return analysis; }