/kibana-testing-tools:test-coverage-analyzerfrom kibana-testing-tools
Analyzes test coverage gaps, identifies untested code paths, and generates targeted test recommendations. Works with Jest coverage reports, Scout tests, and source code analysis to find blind spots.
Ships in kibana-testing-tools. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Purpose: Systematically identify untested code paths and generate targeted test recommendations to improve coverage quality (not just coverage percentage).
Context: High coverage % doesn't guarantee quality coverage. This agent finds critical untested paths: error handlers, RBAC checks, edge cases, and boundary conditions that matter for production reliability.
Philosophy:
Automatic activation triggers:
Manual invocation:
/test-coverage-analyzer
Goal: Gather coverage data from all test layers.
# For specific package (scoped, faster)
yarn test:jest --coverage --collectCoverageFrom='x-pack/plugins/<plugin>/**/*.ts' \
x-pack/plugins/<plugin>
# Generate HTML report
--coverageReporters=html,text,lcov
Output: coverage/lcov-report/index.html + coverage/coverage-summary.json
# Find all Scout tests for package
find x-pack/plugins/<plugin>/test/scout* -name "*.spec.ts"
# Extract test scenarios (describe/test names)
grep -r "test\(" x-pack/plugins/<plugin>/test/scout* -A1
Output: List of Scout-covered scenarios
# Find integration tests
find x-pack/plugins/<plugin> -name "*.integration.test.ts"
# Extract coverage (integration test scenarios)
grep -r "it\(" -A1
Output: List of integration-covered scenarios
Goal: Identify all code paths that SHOULD be tested.
Parse source code for:
Error handlers:
try {
// Happy path
} catch (error) {
// ❓ Is this tested?
}
Conditional branches:
if (condition) {
// Branch A - ❓ Tested?
} else {
// Branch B - ❓ Tested?
}
RBAC checks:
if (!user.hasPrivilege('read')) {
return response.forbidden(); // ❓ Tested?
}
Validation logic:
if (!input.isValid()) {
throw new ValidationError(); // ❓ Tested?
}
Edge cases:
if (items.length === 0) {
return emptyState; // ❓ Tested?
}
if (value > MAX_LIMIT) {
throw new Error('Exceeds limit'); // ❓ Tested?
}
Async error paths:
const result = await apiCall().catch((error) => {
// ❓ Tested?
});
Use AST parsing (TypeScript compiler API) for accuracy:
import * as ts from 'typescript';
function findUncoveredPaths(sourceFile: ts.SourceFile): UncoveredPath[] {
const paths: UncoveredPath[] = [];
function visit(node: ts.Node) {
// Find try-catch blocks
if (ts.isTryStatement(node)) {
paths.push({
type: 'error-handler',
location: `${sourceFile.fileName}:${getLineNumber(node.catchClause)}`,
code: node.catchClause.getText(),
});
}
// Find if-else branches
if (ts.isIfStatement(node)) {
paths.push({
type: 'conditional',
location: `${sourceFile.fileName}:${getLineNumber(node)}`,
condition: node.expression.getText(),
});
}
// Find auth checks (heuristic: .hasPrivilege, forbidden, 403)
if (isAuthCheck(node)) {
paths.push({
type: 'rbac',
location: `${sourceFile.fileName}:${getLineNumber(node)}`,
});
}
ts.forEachChild(node, visit);
}
visit(sourceFile);
return paths;
}
Goal: Compare code paths against test coverage to find gaps.
Use lcov data:
# Extract uncovered lines from lcov.info
grep -A2 "^SF:" coverage/lcov.info | grep -E "^DA:" | grep ",0$"
# Format: DA:<line>,<hit-count>
# DA:42,0 means line 42 was never executed
Match uncovered lines to code paths:
// Example: Line 42 is uncovered
const uncoveredLine = 42;
// Find which code path contains line 42
const path = codePaths.find(p => p.lineNumber === uncoveredLine);
// Categorize gap
if (path.type === 'error-handler') {
gaps.push({
type: 'CRITICAL',
category: 'Error handling not tested',
location: `file.ts:42`,
risk: 'Production errors may not be handled correctly',
});
}
Risk levels:
| Risk Level | Description | Examples |
|---|---|---|
| CRITICAL | Untested code that handles errors, auth, or data loss | try-catch, RBAC checks, delete operations |
| HIGH | Untested business logic, validation, edge cases | Input validation, boundary conditions, state transitions |
| MEDIUM | Untested UI logic, formatting, display | Conditional rendering, empty states, loading states |
| LOW | Untested helper functions, utils (covered by integration) | String formatting, date parsing (if used in tested code) |
Prioritization:
Goal: Generate specific, actionable test recommendations with code snippets.
For each coverage gap, generate appropriate test:
Example 1: Untested Error Handler
Gap found:
// x-pack/plugins/security_solution/server/lib/isolate_endpoint.ts:42
try {
await fleetClient.isolate(endpointId);
} catch (error) {
// ❌ CRITICAL: Not tested
logger.error('Isolation failed', error);
throw new IsolationError('Failed to isolate endpoint');
}
Recommended test (Jest):
// x-pack/plugins/security_solution/server/lib/isolate_endpoint.test.ts
describe('isolateEndpoint', () => {
it('should throw IsolationError when Fleet API fails', async () => {
const mockFleetClient = {
isolate: jest.fn().mockRejectedValue(new Error('Fleet API error')),
};
await expect(
isolateEndpoint(mockFleetClient, 'endpoint-123')
).rejects.toThrow('Failed to isolate endpoint');
expect(mockLogger.error).toHaveBeenCalledWith(
'Isolation failed',
expect.any(Error)
);
});
});
Example 2: Untested RBAC Path
Gap found:
// x-pack/plugins/security_solution/server/routes/isolate.ts:28
if (!authzResult.hasPrivilege) {
// ❌ CRITICAL: Forbidden path not tested
return response.forbidden({
body: { message: 'Insufficient privileges' },
});
}
Recommended test (Scout API):
// x-pack/plugins/security_solution/test/scout_api/isolate_rbac.spec.ts
import { apiTest, expect } from '@kbn/scout/api';
import { COMMON_HEADERS } from '../constants';
apiTest.describe('POST /api/security_solution/isolate - RBAC', () => {
let viewerCredentials: ApiKeyAuth;
apiTest.beforeAll(async ({ requestAuth }) => {
viewerCredentials = await requestAuth.getApiKeyForViewer();
});
apiTest('returns 403 for viewer without isolate privilege', async ({ apiClient }) => {
const response = await apiClient.post('api/security_solution/isolate', {
headers: { ...COMMON_HEADERS, ...viewerCredentials.apiKeyHeader },
body: { endpoint_id: 'test-endpoint-123' },
});
expect(response).toHaveStatusCode(403);
expect(response.body).toMatchObject({
message: 'Insufficient privileges',
});
});
});
Example 3: Untested Edge Case
Gap found:
// x-pack/plugins/security_solution/public/components/alert_list.tsx:156
if (alerts.length === 0) {
// ❌ HIGH: Empty state not tested
return <EmptyStateMessage />;
}
Recommended test (Scout UI or RTL):
// x-pack/plugins/security_solution/public/components/alert_list.test.tsx
import { render, screen } from '@testing-library/react';
import { AlertList } from './alert_list';
describe('AlertList', () => {
it('should show empty state when no alerts', () => {
render(<AlertList alerts={[]} />);
expect(screen.getByTestId('emptyStateMessage')).toBeInTheDocument();
expect(screen.queryByTestId('alertTable')).not.toBeInTheDocument();
});
});
Goal: Generate comprehensive coverage report with prioritized recommendations.
# Test Coverage Analysis: <Package/Feature>
**Analyzed:** [Date]
**Package:** x-pack/plugins/<plugin>
**Current Coverage:** 78.5% (lines), 65.2% (branches)
---
## Executive Summary
**Total code paths:** 156
**Tested paths:** 98 (62.8%)
**Untested paths:** 58 (37.2%)
**By risk level:**
- **CRITICAL:** 8 gaps (error handlers, RBAC, data loss)
- **HIGH:** 15 gaps (business logic, validation, edge cases)
- **MEDIUM:** 22 gaps (UI logic, display, formatting)
- **LOW:** 13 gaps (helpers, utils)
**Recommendation:** Fix 8 CRITICAL + 15 HIGH gaps before release (23 tests, ~4-6 hours)
---
## Coverage Gaps by Risk Level
### CRITICAL Gaps (8) - Fix Before Release
#### 1. Error Handler: Isolation API Failure
**Location:** `server/lib/isolate_endpoint.ts:42`
**Untested code:**
```typescript
catch (error) {
logger.error('Isolation failed', error);
throw new IsolationError('Failed to isolate endpoint');
}
Risk: Production errors may not be handled correctly Test layer: Jest unit test Estimated effort: 15 min
Recommended test:
it('should throw IsolationError when Fleet API fails', async () => {
const mockFleetClient = {
isolate: jest.fn().mockRejectedValue(new Error('Fleet API error')),
};
await expect(
isolateEndpoint(mockFleetClient, 'endpoint-123')
).rejects.toThrow('Failed to isolate endpoint');
});
Location: server/routes/isolate.ts:28
Untested code:
if (!authzResult.hasPrivilege) {
return response.forbidden({ message: 'Insufficient privileges' });
}
Risk: Unauthorized users might bypass security Test layer: Scout API test Estimated effort: 20 min
Recommended test:
apiTest('returns 403 for viewer without isolate privilege', async ({ apiClient, requestAuth }) => {
const viewerCreds = await requestAuth.getApiKeyForViewer();
const response = await apiClient.post('api/security_solution/isolate', {
headers: { ...COMMON_HEADERS, ...viewerCreds.apiKeyHeader },
body: { endpoint_id: 'test-123' },
});
expect(response).toHaveStatusCode(403);
});
[... 6 more CRITICAL gaps with test snippets]
[Similar structure for each gap]
[Condensed list with locations]
[Condensed list]
| File | Lines | Branches | Functions | Uncovered Lines |
|---|---|---|---|---|
server/lib/isolate_endpoint.ts | 85.2% | 62.5% | 90.0% | 42, 56, 78 |
server/routes/isolate.ts | 72.3% | 58.3% | 75.0% | 28, 35, 89-92 |
public/components/alert_list.tsx | 68.9% | 55.0% | 70.0% | 156, 178, 203 |
After fixing CRITICAL + HIGH gaps:
Priority 1: CRITICAL (8 tests, ~2-3 hours)
Priority 2: HIGH (15 tests, ~4-5 hours)
Priority 3: MEDIUM (22 tests, ~3-4 hours)
Total effort: ~9-12 hours to reach 92% high-quality coverage
Tests that are easy to add and high impact:
Empty state tests (UI components)
Forbidden path tests (API routes)
Network timeout tests (API calls)
---
### Phase 3: Test Layer Recommendation (2 min)
**Goal:** Recommend the right test layer for each gap.
#### Test Layer Decision Tree:
What are you testing? ├─ Error handling in backend logic? │ └─ Jest unit test (mock dependencies, fast) │ ├─ API endpoint behavior (RBAC, validation)? │ └─ Scout API test (realistic requests, auth) │ ├─ UI rendering (components, empty states)? │ ├─ Simple component logic? → RTL unit test (isolated, fast) │ └─ User interaction flow? → Scout UI test (browser, realistic) │ ├─ Integration (service → API → response)? │ └─ Jest integration test (test environment) │ └─ E2E user flow (login → navigate → action)? └─ Scout UI test (full browser context)
**Example recommendations:**
| Gap | Code Location | Recommended Layer | Reason |
|-----|---------------|-------------------|--------|
| Error handler: Fleet API failure | `server/lib/isolate.ts:42` | Jest unit | Isolated logic, mock Fleet |
| RBAC: Viewer forbidden | `server/routes/isolate.ts:28` | Scout API | Validate real RBAC enforcement |
| Empty state: No alerts | `public/components/alert_list.tsx:156` | RTL unit | Simple component logic |
| User flow: Isolate from UI | Integration | Scout UI | Full browser flow |
---
### Phase 4: Coverage Improvement Tracking (Ongoing)
**Goal:** Track progress as gaps are filled.
#### Generate tracking document:
```markdown
# Coverage Improvement Tracker: <Feature>
**Started:** [Date]
**Target:** Fix all CRITICAL + HIGH gaps
**Progress:** 0 / 23 gaps fixed
---
## Progress Checklist
### CRITICAL (8)
- [ ] Error handler: Isolation API failure (file.ts:42)
- [ ] RBAC: Viewer forbidden (file.ts:28)
- [ ] Data loss: Delete without confirmation (file.ts:156)
- [ ] ... (5 more)
### HIGH (15)
- [ ] Validation: Empty required field (file.ts:89)
- [ ] Edge case: Max value exceeded (file.ts:134)
- [ ] ... (13 more)
---
## Coverage Metrics (Updated Daily)
| Metric | Initial | Current | Target | Progress |
|--------|---------|---------|--------|----------|
| Lines | 78.5% | 78.5% | 92.0% | 0% |
| Branches | 65.2% | 65.2% | 85.0% | 0% |
| CRITICAL gaps | 8 | 8 | 0 | 0% |
| HIGH gaps | 15 | 15 | 0 | 0% |
**Run to update:**
```bash
yarn test:jest --coverage --collectCoverageFrom='...' && /test-coverage-analyzer
---
## Advanced Analysis
### Pattern 1: Find Untested Error Paths (Heuristic)
**Search for error patterns without tests:**
```bash
# Find all error throw statements
grep -rn "throw new" x-pack/plugins/<plugin>/server --include="*.ts"
# For each throw, check if test exists
# Example: throw new IsolationError(...)
grep -r "IsolationError" x-pack/plugins/<plugin>/**/*.test.ts
# If no match → untested error path
Common untested error patterns:
throw new ValidationError (input validation)throw new AuthorizationError (RBAC)throw new NotFoundError (404 cases)throw new ConflictError (409 cases)return response.forbidden() (403 cases)return response.badRequest() (400 cases)Search for privilege checks without tests:
# Find RBAC checks
grep -rn "hasPrivilege\|forbidden\|requiredPrivileges" \
x-pack/plugins/<plugin>/server --include="*.ts"
# For each RBAC check, verify test exists
# Look for Scout API tests with viewer/editor credentials
grep -r "getApiKeyForViewer\|loginAsViewer" \
x-pack/plugins/<plugin>/test/scout*
# If no corresponding test → CRITICAL gap
Common edge cases to check:
// Empty/null/undefined
if (!value) { ... } // ❓ Tested with null, undefined, ""?
if (array.length === 0) { ... } // ❓ Tested?
// Boundaries
if (value > MAX) { ... } // ❓ Tested with MAX, MAX+1?
if (value < MIN) { ... } // ❓ Tested with MIN, MIN-1?
// Special characters
if (input.includes(' ')) { ... } // ❓ Tested with unicode, emojis?
// Async timeouts
await fetch(url, { timeout: 5000 }) // ❓ Tested with timeout?
For each pattern, check if test exists covering that case.
Use for: Generating Scout API tests for untested RBAC paths
After finding untested RBAC gap:
1. /test-coverage-analyzer identifies gap
2. /api-test-generator creates test suite
→ Includes RBAC test (viewer → 403)
3. Run tests, verify coverage improved
Use for: Ensuring new tests don't introduce flakes
After adding new tests:
1. /test-coverage-analyzer generates tests
2. Developer implements tests
3. /flake-hunter validates with 50-run protocol
4. Coverage improved + no flakes introduced
Use in: Phase 5 (Comprehensive QA)
@spike-builder Phase 5 Step 5.1:
→ Invokes /test-coverage-analyzer
- Identifies gaps in spike implementation
- Generates missing E2E test scenarios
- Ensures comprehensive coverage before demo
Use for: Logging coverage improvement as evidence
After improving coverage 78% → 92%:
→ /promotion-evidence-tracker
- Logs as Problem Solving & Impact
- Metrics: +13.5% line coverage, 23 critical gaps fixed
- Category: Quality improvement initiative
📊 Test Coverage Analysis: Security Solution - Endpoint Isolation
**Current Coverage:** 78.5% lines, 65.2% branches
**Target Coverage:** 92.0% lines, 85.0% branches
**Gaps Found:** 58 total
- CRITICAL: 8 gaps (fix immediately)
- HIGH: 15 gaps (fix before release)
- MEDIUM: 22 gaps (nice to have)
- LOW: 13 gaps (optional)
**Quick Wins:** 14 tests (2-3 hours, high impact)
**Full report:** coverage-analysis-endpoint-isolation.md
# Test Coverage Analysis: Endpoint Isolation
[Full report with all gaps, test snippets, metrics, tracking]
Location: ~/.agents/coverage-reports/endpoint-isolation-[timestamp].md
After running @test-coverage-analyzer:
After implementing recommendations:
Explicit invocation:
Auto-trigger scenarios:
Developer: "Is this feature ready to release?"
1. /test-coverage-analyzer
→ Analyzes coverage
→ Finds 8 CRITICAL gaps
→ Report: "❌ Not ready - 8 CRITICAL gaps found"
2. Developer implements recommended tests (2-3 hours)
3. /test-coverage-analyzer (re-run)
→ Re-analyzes coverage
→ Report: "✅ Ready - 0 CRITICAL gaps, 92% coverage"
4. Feature released with confidence
Reviewer: "What's the test coverage for this PR?"
1. /test-coverage-analyzer
→ Analyzes changed files only
→ Finds 3 HIGH gaps in new code
→ Generates test recommendations
2. Developer adds 3 tests
3. /test-coverage-analyzer (re-run)
→ Verifies gaps fixed
→ Report: "✅ All new code tested"
4. PR approved
Team lead: "Improve test coverage in Detection Engine"
1. /test-coverage-analyzer
→ Analyzes entire package
→ Finds 45 gaps (12 CRITICAL, 18 HIGH, 15 MEDIUM)
→ Generates improvement plan
2. Team divides work (3 engineers × 1 week)
3. /test-coverage-analyzer (daily tracking)
→ Updates progress dashboard
→ Day 1: 12 → 8 CRITICAL
→ Day 3: 8 → 2 CRITICAL
→ Day 5: 2 → 0 CRITICAL ✅
4. /promotion-evidence-tracker
→ Logs as Technical Leadership
→ Metrics: 68% → 92% coverage, 45 gaps → 0 CRITICAL
Suggested coverage thresholds:
| Code Type | Minimum Coverage | Target Coverage |
|---|---|---|
| Backend APIs | 80% lines, 70% branches | 95% lines, 85% branches |
| Business logic | 85% lines, 75% branches | 95% lines, 90% branches |
| UI components | 70% lines, 60% branches | 85% lines, 75% branches |
| Utils/helpers | 75% lines, 65% branches | 90% lines, 80% branches |
CRITICAL gap tolerance: 0 (block merge if any found) HIGH gap tolerance: ≤3 (warn, but allow if documented)
Track coverage trends over time:
# Store coverage snapshot
coverage-history/
2026-03-20.json # { lines: 78.5%, branches: 65.2%, gaps: 58 }
2026-03-21.json # { lines: 82.3%, branches: 68.1%, gaps: 42 }
2026-03-22.json # { lines: 88.7%, branches: 78.5%, gaps: 18 }
# Generate trend chart
→ "Coverage improved +10.2% in 2 days (58 → 18 gaps)"
Analyze coverage for PR changes only:
# Get changed files in PR
git diff main...HEAD --name-only --diff-filter=AM
# Run coverage for changed files only
yarn test:jest --coverage --collectCoverageFrom='<changed-files>'
# Analyze only changed code paths
→ "This PR adds 3 new code paths, 2 are tested, 1 is missing tests"
Benefit: Focus on new code, not entire codebase
Detect weak tests (tests that pass even when code is broken):
# Use Stryker for mutation testing
npx stryker run
# Identify tests that don't catch mutations
→ "3 tests pass even when error handler is removed - tests are too weak"
Recommendation: Strengthen tests with specific assertions
A coverage analysis is complete when:
Always test:
Always test:
Always test:
Problem: 100% coverage includes trivial code (getters, simple formatters)
Better: Focus on 90-95% with ALL critical paths tested
Problem: Tests that break when refactoring (brittle)
// ❌ Bad: Tests internal variable
expect(component.state.internalCounter).toBe(5);
// ✅ Good: Tests observable behavior
expect(component.getDisplayValue()).toBe('5 items');
Problem: High line coverage but low branch coverage = untested conditionals
// Lines: 100% (all 3 lines executed in tests)
// Branches: 50% (only if-branch tested, not else)
if (condition) {
doSomething(); // ✅ Tested
} else {
doOtherThing(); // ❌ Not tested
}
Fix: Add test for else branch
# Run coverage (scoped to package)
yarn test:jest --coverage --collectCoverageFrom='x-pack/plugins/<plugin>/**/*.ts'
# Generate HTML report (open in browser)
yarn test:jest --coverage --coverageReporters=html
open coverage/lcov-report/index.html
# Find untested error handlers
grep -rn "catch\|throw" --include="*.ts" | while read line; do
file=$(echo $line | cut -d: -f1)
grep -q "$(basename $file .ts).test.ts" && echo "✅ $line" || echo "❌ $line"
done
# Find untested RBAC checks
grep -rn "forbidden\|requiredPrivileges" --include="*.ts" | \
grep -v ".test.ts"
# Check coverage summary
cat coverage/coverage-summary.json | jq '.total'
Time investment:
Value:
Ready to find your coverage gaps! 🔍
What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub patrykkopycinski/patryks-treadmill-claude-plugins --plugin kibana-testing-tools9 skills in this plugin
/api-test-generatorAuto-generate comprehensive Scout API tests from Kibana route definitions, including valid/invalid request tests, RBAC tests, and schema-driven test data generation./cypress-to-scout-migratorStrategic test suite optimizer for Cypress→Scout migration. Analyzes entire test coverage, identifies blind spots, refactors for performance and DRY principles, then generates optimized Scout suites. Not a 1:1 converter.
/flake-hunterIdentify, debug, and fix flaky tests systematically by detecting root causes, applying targeted fixes, and verifying stability to eliminate intermittent CI failures.