Skip to main content

Cross-Browser Testing with TestGrid Selenium Using Local Execution

Overview

The open-source Selenium toolkit is primarily used to automate web browsers.
Chrome, Firefox, Safari, Edge, and Opera are just a few of the web browsers that Selenium supports. This makes it possible for testers to conduct cross-browser testing to guarantee uniform behavior across various browsers.
For quicker results, you can quickly set up and test your web browser’s local code using Selenium with TestGrid.

Prerequisites

  • TestGrid login credentials
  • Java Development Kit (JDK): Install the latest version of JDK on your machine. Appium is compatible with JDK 8 or later versions.
  • Integrated Development Environment (IDE): Choose an IDE to write and execute your Java Appium code. Popular choices include IntelliJ IDEA, Eclipse, or NetBeans. Make sure your IDE is properly installed and configured.
  • Selenium Java Client: Add the Selenium Java Client dependency to your Java project. Using a build automation tool like Maven or Gradle, you can include the Selenium client library. The Selenium Java client allows you to interact with the Selenium server using Java code.
  • Selenium provides official Java client libraries that implement the W3C WebDriver protocol.
    You should use these Selenium client libraries to interact with web browsers instead of generic WebDriver implementations.

Start configuring your local Java or other language code right away.

Step 1: Open the Device Cloud tab and locate the appropriate browser’s information for running.

  • Login with TestGrid credentials and go to the Devices Cloud option tab.

Once the device cloud screen appears, you can find several devices and browsers there.

Step 2: Now, Choose the browser in which you want to run your local Selenium code.

Step 3: Select the browser and update the “Browser Run URL (Public)” and “Browser Type” provided in your local Selenium code.

  • When you click on the ‘i’ button, you will see the device information and desired capabilities window.

Notes: To use our device cloud with Web local execution, the following list of capabilities must be used:
For example

{
"browserName": "Chrome",
"platformName": "Linux",
"tg:userToken": "your-user-token",
"browserUrl": "http://{Your_Domain}.testgrid.io:351411/wd/hub",
"tg:udid": "your-device-udid",
}

Step 4: Steps to execute local Selenium code.

  • TG_BROWSER_URL
  • setBrowserName capability to one of the following:
    • BrowserType.CHROME
    • BrowserType.FIREFOX
    • BrowserType.EDGE
    • BrowserType.SAFARI
  • TG_UDID
  • TG_USER_TOKEN

NoteIn the TestGrid Local Execution flow, the driver.quit(); method must be called at the end of each test case.

  • This ensures the active session is properly closed.
  • All test results will be correctly reflected, including:
  • Test Case Name
  • Test Case Steps
  • Visual Testing Result
  • Server-Side Logs
  • Execution Recording Video
  • Insights Data
  • Transaction Analysis

If it driver.quit(); is not called, the session may instead show only a timestamp (date and time). Additionally, any intermediate failures will be highlighted as errors in the logs.

Notes: The user can pass either the “tg:userToken” capability or can pass “tg: userName” and “tg: password” capabilities for authentication.

// 1. Set the capabilities of the driver

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("tg:udid", "your-device-udid");
capabilities.setCapability("tg:userToken", "your-user-token");
capabilities.setCapability("browserName", "chrome");

// You can use this capability to categorise your test results.
capabilities.setCapability("tg:projectName", "WebDemoqa");
WebDriver driver = new RemoteWebDriver(new URL("http://{_YOUR_Domain_}/browserrun35511/wd/hub"), capabilities);

// Java Syntax Add this at the start of your test to provide the test case name on the automation results screen.

((JavascriptExecutor) driver).executeScript("tg:logs", ImmutableMap.of("testcaseName", "SampleTestCase"));

//Add this after each step to add a screenshot for each step for visual testing.

((JavascriptExecutor) driver).executeScript("tg:logs", ImmutableMap.of("testStepName", "Step Description"));

Testcases pass or fail status can be added to the TestGrid Automation results screen by adding the following line of code:.

//Pass

((JavascriptExecutor) driver).executeScript("tg:action", "{\"status\": \"passed\", \"case\": \"Reason for the testcase!\"}");

// Fail

((JavascriptExecutor) driver).executeScript("tg:action", "{\"status\": \"failed\", \"case\": \"Reason for the testcase!\"}");

Step 5: Determine the user’s Token capabilities.

a. Go to the Dashboard and then click on the Created “Test Runs Application”. After that, click on “Test Case Writer” and then click on “Versions.” On the same screen, look for the “i” button in the upper right corner.

b.  Select the “i” button icon and obtain the user token from there.

Step 6: Execute your local Selenium code. Below is the sample for Java.

For example, Selenium uses JAVA.

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

