Course contentsShow
← JavaScript
Lesson 2722 of 2,72354. Testing in JavaScriptFree lesson

Ignoring Unreachable Code

Using coverage ignore comments and configuration to exclude generated code, type guards, and defensive checks.

Ignoring Unreachable Code

You'll learn how to exclude intentionally unreachable code from coverage reports using ignore comments and configuration.

Sometimes your codebase contains code that legitimately can't be covered by tests: generated files, defensive type guards that TypeScript already prevents, or safety checks for edge cases that can't occur in your test environment. Tracking these in coverage reports creates noise and makes it harder to spot real gaps.

The Core Idea

Coverage tools allow you to mark specific lines, blocks, or entire files as "ignored" using special comments. This tells the coverage tool: "Yes, I know this isn't covered, and that's intentional." The code remains in your source, but doesn't count against your coverage percentage.

Ignore Comments

Most coverage tools (like Istanbul/nyc used by Jest and Vitest) support these comments:

/* istanbul ignore next */
if (process.env.NODE_ENV === 'production') {
  // This branch only runs in production, not tests
}

/* istanbul ignore else */
if (userInput) {
  handleInput(userInput);
} else {
  // Defensive else that should never happen
}

/* istanbul ignore file */
// At the top of auto-generated files

Configuration-Level Ignoring

You can also exclude entire patterns in your coverage configuration:

// jest.config.js
module.exports = {
  coveragePathIgnorePatterns: [
    '/node_modules/',
    '/dist/',
    '/__generated__/',
    '\\.config\\.js$'
  ]
};

This approach works better for systematic exclusions like build artifacts, migrations, or generated GraphQL types.

Key Takeaway: Use ignore comments sparingly for genuinely unreachable code (like environment-specific branches or type guards), and configuration to exclude entire categories of files—this keeps your coverage metrics focused on code that actually needs testing.