0
0
JenkinsHow-ToBeginner · 4 min read

How to Run Tests in Jenkins Pipeline: Syntax and Example

To run tests in a Jenkins Pipeline, use the sh or bat step to execute your test commands inside a stage. Wrap test execution in a stage block and use post steps to handle test results or failures.
📐

Syntax

A Jenkins Pipeline runs tests inside a stage using shell commands with sh (Linux/macOS) or bat (Windows). The basic syntax includes:

  • pipeline: Defines the pipeline script.
  • agent: Specifies where to run the pipeline.
  • stages: Groups multiple stage blocks.
  • stage: Defines a step like running tests.
  • steps: Contains commands to execute.
groovy
pipeline {
    agent any
    stages {
        stage('Run Tests') {
            steps {
                sh 'your-test-command'
            }
        }
    }
}
💻

Example

This example runs unit tests using npm test in a Jenkins Pipeline on a Linux agent. It shows how to run tests and mark the build as failed if tests fail.

groovy
pipeline {
    agent any
    stages {
        stage('Install Dependencies') {
            steps {
                sh 'npm install'
            }
        }
        stage('Run Tests') {
            steps {
                sh 'npm test'
            }
        }
    }
    post {
        failure {
            echo 'Tests failed!'
        }
        success {
            echo 'Tests passed!'
        }
    }
}
Output
[INFO] Running tests... > npm test > jest Test Suites: 5 passed, 5 total Tests: 20 passed, 20 total Snapshots: 0 total Time: 3.5s Tests passed!
⚠️

Common Pitfalls

Common mistakes when running tests in Jenkins Pipeline include:

  • Not using sh or bat to run test commands, causing no tests to run.
  • Ignoring test failures by not checking exit codes, so the pipeline continues even if tests fail.
  • Running tests outside a stage, making the pipeline hard to read and debug.
  • Not installing dependencies before running tests.
groovy
pipeline {
    agent any
    stages {
        stage('Run Tests') {
            steps {
                // Wrong: just echoing test command, tests won't run
                sh 'echo npm test'
                
                // Right: actually run tests
                sh 'npm test'
            }
        }
    }
}
📊

Quick Reference

Tips for running tests in Jenkins Pipeline:

  • Use sh for Linux/macOS and bat for Windows agents.
  • Always run tests inside a stage for clarity.
  • Use post blocks to handle success or failure notifications.
  • Install dependencies before running tests.
  • Check test exit codes to fail the build on test failures.

Key Takeaways

Run tests inside a dedicated stage using sh or bat steps.
Always install dependencies before running tests to avoid failures.
Use post blocks to handle test success or failure notifications.
Ensure test commands return proper exit codes to fail the build on test errors.
Keep your pipeline stages clear and organized for easier debugging.