Logotipo de Code Coverage Analysis

Code Coverage Analysis

Comunidad
PramodDutta
Code Coverage Analysis

Measure and enforce test coverage with Istanbul/nyc, c8, Jest, and Vitest. Covers branch versus line coverage, per-directory thresholds, CI gates, and correctly excluding generated code from reports.

Descripción general

EditorPramodDutta
Repositorioqaskills
Nombre de la habilidadCode Coverage Analysis
Estrellas
239
Forks
31
Archivos incluidos
Solo instrucciones
LicenciaMIT
Enlaces
  • Instrucciones en Markdown

    Un archivo SKILL.md que el modelo carga cuando lo necesita, de modo que solo consume tokens cuando la petición encaja con la habilidad.

  • Funciona con cualquier LLM

    Las habilidades de IA están en Markdown, no en código específico de un proveedor, por lo que funcionan con GPT, Claude, Gemini, Grok o un modelo local.

  • Todo en las instrucciones

    Todo lo que necesita el modelo está en las instrucciones: no hay archivos adicionales que sincronizar.

  • Código abierto

    Publicada por PramodDutta en GitHub. Revisa el contenido original antes de instalarla.

Instalación

Instala la habilidad de IA Code Coverage Analysis en TypingMind para usarla con cualquier LLM, o añádela a otro agente que lea SKILL.md.

1

Instalar en TypingMind

TypingMind instala una habilidad directamente desde su carpeta de GitHub: lee SKILL.md, empaqueta los archivos de recursos y guarda el resultado localmente.

  1. Abre la aplicación y ve a Plugins → Habilidades.
  2. Elige «Instalar desde GitHub».
  3. Pega la URL de la carpeta de la habilidad que se muestra a continuación y confirma.
    https://github.com/PramodDutta/qaskills/tree/main/seed-skills/code-coverage
  4. Activa la habilidad en cada chat en el que quieras tenerla disponible.
Plugins → Habilidades → Añadir habilidad → URL de GitHub; después, pega la URL de la carpeta y pulsa Continuar.
2

Instalar en otro agente

Cualquier agente que lea el formato Agent Skills puede usar esta habilidad: copia la carpeta en el directorio de habilidades de ese agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/PramodDutta/qaskills.git /tmp/qaskills
mkdir -p .claude/skills
cp -r /tmp/qaskills/seed-skills/code-coverage .claude/skills/pramoddutta-code-coverage-analysis
Reinicia Claude Code después de copiarla para que detecte la nueva habilidad.

Úsala en TypingMind

Activa Code Coverage Analysis en cualquier chat de TypingMind y el modelo se encargará del resto. Su nombre y descripción se incluyen en el prompt del sistema y, en cuanto una petición encaja con la habilidad, el modelo carga las instrucciones completas por sí solo. No tienes que invocarla manualmente y no consume tokens hasta que se utiliza.

El modelo carga Code Coverage Analysis automáticamente en cuanto una petición es relevante para esa habilidad.

Funciona con cualquier modelo de IA

Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que Code Coverage Analysis no está vinculada al modelo para el que se creó. Instálala una sola vez en TypingMind y úsala con GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama o un modelo local que ejecutes tú, todo con tus propias claves API.

  • Se carga solo cuando se necesita

    El prompt del sistema solo incluye el nombre y la descripción. Las instrucciones se cargan con la primera petición que encaja con la habilidad, por lo que una habilidad que no se usa no supone ningún coste.

  • Cambia de modelo durante el chat

    Como la habilidad contiene instrucciones y no código, cambiar de modelo no impide que funcione: el nuevo modelo lee el mismo archivo SKILL.md.

Instrucciones de la habilidad

Este es el contenido de SKILL.md que carga el modelo. Léelo antes de instalar la habilidad: contiene instrucciones que tu modelo seguirá.

Code Coverage Analysis

This skill makes an AI agent configure coverage collection correctly (Istanbul instrumentation or V8 native coverage), set thresholds that fail builds, read coverage reports to find genuinely untested branches, and exclude generated or config code so the numbers mean something. Trigger it when a user asks "what is our coverage", wants a coverage gate in CI, or when a coverage/ directory, --coverage flag, .nycrc, or coverageThreshold appears in the project.

Core Principles

  1. Branch coverage is the number that matters. Line coverage marks a line as hit even if only one of its outcomes ran. A guard clause if (a && b) return x; can be 100 percent line-covered with three of its four branch outcomes untested.
  2. Coverage is a gap detector, not a quality score. 95 percent coverage with assertion-free tests proves nothing. Use coverage to find untested code paths; use mutation testing to check assertion strength.
  3. Thresholds must fail the build. A coverage report nobody reads is decoration. Wire coverageThreshold (Jest), thresholds (Vitest), or --check-coverage (nyc/c8) so CI goes red on regression.
  4. Set thresholds at current reality, then ratchet. Dropping a 90 percent global gate onto a 60 percent codebase makes the team delete the gate. Start at today's number minus 1, raise it as coverage improves.
  5. Measure all files, not just imported ones. By default some tools only report files touched by tests, so a completely untested module is invisible. Enable all: true (nyc), coverage.all (Vitest), or a broad collectCoverageFrom (Jest).
  6. Exclude generated code explicitly. Protobuf stubs, GraphQL codegen, migrations, and *.d.ts inflate or deflate numbers randomly. Exclude them in config, never by sprinkling ignore comments through generated files.

