Certified Jenkins Engineer

Code Quality and Testing

Demo Code Coverage and Catch Errors

This tutorial walks you through extending your Jenkins Pipeline to generate code coverage metrics, handle coverage failures gracefully with catchError, and publish an HTML coverage report. You’ll update your Jenkinsfile, use the Credentials Binding and HTML Publisher plugins, and ensure downstream stages always run.

Pipeline Stages Overview

Stage NamePurposeCommand
Installing DependenciesInstall application dependenciesnpm install
Dependency ScanningRun security and vulnerability scansnpm audit
Unit TestingExecute unit testsnpm test
Code CoverageGenerate coverage metricsnpm run coverage

1. Add the Code Coverage Stage

Open your Jenkinsfile and duplicate the Unit Testing stage for coverage:

pipeline {
  agent any
  stages {
    stage('Installing Dependencies') {
      steps {
        sh 'npm install'
      }
    }
    stage('Dependency Scanning') {
      steps {
        sh 'npm audit'
      }
    }
    stage('Unit Testing') {
      steps {
        withCredentials([usernamePassword(
          credentialsId: 'mongo-db-credentials',
          usernameVariable: 'MONGO_USERNAME',
          passwordVariable: 'MONGO_PASSWORD'
        )]) {
          sh 'npm test'
        }
      }
    }
    stage('Code Coverage') {
      steps {
        withCredentials([usernamePassword(
          credentialsId: 'mongo-db-credentials',
          usernameVariable: 'MONGO_USERNAME',
          passwordVariable: 'MONGO_PASSWORD'
        )]) {
          sh 'npm run coverage'
        }
      }
    }
  }
}

Commit and push to trigger a new build.

2. Observe the Coverage Failure

If coverage falls below your global threshold (e.g., 90%), the pipeline will fail:

> npm run coverage
…
ERROR: Coverage for lines (79.1%) does not meet global threshold (90%)
…
script returned exit code 1

The image shows a Jenkins pipeline interface for a project named "solar-system," displaying the stages of a build process with a failure at the "Code Coverage" stage. The details below indicate a failed "npm run coverage" shell script."

3. Introduce catchError

Wrap the coverage command in catchError so the stage becomes UNSTABLE instead of FAILED, allowing later stages to run.

Note

The catchError step lets you control both the stage and build result. For full syntax, see the Jenkins Pipeline Syntax reference.

Example using the Snippet Generator or manual insertion:

catchError(
  buildResult: 'SUCCESS',
  stageResult: 'UNSTABLE',
  message: 'Coverage below threshold; will be fixed soon'
) {
  sh 'npm run coverage'
}

The image shows a Jenkins interface with a "Snippet Generator" for creating pipeline scripts. It includes options for handling errors, with a message input field containing "Oops!" and settings for build and stage results on error.

4. Update the Jenkinsfile

Combine catchError with the HTML Publisher plugin to publish coverage reports:

pipeline {
  agent any
  stages {
    // ... previous stages ...
    stage('Code Coverage') {
      steps {
        withCredentials([usernamePassword(
          credentialsId: 'mongo-db-credentials',
          usernameVariable: 'MONGO_USERNAME',
          passwordVariable: 'MONGO_PASSWORD'
        )]) {
          catchError(
            buildResult: 'SUCCESS',
            stageResult: 'UNSTABLE',
            message: 'Coverage below threshold; will be fixed soon'
          ) {
            sh 'npm run coverage'
          }
        }
        publishHTML([
          allowMissing: true,
          alwaysLinkToLastBuild: true,
          keepAll: true,
          reportDir: 'coverage/lcov-report',
          reportFiles: 'index.html',
          reportName: 'Code Coverage HTML Report'
        ])
      }
    }
  }
}

Push your changes.

5. Verify the Results

Rerun the pipeline. The Code Coverage stage will be marked UNSTABLE and subsequent stages will still execute.

View the build history and status in the Jenkins dashboard:

The image shows a Jenkins dashboard displaying a list of recent build activities for a project named "solar-system" under the "Gitea-Organization." It includes details such as status, run number, commit ID, branch, message, duration, and completion time.

In the Pipeline view, stages reflect their new statuses:

The image shows a Jenkins build pipeline interface, displaying the status of various stages such as SCM checkout, tool installation, dependency scanning, and unit testing, with some stages marked as successful and others with issues.

6. View the HTML Coverage Report

Click Code Coverage HTML Report in Jenkins to open coverage/lcov-report/index.html. You’ll see detailed metrics for each file—e.g., for app.js:

  • Statement coverage: 79.54%
  • Branch coverage: 33.33%
  • Function coverage: 70%
  • Line coverage: 79.06%

The image shows a code coverage report for a file named "app.js," indicating 79.54% statement coverage, 33.33% branch coverage, 70% function coverage, and 79.06% line coverage.

You can also view this report in Blue Ocean or any HTML-compatible Jenkins plugin.


Watch Video

Watch video content

Previous
Demo Using Options Directive