public class ChromeGridTest {
    public static void main(String[] args) {
        String url = "https://demoqa.com/";
        try {
          //  ChromeOptions chromeOptions = new ChromeOptions();
            DesiredCapabilities chromeOptions = new DesiredCapabilities();
            chromeOptions.setCapability("browserName", "firefox");
            chromeOptions.setCapability("platformName", "linux");
            chromeOptions.setCapability("tg:userToken", "Your_User_token_here");
            capabilities.setCapability("tg:projectName", "GoodWeather");

            // Either you can use a user token or username and password for authentication
            chromeOptions.setCapability("tg:userName", "< Your_Emails_ID >");
            chromeOptions.setCapability("tg:password", "< Your_Password >");
            chromeOptions.setCapability("tg:udid", "your-device-udid");
            WebDriver driver = new RemoteWebDriver(new URL("http://{_YOUR_Domain_}.testgrid.io:34555/wd/hub"), chromeOptions);
            Thread.sleep(15000);
            driver.get(url);
            System.out.println("Redirected to "+url+" successfully. ");
            Thread.sleep(15000); // Replace driver.wait with Thread.sleep for the desired delay
            driver.quit();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
Example java code for Browser –
package org.example;

import com.google.common.collect.ImmutableMap;
import org.openqa.selenium.*;

import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.Select;

import java.net.MalformedURLException;
import java.net.URL;

public class WebAllOperator {

    public static void main(String[] args) throws InterruptedException, MalformedURLException {
        {
            WebDriver driver;
            for (int i = 0; i < 1 ; i++) {
                    DesiredCapabilities capabilities = new DesiredCapabilities();

                    // add this cap if you want to give Project name to your Automation Test Case
                    capabilities.setCapability("tg:projectName", "Web Automation Test");     

                    capabilities.setCapability("tg:udid", "your-device-udid");
                    capabilities.setCapability("tg:userToken", "put your usertoken here");
                    capabilities.setCapability("browserName", "chrome");

                    driver = new RemoteWebDriver(new URL("https:{_YOUR_Domain_}.testgrid.io:39102/wd/hub"), capabilities);

                    // Testcases pass status can be added to the TestGrid Automation results screen by adding the following line of code:
                    ((JavascriptExecutor) driver).executeScript("tg:action", "{\"status\": \"passed\", \"case\": \"Passed Case Test\"}");

                    Alloperatorcheck(driver);

                driver.quit();
                // Wait for 20 seconds before starting the next test run
                    Thread.sleep(10000);
            }
        }
    }

    static void Alloperatorcheck(WebDriver driver) {

        // If you want to see the Automation Test Case name on the automation results screen, add this line of code.

        ((JavascriptExecutor) driver).executeScript("tg:logs", ImmutableMap.of("testcaseName", "Website_Test"));

        try {
            String automationtesting = "https://demo.automationtesting.in/Register.html";
            Thread.sleep(5000);
            driver.get(automationtesting);
            System.out.println("Redirected to " + automationtesting + " successfully.");

            // To get page performance summary metric data and insights add following code in your automation code
            // Add this at the start of your test case

            ((JavascriptExecutor) driver).executeScript("tg:logs", ImmutableMap.of("pageLoadStart", "Register"));

            WebElement elementslink = driver.findElement(By.xpath("//a[normalize-space()='Register']"));

            elementslink.click();
            System.out.println("Clicked on Elements link successfully.");

            // Include this code following the test step if you wish to compare any UI modifications during visual testing.
            
            ((JavascriptExecutor) driver).executeScript("tg:logs", ImmutableMap.of("testStepName", "elementslink"));

            Thread.sleep(5000);

            WebElement AutomationDemoSite = driver.findElement(By.xpath("//h1[normalize-space()='Automation Demo Site']"));
            if(AutomationDemoSite.isDisplayed())
                ((JavascriptExecutor) driver).executeScript("tg:logs", ImmutableMap.of("testStepName", "isDisplayed"));
            {
                AutomationDemoSite.click();
                System.out.println("Clicked on TextBox link successfully.");
            }

            // Add this code after the desired screen appears on the device's screen
            ((JavascriptExecutor) driver).executeScript("tg:logs", ImmutableMap.of("pageLoadEnd", "Register"));

            AutomationDemoSite.isEnabled();
            System.out.println("Automation Demo Site is enabled.");

            Thread.sleep(5000);

            WebElement checkbox1 = driver.findElement(By.xpath("(//input[@id='checkbox1'])[1]"));
            if(checkbox1.isDisplayed())
            {
                checkbox1.click();
                System.out.println("Tap on checkbox1.");
            }

            Thread.sleep(2000);
            checkbox1.isSelected();
            System.out.println("checkbox1 is Selected");

            driver.quit();

        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}

Step 7: View live Execution on the TestGrid Device cloud.

Additionally, the remote execution of code can also be viewed live on the TestGrid Device Cloud.

Table of Contents