Setup and Patterns

1. Jest: collection, thresholds, and per-directory gates

js
// jest.config.js
module.exports = {
  preset: 'ts-jest',
  collectCoverage: true,
  coverageProvider: 'v8',
  collectCoverageFrom: [
    'src/**/*.{ts,tsx}',
    '!src/**/*.d.ts',
    '!src/**/__generated__/**',
    '!src/**/*.stories.tsx',
    '!src/test-utils/**',
  ],
  coverageReporters: ['text', 'lcov', 'json-summary'],
  coverageThreshold: {
    global: {
      branches: 80,
      functions: 85,
      lines: 90,
      statements: 90,
    },
    // Money-handling code gets a stricter gate
    './src/lib/payments/': {
      branches: 95,
      lines: 98,
    },
  },
};
bash
npx jest --coverage --ci
# Exit code is 1 if any threshold is missed; CI fails automatically

2. nyc (Istanbul) for Mocha or plain Node scripts

json
{
  "all": true,
  "include": ["src/**/*.ts"],
  "exclude": ["**/*.spec.ts", "src/generated/**", "src/migrations/**"],
  "reporter": ["text", "html", "lcov"],
  "check-coverage": true,
  "branches": 80,
  "lines": 90,
  "functions": 85,
  "statements": 90
}

Save as .nycrc.json, then:

bash
npm install --save-dev nyc
npx nyc mocha 'test/**/*.spec.ts'
npx nyc report --reporter=text-summary

3. c8: native V8 coverage with zero instrumentation

c8 reads V8's built-in coverage, so it works with the Node test runner and needs no transpile-time instrumentation:

bash
npm install --save-dev c8
npx c8 --all --src src --reporter=text --reporter=lcov \
  --lines 90 --branches 80 --check-coverage \
  node --test test/

4. Vitest: built-in V8 coverage with thresholds

ts
// vitest.config.ts
import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    coverage: {
      provider: 'v8',
      all: true,
      include: ['src/**/*.ts'],
      exclude: ['src/generated/**', 'src/**/*.test.ts', '**/*.config.ts'],
      reporter: ['text', 'lcov', 'json-summary'],
      thresholds: {
        lines: 90,
        branches: 80,
        functions: 85,
        statements: 90,
        // Fail if coverage DROPS below auto-updated values
        autoUpdate: false,
      },
    },
  },
});
bash
npx vitest run --coverage

5. Branch versus line coverage, concretely

ts
// shipping.ts
export function shippingCost(country: string, total: number): number {
  if (country === 'US' && total > 50) return 0;
  return country === 'US' ? 5 : 15;
}

// shipping.test.ts -- this single test yields 100% LINE coverage
import { shippingCost } from './shipping';

it('ships free for large US orders', () => {
  expect(shippingCost('US', 100)).toBe(0);
});
// But branch coverage shows: total <= 50 untested, non-US untested,
// the $5 domestic path untested. Three real behaviors have no test.

The branch report (text reporter prints % Branch per file, the HTML report highlights yellow I/E markers) is how you find these.

6. Ignoring unreachable code the honest way

ts
// Istanbul-instrumented runners (nyc, babel-plugin-istanbul)
/* istanbul ignore next -- @preserve defensive guard, unreachable after zod validation */
if (typeof input !== 'string') throw new TypeError('input must be a string');

// V8-based runners (vitest --coverage.provider=v8, c8)
/* v8 ignore next 2 */
if (process.platform === 'win32') {
  pathSeparator = '\\';
}

Every ignore comment needs a reason suffix; an ignore without a justification is a coverage lie waiting to rot.

7. CI gate plus PR summary

yaml
# .github/workflows/test.yml (excerpt)
- name: Test with coverage gate
  run: npx vitest run --coverage

- name: Print coverage summary to job log
  if: always()
  run: |
    pct_lines=$(jq -r '.total.lines.pct' coverage/coverage-summary.json)
    pct_branches=$(jq -r '.total.branches.pct' coverage/coverage-summary.json)
    echo "### Coverage: ${pct_lines}% lines / ${pct_branches}% branches" >> "$GITHUB_STEP_SUMMARY"

- name: Upload lcov for review tooling
  uses: actions/upload-artifact@v4
  with:
    name: lcov-report
    path: coverage/lcov.info

