5 minutes read

Complete Step-by-Step Jenkins Integration Guide

This comprehensive guide walks you through integrating the LoadFocus JMeter API Client with Jenkins to create automated, reliable performance testing pipelines that catch issues before they reach production.

Essential Setup: Getting Started with Jenkins Integration

1. Securely Store Your LoadFocus Credentials in Jenkins

First, properly secure your LoadFocus API credentials in Jenkins:

Is Your Infrastructure Ready for Global Traffic Spikes?

Unexpected load surges can disrupt your services. With LoadFocus’s cutting-edge Load Testing solutions, simulate real-world traffic from multiple global locations in a single test. Our advanced engine dynamically upscales and downscales virtual users in real time, delivering comprehensive reports that empower you to identify and resolve performance bottlenecks before they affect your users.

View Pricing
Real-time insights
Discover More
Global scalability
  1. Navigate to Jenkins Dashboard > Manage Jenkins > Manage Credentials
  2. Select the appropriate credential domain (e.g., global)
  3. Click “Add Credentials”
  4. Add the following credentials:
    • Kind: Secret text
    • Scope: Global
    • Secret: Your LoadFocus API key
    • ID: loadfocus-api-key
    • Description: LoadFocus API Key
  5. Repeat for your team ID with ID: loadfocus-team-id

2. Create a Powerful Jenkins Pipeline

Create a Jenkinsfile in your repository with this configuration:

pipeline {
    agent {
        docker {
            image 'node:16-alpine'
        }
    }
    
    environment {
        LOADFOCUS_API_KEY = credentials('loadfocus-api-key')
        LOADFOCUS_TEAM_ID = credentials('loadfocus-team-id')
    }
    
    stages {
        stage('Build') {
            steps {
                // Your build steps
                sh 'npm install'
                sh 'npm run build'
            }
        }
        
        stage('Test') {
            steps {
                // Your test steps
                sh 'npm test'
            }
        }
        
        stage('Performance Test') {
            steps {
                // Install LoadFocus JMeter API Client
                sh 'npm install -g @loadfocus/loadfocus-api-client'
                
                // Configure LoadFocus API Client
                sh 'loadfocus-api config set apiKey $LOADFOCUS_API_KEY'
                sh 'loadfocus-api config set teamId $LOADFOCUS_TEAM_ID'
                
                // Run Performance Tests
                sh '''
                    loadfocus-api jmeter run-test \
                      --name "Jenkins_${JOB_NAME}_${BUILD_NUMBER}" \
                      --thresholds "avgresponse<=200,errors==0,p95<=250" \
                      --format json > performance_results.json
                '''
                
                // Archive the results
                archiveArtifacts artifacts: 'performance_results.json', fingerprint: true
            }
        }
        
        stage('Deploy') {
            when {
                expression {
                    return currentBuild.resultIsBetterOrEqualTo('SUCCESS')
                }
            }
            steps {
                // Your deployment steps
                echo 'Deploying...'
            }
        }
    }
    
    post {
        always {
            // Clean up workspace
            cleanWs()
        }
    }
}

3. Configure Your Jenkins Job for Success

  1. Create a new Pipeline job in Jenkins
  2. Configure the Pipeline to use your Jenkinsfile
  3. Set up the appropriate SCM configuration to fetch your repository

Advanced Configuration Techniques

Parallel Testing: Run Multiple Tests Simultaneously

Optimize your pipeline with parallel performance tests:

pipeline {
    agent any
    
    environment {
        LOADFOCUS_API_KEY = credentials('loadfocus-api-key')
        LOADFOCUS_TEAM_ID = credentials('loadfocus-team-id')
    }
    
    stages {
        // Previous stages...
        
        stage('Performance Tests') {
            parallel {
                stage('API Performance') {
                    agent {
                        docker {
                            image 'node:16-alpine'
                        }
                    }
                    steps {
                        sh 'npm install -g @loadfocus/loadfocus-api-client'
                        sh 'loadfocus-api config set apiKey $LOADFOCUS_API_KEY'
                        sh 'loadfocus-api config set teamId $LOADFOCUS_TEAM_ID'
                        sh '''
                            loadfocus-api jmeter run-test \
                              --name "API_Performance_Test" \
                              --thresholds "avgresponse<=150,errors==0" \
                              --format json > api_performance_results.json
                        '''
                        archiveArtifacts artifacts: 'api_performance_results.json', fingerprint: true
                    }
                }
                
                stage('UI Performance') {
                    agent {
                        docker {
                            image 'node:16-alpine'
                        }
                    }
                    steps {
                        sh 'npm install -g @loadfocus/loadfocus-api-client'
                        sh 'loadfocus-api config set apiKey $LOADFOCUS_API_KEY'
                        sh 'loadfocus-api config set teamId $LOADFOCUS_TEAM_ID'
                        sh '''
                            loadfocus-api jmeter run-test \
                              --name "UI_Performance_Test" \
                              --thresholds "avgresponse<=300,errors==0" \
                              --format json > ui_performance_results.json
                        '''
                        archiveArtifacts artifacts: 'ui_performance_results.json', fingerprint: true
                    }
                }
            }
        }
        
        // Next stages...
    }
}

