ScreenshotNeo

BlogHow-to

How to Integrate Selenium WebDriver with Jenkins

Run Selenium WebDriver tests in Jenkins with a repeatable Pipeline, local browsers or Selenium Grid, useful reports, and practical troubleshooting.

By the ScreenshotNeo team4 October 202610 min read

Direct answer: Run your existing Selenium test command as a stage in a Jenkins Pipeline on an agent that has the project runtime and a usable browser environment. For a small suite, install the browser on that agent. Use Selenium Grid when tests need remote browsers, parallel capacity, or operating system and browser coverage. Publish test reports and preserve failure artifacts so the build explains what failed.

Jenkins orchestrates the build; Selenium remains a dependency of your test project. You do not need a Selenium-specific Jenkins job or plugin for a standard integration.

1. Make the test suite run outside Jenkins

Before changing Jenkins, confirm the suite runs with the same command a developer uses locally. Identify its runtime, test framework, browser, browser driver, required environment variables, and report output. This prevents Jenkins configuration from concealing missing project setup.

For Java, add Selenium through the project’s build tool. The Selenium installation guide demonstrates the Maven dependency org.seleniumhq.selenium:selenium-java; use a release compatible with your Java baseline and check the current Selenium downloads rather than copying an old tutorial’s version number. See Selenium’s library installation guide.

<dependency>
  <groupId>org.seleniumhq.selenium</groupId>
  <artifactId>selenium-java</artifactId>
  <version>YOUR_COMPATIBLE_SELENIUM_VERSION</version>
</dependency>

Replace the version placeholder with a real release before building. Keep the version in the project’s normal dependency management so local development and Jenkins resolve the same one.

2. Run the suite in a Jenkins Pipeline

Commit a Jenkinsfile to the repository and start with the existing Maven test command. This Declarative Pipeline checks out source, runs tests, and asks Jenkins to collect JUnit XML reports even when the test step fails.

pipeline {
  agent any
  stages {
    stage('Checkout') {
      steps {
        checkout scm
      }
    }
    stage('WebDriver tests') {
      steps {
        sh 'mvn -B test'
      }
    }
  }
  post {
    always {
      junit 'target/surefire-reports/*.xml'
    }
  }
}

This example assumes a Unix-like agent, Maven, and Surefire reports at that path. Change sh to bat on Windows, use the repository’s actual test command, and adjust the report glob to match its framework and build layout. If tests do not produce JUnit XML, configure the test framework to do so or publish its supported report format with an appropriate Jenkins publisher.

Configure Jenkins-managed Maven and Java when useful

The Jenkins Pipeline Maven Integration plugin provides withMaven to configure Maven and can select Jenkins-managed JDK and Maven installations, settings files, and Maven report handling. Use it if your team manages those tools centrally; it is optional when the agent image or machine already supplies the required tools. See the Jenkins Pipeline Maven Integration steps.

pipeline {
  agent { label 'selenium-linux' }
  stages {
    stage('WebDriver tests') {
      steps {
        withMaven(maven: 'Maven-3', jdk: 'JDK-17') {
          sh 'mvn -B test'
        }
      }
    }
  }
  post {
    always {
      junit 'target/surefire-reports/*.xml'
    }
  }
}

The installation names are examples: define matching tool installations in Jenkins or omit the arguments and use the agent’s configured tools. Do not assume a particular Java version works with every Selenium, browser, or driver release; select compatible versions together.

3. Choose where the browser runs

Execution setup Good fit Things to manage
Browser on Jenkins agent Small suites and an initial CI setup Browser and driver availability, headless configuration, permissions, and agent consistency
Selenium Grid Remote browsers, parallel sessions, or browser and operating system coverage Grid deployment, network access, capacity, session cleanup, and endpoint security
Dockerized test agent Packaging runtime and browser dependencies into a repeatable stage Docker-capable agents, image maintenance, browser resources, and networking to a Grid

Use a browser installed on the Jenkins agent

This is the simplest topology: the Jenkins agent runs the test process and launches the installed browser. Install the browser supported by the project and ensure the agent’s operating-system user can launch it. Selenium’s Grid getting-started guide lists installed browsers and drivers among the prerequisites and notes that Selenium Manager can configure drivers automatically when enabled. Verify behavior with the versions you select; do not assume an old browser-driver pairing remains compatible. See Selenium Grid getting started.

