Using JavaScript Executor in Mobile Testing - Notes By ShariqSP

Using JavaScript Executor in Mobile Testing with Selenium and Appium

JavaScript Executor is a powerful feature in Selenium that allows executing custom JavaScript commands directly in the browser or mobile application context. In mobile testing with Appium, it is used to handle scenarios like scrolling, swiping, or interacting with elements that are not natively supported by WebDriver methods.

Code Example: Scrolling and Swiping Using JavaScript Executor

              
                package addItemWithJSExecutor;

                import java.net.MalformedURLException;
                import java.net.URL;
                import java.time.Duration;
                
                import org.openqa.selenium.JavascriptExecutor;
                import org.openqa.selenium.WebDriver;
                import org.openqa.selenium.WebElement;
                import org.openqa.selenium.remote.DesiredCapabilities;
                
                import io.appium.java_client.AppiumBy;
                import io.appium.java_client.android.AndroidDriver;
                
                public class AddItemWithJSExecutor {
                
                    public static void scrollWithJS(AndroidDriver driver) {
                        // Use JavaScript Executor to scroll
                        JavascriptExecutor js = (JavascriptExecutor) driver;
                        js.executeScript("mobile: scrollGesture", 
                            java.util.Map.of(
                                "left", 0,          // Start at the leftmost edge
                                "top", 66,          // Start just below the status bar
                               //make sure you knwo hight and width of your screen
                                "width", 1080,      // Full screen width
                                "height", 1920 - 96, // Full screen height minus the status bar
                                "direction", "down", 
                                "percent", 1     // Scroll 100% of the full screen height
                            )
                        );
                
                    }
                
                
                    public static void swipeWithJS(AndroidDriver driver) {
                        // Use JavaScript Executor to swipe
                        JavascriptExecutor js = (JavascriptExecutor) driver;
                        js.executeScript("mobile: swipeGesture", 
                                java.util.Map.of(
                                    "left", 500,  // X-coordinate to start the swipe
                                    "top", 1000,  // Y-coordinate to start the swipe
                                    "width", 500, // Width of the swipe area
                                    "height", 600, // Height of the swipe area
                                    "direction", "up", 
                                    "percent", 0.75 // Reduced swipe distance (50% of the swipe area)
                                )
                            );
                
                
                    }
                
                    public static void main(String[] args) throws MalformedURLException, InterruptedException {
                        // Set Desired Capabilities
                        DesiredCapabilities caps = new DesiredCapabilities();
                        caps.setCapability("platformName", "Android");
                        caps.setCapability("appium:platformVersion", "7.1.1");
                        caps.setCapability("appium:deviceName", "Mi Max 2");
                        caps.setCapability("appium:appPackage", "com.swaglabsmobileapp");
                        caps.setCapability("appium:appActivity", ".MainActivity");
                        caps.setCapability("appium:automationName", "UiAutomator2");
                
                        // Initialize Android Driver
                        AndroidDriver driver = new AndroidDriver(new URL("http://127.0.0.1:4723"), caps);
                        driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3000));
                        
                        // Login script
                        driver.findElement(AppiumBy.accessibilityId("test-Username")).sendKeys("standard_user");
                        driver.findElement(AppiumBy.accessibilityId("test-Password")).sendKeys("secret_sauce");
                        driver.findElement(AppiumBy.accessibilityId("test-LOGIN")).click();
                        
                        //add item to cart
                        driver.findElement(AppiumBy.xpath("(//android.widget.TextView[@text=\"ADD TO CART\"])[1]")).click();
                
                        //open cart
                        driver.findElement(AppiumBy.xpath("//android.view.ViewGroup[@content-desc=\"test-Cart\"]/android.view.ViewGroup/android.view.ViewGroup")).click();
                
                        //click on checkout
                        driver.findElement(AppiumBy.xpath("//android.widget.TextView[@text=\"CHECKOUT\"]")).click();
                
                        //enter first name as shariq
                        driver.findElement(AppiumBy.xpath("//android.widget.EditText[@content-desc=\"test-First Name\"]")).sendKeys("Shariq");
                
                        //enter Last name as sp
                        driver.findElement(AppiumBy.xpath("//android.widget.EditText[@content-desc=\"test-Last Name\"]")).sendKeys("SP");
                
                        //enter zip code as 560001
                        driver.findElement(AppiumBy.accessibilityId("test-Zip/Postal Code")).sendKeys("560001");
                
                        //click on continue  
                        driver.findElement(AppiumBy.xpath("//android.widget.TextView[@text='CONTINUE']")).click();
                
                
                        Thread.sleep(1000);
                        // Perform a Scroll gesture using JavaScript Executor
                        scrollWithJS(driver);
                
                         //click on Finish
                           WebElement finish = driver.findElement(AppiumBy.xpath("//android.widget.TextView[@text='FINISH']"));
                           finish.click();
                
                        // Close the session
                        driver.terminateApp("com.swaglabsmobileapp");
                    }
                }
                
              
                

Explanation

  • JavaScript Executor Setup: The `JavascriptExecutor` interface is implemented via the `driver` object. It allows executing commands like scrolling or swiping.
  • Scroll Implementation: The `mobile: scroll` script scrolls the view by a specified percentage in the desired direction.
  • Swipe Implementation: The `mobile: swipeGesture` script performs a swipe by specifying start coordinates, direction, and swipe percentage.
  • Integrating with Appium: These scripts are executed within an Appium session, enhancing the interaction capabilities for elements not readily accessible via WebDriver methods.

Key Benefits

JavaScript Executor enables handling scenarios that involve dynamic interactions like scrolling and swiping, making it indispensable for robust mobile app testing.