Best Practices

  • Review the HTML report (coverage/index.html) when writing tests for legacy code; the red/yellow highlighting finds untested branches faster than reading source.
  • Track coverage trends per package in a monorepo rather than one blended global number that averages away problems.
  • Gate on json-summary totals for speed, keep lcov output for editors and review tools that show per-line coverage in diffs.
  • Prefer the V8 provider for TypeScript projects; Istanbul instrumentation of transpiled output can misattribute branches to source maps.
  • Delete dead code instead of ignoring it; an istanbul ignore on reachable code is technical debt with a receipt.
  • For bug fixes, check the coverage diff: the fixed lines must be covered by the new regression test.

Anti-Patterns

  • Chasing 100 percent: the last few points usually buy tests for getters and logging branches while real risk lives in untested integration seams.
  • Writing tests that execute code without asserting anything, purely to move the number. Mutation testing will expose these instantly.
  • Excluding files from coverage because they are "hard to test" - that is the highest-risk code in the repository.
  • A global threshold so low (40 percent) that it never fires; gates that cannot fail teach the team to ignore them.
  • Measuring coverage only on unit tests when most behavior is exercised by integration tests; merge reports (nyc merge, --coverage.reportsDirectory per suite plus lcov merge) before judging.
  • Letting coverage/ get committed; add it to .gitignore.

When to Trigger This Skill

  • The user asks "what is our test coverage", "add a coverage gate", "why is coverage dropping", or "enforce 80 percent coverage".
  • A PR adds --coverage, coverageThreshold, .nycrc, c8, or @vitest/coverage-v8 to the project.
  • CI needs a quality gate tied to lines/branches/functions, or thresholds need ratcheting after a coverage push.
  • Generated code (GraphQL codegen, protobuf, ORM migrations) is skewing the numbers and needs principled exclusion.
  • Pair it with mutation testing when the user suspects high coverage numbers but weak assertions.

Preguntas frecuentes

¿Qué hace la habilidad de IA Code Coverage Analysis?

Measure and enforce test coverage with Istanbul/nyc, c8, Jest, and Vitest. Covers branch versus line coverage, per-directory thresholds, CI gates, and correctly excluding generated code from reports.

¿Por qué usar Code Coverage Analysis en TypingMind?

Porque la instalas una vez y la usas con cualquier modelo. Code Coverage Analysis está escrita en Markdown, no en código específico de un proveedor, por lo que la misma habilidad funciona con GPT-5, Claude, Gemini, Grok o un modelo local, y puedes cambiar de modelo en mitad del chat sin que deje de funcionar. TypingMind utiliza tus propias claves API, de modo que pagas directamente a los proveedores en lugar de pagar una suscripción por puesto, y tus habilidades y chats permanecen en tu propio almacenamiento.

¿Cómo instalo Code Coverage Analysis en TypingMind?

Abre Plugins → Habilidades → Instalar desde GitHub en TypingMind y pega https://github.com/PramodDutta/qaskills/tree/main/seed-skills/code-coverage. TypingMind lee el archivo SKILL.md de esa carpeta e instala su contenido como una habilidad que puedes activar en cada chat.

¿Qué modelos de IA pueden usar Code Coverage Analysis?

Cualquier modelo que conectes en TypingMind. Las habilidades de IA son instrucciones en Markdown, no código específico de un proveedor, por lo que GPT, Claude, Gemini, Grok y los modelos locales pueden cargar esta habilidad cuando una solicitud se corresponda con ella.

¿Con cuántos modelos de IA puedo usar Code Coverage Analysis?

Con tantos como quieras. Siempre que un modelo admita habilidades, puedes usar Code Coverage Analysis con él: GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama y muchos más, todos en TypingMind con tus propias claves API.

¿Es gratuita la habilidad de IA Code Coverage Analysis?

Sí. PramodDutta la ha publicado en GitHub bajo la licencia MIT. Solo pagas a tu proveedor de IA por los tokens que utilizas.

¿Qué son las habilidades de IA?

Una habilidad de IA es un conjunto de instrucciones reutilizables que enseña a un modelo de IA a realizar una tarea concreta. Sigue el formato abierto Agent Skills: un archivo SKILL.md con un nombre y una descripción, además de los scripts, plantillas o archivos de referencia que pueda necesitar el modelo. El modelo solo lee las instrucciones cuando tu solicitud se corresponde con la habilidad, por lo que una habilidad instalada no supone ningún coste hasta que se utiliza.

¿En qué se diferencian las habilidades de IA de los plugins o los servidores MCP?

Un plugin o un servidor MCP proporciona al modelo nuevas herramientas que puede invocar: código que se ejecuta en algún lugar y devuelve un resultado. En cambio, una habilidad de IA aporta conocimientos y procedimientos al modelo: cómo abordar una tarea, qué pasos seguir y qué se considera un buen resultado. Las habilidades son instrucciones en Markdown, por lo que no necesitan servidor, clave API ni entorno de ejecución, y funcionan con cualquier modelo.

Ver el directorio

Crea ya tu propio espacio de trabajo con IA

Suscríbete a nuestro boletín para recibir avisos sobre nuevas funciones y próximos sorteos 👇