For Linux agents, decide whether the browser runs headless and ensure the image or host includes required browser libraries and fonts. A successful shell command is not enough: run a small WebDriver test as the same user and in the same environment Jenkins uses.

Use Selenium Grid for remote browsers

Grid routes WebDriver commands to remote browser instances. It is useful when browser execution should be separate from build agents, when a test matrix spans browsers or platforms, or when multiple sessions need to run concurrently. Selenium documents standalone and Hub/Node deployment roles; its default RemoteWebDriver endpoint uses port 4444. Check the Grid overview and Grid setup guide for the chosen deployment.

For a Java suite, make the remote endpoint configurable so the same tests can run locally or against Grid. This example uses Selenium 4 APIs and a placeholder endpoint; supply a reachable Grid URL through the environment.

import java.net.URL;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.RemoteWebDriver;

public class GridSmokeTest {
  public static void main(String[] args) throws Exception {
    String gridUrl = System.getenv().getOrDefault(
        "SELENIUM_REMOTE_URL", "http://localhost:4444");
    WebDriver driver = new RemoteWebDriver(new URL(gridUrl), new ChromeOptions());
    try {
      driver.get("https://example.com");
      System.out.println(driver.getTitle());
    } finally {
      driver.quit();
    }
  }
}

In a test framework, create the driver in setup and always call quit() in teardown, including after assertion failures. A leaked session consumes Grid capacity and can cause later tests to wait or fail.

Keep the Grid endpoint on a private network or restrict it with firewall and access controls. Selenium warns that an exposed Grid can let outsiders access infrastructure, internal applications and files, or run binaries. Do not publish the endpoint directly to the public internet.

Use Docker when it improves repeatability

Jenkins Pipeline can run a stage in a Docker image when the Docker Pipeline plugin is installed and the agent is configured to run Docker. Package the required runtime and test dependencies in a maintained image or repository Dockerfile. Docker does not remove the need to manage browser versions, fonts, shared memory, or network access to Grid. Read Jenkins’ Docker with Pipeline guide and verify the selected image in your own agent environment.

pipeline {
  agent {
    docker {
      image 'maven:YOUR_APPROVED_TAG'
      args '--shm-size=2g'
    }
  }
  stages {
    stage('WebDriver tests') {
      steps {
        sh 'mvn -B test'
      }
    }
  }
  post {
    always {
      junit 'target/surefire-reports/*.xml'
    }
  }
}

This is a structural example, not a claim that the placeholder image contains your chosen browser or driver. Select and maintain an image that actually includes the required dependencies. If the browser is on a separate Grid, configure networking and the remote URL explicitly.

4. Make test results useful

  1. Publish machine-readable results. Use Jenkins’ JUnit step with the report path your framework generates. Keep it in post { always { ... } } so failed tests still produce results.
  2. Preserve failure evidence. Configure the test framework to save a screenshot, browser console output, and relevant logs on failure. Archive those files with Jenkins so a failed run can be diagnosed after the agent is gone.
  3. Separate product failures from environment failures. Identify whether the failure is an assertion, browser startup problem, missing driver, unreachable Grid, capacity exhaustion, or a version mismatch.
  4. Keep secrets out of source. Store credentials in Jenkins credentials and bind them only to the stage that needs them. Avoid printing tokens or sensitive test data to the build log.
  5. Make cleanup unconditional. Close browser sessions in test teardown and ensure temporary files are cleaned up. This matters especially for shared Grid capacity.

Report paths and artifact names depend on the test framework and repository. The example paths above are common Maven defaults, not a guarantee about every project.

5. Performance, reliability, and cost

  • Start with one worker. Establish a stable baseline before adding parallelism. Concurrent browser sessions need enough CPU and memory, and tests that share data may interfere with one another.
  • Size from observation. Selenium’s Grid guide offers a reference allocation of 1 CPU and 1 GB RAM per browser, while cautioning that actual needs vary and should be measured. Treat this as a starting point, not a universal capacity guarantee.
  • Reduce avoidable waiting. Use explicit waits for the condition under test instead of arbitrary long sleeps. Keep test setup deterministic and avoid repeatedly downloading dependencies or browser assets where the build environment can safely cache them.
  • Keep environments aligned. Pin and update Java, Selenium, browser, driver, and container versions as a compatible set. Uncontrolled agent updates can make previously stable tests fail differently across machines.
  • Budget for the whole run. Browser processes, Grid nodes, Docker-capable agents, and parallel workers consume infrastructure. More parallelism can shorten elapsed time while increasing concurrent resource use.
  • Retry selectively. A retry can help expose a transient infrastructure fault, but blanket retries can hide flaky tests. Preserve the original failure and track repeated instability.