Scripted Pipeline: Maximum Flexibility for Complex Scenarios

For more control and conditional logic, use a scripted pipeline:

Think your website can handle a traffic spike?

Fair enough, but why leave it to chance? Uncover your website’s true limits with LoadFocus’s cloud-based Load Testing for Web Apps, Websites, and APIs. Avoid the risk of costly downtimes and missed opportunities—find out before your users do!

Effortless setup No coding required
node {
    def performanceTestPassed = false
    
    stage('Checkout') {
        checkout scm
    }
    
    stage('Build &amp; Test') {
        // Your build and test steps
    }
    
    stage('Performance Test') {
        docker.image('node:16-alpine').inside {
            withCredentials([
                string(credentialsId: 'loadfocus-api-key', variable: 'LOADFOCUS_API_KEY'),
                string(credentialsId: 'loadfocus-team-id', variable: 'LOADFOCUS_TEAM_ID')
            ]) {
                sh 'npm install -g @loadfocus/loadfocus-api-client'
                sh 'loadfocus-api config set apiKey $LOADFOCUS_API_KEY'
                sh 'loadfocus-api config set teamId $LOADFOCUS_TEAM_ID'
                
                try {
                    sh '''
                        loadfocus-api jmeter run-test \
                          --name "Jenkins_${JOB_NAME}_${BUILD_NUMBER}" \
                          --thresholds "avgresponse<=200,errors==0,p95<=250" \
                          --format json > performance_results.json
                    '''
                    
                    // Check if test passed by examining the JSON
                    def testResults = readJSON file: 'performance_results.json'
                    if (testResults.overallResult == 'PASSED') {
                        performanceTestPassed = true
                        echo "Performance test passed!"
                    } else {
                        echo "Performance test failed to meet thresholds!"
                        // Optional: Fail the build
                        // error "Performance test failed"
                    }
                } catch (Exception e) {
                    echo "Error running performance test: ${e.message}"
                }
                
                archiveArtifacts artifacts: 'performance_results.json', fingerprint: true
            }
        }
    }
    
    stage('Deploy') {
        if (performanceTestPassed) {
            echo 'Deploying...'
            // Your deployment steps
        } else {
            echo 'Skipping deployment due to performance test failure'
        }
    }
}

Shared Library: Create Reusable Performance Testing Components

Build reusable components for consistent testing across projects:

// vars/performanceTest.groovy
def call(Map config = [:]) {
    def testName = config.testName ?: "Jenkins_${env.JOB_NAME}_${env.BUILD_NUMBER}"
    def thresholds = config.thresholds ?: "avgresponse<=200,errors==0,p95<=250"
    def waitTimeout = config.waitTimeout ?: 1800
    def resultsFile = config.resultsFile ?: "performance_results.json"
    
    docker.image('node:16-alpine').inside {
        withCredentials([
            string(credentialsId: 'loadfocus-api-key', variable: 'LOADFOCUS_API_KEY'),
            string(credentialsId: 'loadfocus-team-id', variable: 'LOADFOCUS_TEAM_ID')
        ]) {
            sh 'npm install -g @loadfocus/loadfocus-api-client'
            sh 'loadfocus-api config set apiKey $LOADFOCUS_API_KEY'
            sh 'loadfocus-api config set teamId $LOADFOCUS_TEAM_ID'
            
            sh """
                loadfocus-api jmeter run-test \\
                  --name "${testName}" \\
                  --thresholds "${thresholds}" \\
                  --waitTimeout ${waitTimeout} \\
                  --format json > ${resultsFile}
            """
            
            archiveArtifacts artifacts: resultsFile, fingerprint: true
            
            // Return the test results
            def testResults = readJSON file: resultsFile
            return testResults
        }
    }
}

Then in your Jenkinsfile:

@Library('my-shared-library') _

pipeline {
    agent any
    
    stages {
        stage('Performance Test') {
            steps {
                script {
                    def results = performanceTest(
                        testName: "API_Performance_Test",
                        thresholds: "avgresponse<=150,errors==0"
                    )
                    
                    if (results.overallResult != 'PASSED') {
                        error "Performance test failed"
                    }
                }
            }
        }
    }
}