6. Troubleshoot common Jenkins and Selenium failures

Symptom Likely cause What to check or change
mvn: command not found or tool not found Maven is absent from the agent or Jenkins tool configuration Install/configure Maven, use a managed installation with withMaven, or choose an agent image that includes it.
Browser binary cannot be found or launched Browser missing, wrong path, missing system libraries, or agent user lacks access Run a browser startup check as the Jenkins agent user; install the required browser dependencies and configure the binary path if needed.
Driver/browser version mismatch Browser and driver versions are incompatible, or the agent changed independently Pin compatible versions or use Selenium Manager where supported and enabled; inspect the browser and driver versions in the failing agent.
Tests pass locally but fail in CI Different browser, headless behavior, timezone, locale, fonts, permissions, network, or environment variables Compare local and agent versions and environment; capture browser logs and screenshots; make the needed environment explicit.
Grid connection refused or times out Wrong URL/port, DNS or firewall issue, Grid unavailable, or agent cannot reach its network Check the configured remote URL from the agent, Grid health, port access, and container networking. Do not expose Grid publicly to work around connectivity.
Session request waits or returns no capacity All Grid slots are occupied, sessions leaked, or requested capabilities are unavailable Ensure every test calls quit(), inspect node capacity and browser availability, and lower parallel workers or add capacity.
JUnit reports are missing The glob points to the wrong directory or tests did not emit XML Inspect the workspace after the test stage, configure the framework’s XML reporter, and update the junit glob.
Pipeline ends before reports publish Report publishing is only in the success path Move report collection to post { always { ... } } and confirm the agent workspace still contains the files.
Docker stage cannot start or reach Grid Agent lacks Docker support, image is unavailable, or container networking is wrong Confirm Docker Pipeline requirements on the agent, validate the image and permissions, and test Grid reachability from inside the container.
Tests hang or later builds become slower Browser sessions or processes are not closed; waits are indefinite; agent resources are exhausted Use unconditional teardown, bound waits, inspect process and resource usage, and cap concurrency to available capacity.

7. Avoid relying on the legacy Selenium Jenkins plugin

The Jenkins Selenium plugin page describes a legacy Selenium 3 Grid plugin and currently warns of absent CSRF protection and potential OS command injection; it also says the plugin is up for adoption. It should not be the default integration path for a new setup. Use a normal Pipeline to invoke the project’s test command, and evaluate any existing plugin deployment against its current security status. See the Jenkins Selenium plugin page.

Or skip the browser setup

If your immediate task is capturing a page image for a build artifact or visual review, ScreenshotNeo provides a website screenshot API and MCP server. One GET request returns PNG, JPEG, WebP, or PDF; the API has options for full-page captures, selectors, viewport and device settings, waiting, custom CSS or JavaScript, and more. It does not run your Selenium test suite or replace browser automation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests

r = requests.get(
    "https://api.screenshotneo.com/v1/shot",
    params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
    timeout=90,
)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

See the ScreenshotNeo API documentation for request options and response details. Cookie banners, newsletter popups, and chat widgets are removed before the shot; bot checks, blank pages, and failed loads are never billed. An MCP server lets AI agents use screenshot tools. The Free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000 shots. Sign up for 1,000 free screenshots a month, with no card.

Frequently asked questions

Does Jenkins need a Selenium plugin to run WebDriver tests?

No. A Pipeline can invoke the project’s test command directly. Add Jenkins plugins only for capabilities your team actually uses, such as Docker-based execution or Maven tool integration.

Should I run tests on every commit?

That depends on suite duration and the team’s feedback needs. A common approach is a fast relevant suite on change and broader browser coverage on a scheduled or release build; keep the trigger strategy consistent with your project’s risk and available capacity.

Can the same tests run locally and on Grid?

Yes. Make the remote endpoint configurable and choose local or remote driver creation through test configuration. Keep assertions and test behavior shared so the execution location does not change what the test verifies.

Is headless browser execution required on Jenkins?

No. Headless mode is a practical choice for agents without a display, but the browser still needs a valid runtime environment. Validate the selected browser mode on the actual agent image.

Sources