Powerful Plugin Integrations

Visualize Results with Performance Plugin

Use the Jenkins Performance Plugin to create insights from test results:

  1. Install the Performance Plugin in Jenkins
  2. Convert LoadFocus results to a format supported by the plugin (JMeter CSV or JUnit XML)
  3. Configure your pipeline:
stage('Performance Test') {
    steps {
        // Run LoadFocus test
        sh '''
            loadfocus-api jmeter run-test \
              --name "Jenkins_${JOB_NAME}_${BUILD_NUMBER}" \
              --thresholds "avgresponse<=200,errors==0,p95<=250" \
              --format json > performance_results.json
            
            # Convert to JMeter CSV format (using a custom script)
            node convert-to-jmeter.js performance_results.json performance_results.csv
        '''
        
        // Use Performance Plugin
        perfReport sourceDataFiles: 'performance_results.csv', 
                   errorFailedThreshold: 0, 
                   errorUnstableThreshold: 0, 
                   errorUnstableResponseTimeThreshold: '200'
    }
}

Automated Email Notifications with Test Results

Keep your team informed with detailed test results:

LoadFocus is an all-in-one Cloud Testing Platform for Websites and APIs for Load Testing, Apache JMeter Load Testing, Page Speed Monitoring and API Monitoring!

Effortless setup No coding required
post {
    always {
        script {
            if (fileExists('performance_results.json')) {
                def results = readJSON file: 'performance_results.json'
                def resultStatus = results.overallResult == 'PASSED' ? 'SUCCESS' : 'FAILURE'
                def subject = "Performance Test ${resultStatus}: ${env.JOB_NAME} #${env.BUILD_NUMBER}"
                
                // Create email body
                def body = """
                <h2>Performance Test Results</h2>
                <p><strong>Overall Result:</strong> ${results.overallResult}</p>
                <h3>Results by Label</h3>
                <table border="1">
                <tr><th>Label</th><th>Result</th><th>Avg Response</th><th>Errors</th></tr>
                """
                
                results.labels.each { label ->
                    body += """
                    <tr>
                        <td>${label.label}</td>
                        <td>${label.result}</td>
                        <td>${label.metrics.avgresponse}ms</td>
                        <td>${label.metrics.errors}</td>
                    </tr>
                    """
                }
                
                body += "</table>"
                
                emailext (
                    subject: subject,
                    body: body,
                    to: 'team@example.com',
                    attachmentsPattern: 'performance_results.json',
                    mimeType: 'text/html'
                )
            }
        }
    }
}

Expert Tips for Performance Testing in Jenkins

1. Smart Timeout Handling

Set appropriate timeouts for long-running performance tests:

stage('Performance Test') {
    options {
        timeout(time: 60, unit: 'MINUTES')
    }
    steps {
        // Performance test steps
    }
}

2. Strategic Conditional Execution

Run performance tests only when they’re most valuable:

stage('Performance Test') {
    when {
        anyOf {
            branch 'main'
            branch 'develop'
            tag pattern: "v\\d+\\.\\d+\\.\\d+", comparator: "REGEXP"
        }
    }
    steps {
        // Performance test steps
    }
}

3. Automated Scheduled Testing

Set up regular performance checks to catch regressions:

pipeline {
    agent any
    
    triggers {
        cron('0 0 * * *')  // Run at midnight every day
    }
    
    stages {
        // Pipeline stages
    }
}

4. Customizable Parameterized Tests

Make your tests flexible with customizable parameters:

pipeline {
    agent any
    
    parameters {
        string(name: 'TEST_NAME', defaultValue: 'API_Performance_Test', description: 'Name of the LoadFocus test to run')
        string(name: 'THRESHOLDS', defaultValue: 'avgresponse<=200,errors==0', description: 'Performance thresholds')
        string(name: 'WAIT_TIMEOUT', defaultValue: '1800', description: 'Maximum wait time in seconds')
    }
    
    stages {
        stage('Performance Test') {
            steps {
                // Run test with parameters
                sh """
                    loadfocus-api jmeter run-test \\
                      --name "${params.TEST_NAME}" \\
                      --thresholds "${params.THRESHOLDS}" \\
                      --waitTimeout ${params.WAIT_TIMEOUT} \\
                      --format json > performance_results.json
                """
            }
        }
    }
}

Start Transforming Your Testing Pipeline Today

By integrating the LoadFocus API Client with Jenkins, you’ll create a powerful performance testing pipeline that catches issues early and ensures your applications deliver consistently excellent performance. Follow this guide to implement a robust, automated approach that makes performance testing an integral part of your development process.

For more information, visit Jenkins documentation and LoadFocus API Client documentation.

How fast is your website? Free Website Speed Test