DEV Community

Cover image for How to perform Mouse Actions in Selenium WebDriver
himanshuseth004 for LambdaTest

Posted on • Edited on • Originally published at lambdatest.com

How to perform Mouse Actions in Selenium WebDriver

A web product (or website) comprises multiple web elements like buttons, text boxes, checkboxes, menus, sliders, and more. During the process of Selenium automation testing of the website, you can realise specific scenarios by automating low-level interactions such as keypresses and mouse button actions (e.g. click, double click, right-click, etc.) with the WebElement(s) in the DOM. These interactions, also called Actions, play an integral part in testing an application using the Selenium framework.

Source-mouseclickgifs

Implementing Selenium tests that involve automating actions like accessing drop-down boxes or clicking or double-clicking on a button element or right-clicking on an item to get the corresponding context menu requires good know-how of the Action Class in Selenium. At a broad level, the action class comprises Keyboard actions and Mouse actions, but our focus would be on Mouse actions in Selenium WebDriver.

By the end of this blog, your acquaintance with the Actions class would help perform mouse actions in Selenium WebDriver.

Check out what WebDriver is, its features, how it works, best practices, and more in this WebDriver tutorial.

Introduction to Action Class in Selenium

Actions are mainly triggered using two peripherals — Keyboard and Mouse. How do you use Selenium test automation to trigger the requisite actions automatically? The answer lies with ‘Actions Class’.

Test your native, hybrid, and web apps across all legacy and latest mobile operating systems on the most powerful Android online emulator.

What is Action Class in Selenium

The Actions Class in Selenium contains a collection of actions for performing the corresponding actions (e.g. click, double click, drag & drop, etc.) on the WebElements present on the page.

In terms of categorization, Keyboard Actions and Mouse Actions are the two broad categories of actions. Action APIs provides a low-level interface that provides virtualized device input to the web browser.

In Java, the org.openqa.selenium.interactions.Actions class provides the required user-facing APIs for emulating complex user gestures. The set of APIs can also be used for building a Composite Action that contains actions specified by the method calls.

Here is a sample Composite Action that comprises of a chain (or series) of Keyboard and Mouse Actions in Selenium WebDriver:

  • Move to a WebElement (e.g. text box)

  • Enter text in the text box using the SendKeys() method

  • Double-click on the entered text

  • Selecting the right option in the Context Menu to perform the operation (e.g. cut, copy, etc.).

In the subsequent sections, we explore the methods provided by the Actions Class and deep-diving into how to perform mouse actions in Selenium WebDriver using the methods in Actions Class.

Watch this video to learn what the Actions Class is in Selenium and how to use it.

Are you using Playwright for automation testing? Run your Playwright test scripts instantly on 50+ browser/OS combinations using the LambdaTest cloud

What is Action in Selenium

Action in Selenium is an interface that provides two methods — build() and perform(). The commands of the Action Interface are implemented by the Action class.

build() method

The build() method generates a composite action containing all the actions in the chain. These actions are ready to be performed. This method does resetting of the internal builder state so that the subsequent calls to the build() method only contain fresh sequences.

The build() method returns a composite action. In scenarios where the action chain contains only one action, you can avoid the build() method and directly call the perform() method.

Syntax

import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
web_driver = new ChromeDriver();
/* create an object for the Actions class and pass the driver argument */
Actions action = new Actions(web_driver);

Action act = action.build();
Enter fullscreen mode Exit fullscreen mode

perform() method

Without calling the build() method, you could call the perform() method for performing the sequence of actions.

Syntax

import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

web_driver = new ChromeDriver();

/* create an object for the Actions class and pass the driver argument */
Actions action = new Actions(web_driver);

action.perform();
Enter fullscreen mode Exit fullscreen mode

Mouse Actions in Selenium WebDriver

Mouse actions in Selenium WebDriver provide a mechanism for automating low-level elementary interactions such as mouse clicks, mouse hover, mouse button actions; as well as complex low-level interactions such as mouse hover, drag & drop, click & hold, and more.

Here is a brief list of mouse actions that are provided by the Action Class in Selenium:

  • click() method

*click() *— Clicks on the current mouse position

click​(WebElement web_element) — Clicks in the middle of the given WebElement which is passed to the method

  • doubleClick() method

*doubleClick() *— Double clicks on the current mouse position

*doubleClick(WebElement web_element) *— Double clicks in the middle of the given WebElement which is passed to the method

  • clickAndHold() method

*clickAndHold() *— Clicks without releasing on the current mouse position

clickAndHold(WebElement web_element) — Clicks without releasing in the middle of the WebElement which is passed to the method

  • contextClick() method

contextClick() — Performs a context click operation on the current mouse position

contextClick(WebElement web_element) — Performs a context click operation at the middle of the WebElement which is passed to the method

  • dragAndDrop() method

*dragAndDrop​(WebElement source_elem, WebElement target_elem) *— Perform a click and hold operation in the middle of the source element (i.e. source_elem), moves to the location of the target element (i.e. target_elem), and release the mouse. On the successful execution of this method, the source element is dragged and dropped at the place where the target element is located

*dragAndDropBy​(WebElement elem_source, int x_Offset, int y_Offset) *— Perform a click and hold operation in the middle of the source element (i.e. source_elem) and move by a given offset available as x_Offset and y_Offset

  • moveToElement() method

*moveToElement​(WebElement elem_target) *— Move the mouse to the middle of the element (i.e. elem_target) which is passed to the method

*moveToElement​(WebElement target, int x_Offset, int y_Offset) *— Move to an offset (x_Offset and y_Offset) from the WebElement’s in center viewpoint

  • moveByOffset() method

moveByOffset​(int x_Offset, int y_Offset) — Move the mouse from the current position by the offset which is passed to the method

  • release() method

release() — Release the depressed left mouse button which is pressed at the current mouse position
release(WebElement elem_target) — Release the depressed left mouse button which is pressed in the middle of the given WebElement (i.e. elem_target)
click(), doubleClick(), contextClick(), moveToElement(), and release() are overloaded methods in the Action Class and the actions performed depends on the parameters passed to the methods.

A comprehensive end to end Testing tutorial that covers what E2E Testing is, its importance, benefits, and how to perform it with real-time examples.

How to perform Mouse Actions in Selenium WebDriver

Now that we have covered the methods in the Actions Class used to perform mouse-related actions, let us look at how to implement the Actions Class in the Selenium Automation scripts. Here are the steps to use the Actions Class for automating mouse operations (or Actions):

  1. Import the package org.openqa.selenium.interactions.Actions

  2. In order to use the methods for performing mouse actions, create an object of the Actions class and pass the object to the Selenium WebDriver instance.

 ChromeDriver web_driver = null;

web_driver = new ChromeDriver();

/* create an object for the Actions class and pass the driver argument */
Actions action = new Actions(web_driver);
Enter fullscreen mode Exit fullscreen mode
  1. Once the object of Actions Class is created, use the object to access the methods for automating mouse-related operations in the Selenium script.

We now look at using the methods of Action Class in Selenium for realizing specific test scenarios that would help in your Selenium testing activity. We would be using the TestNG framework and Selenium 4 Java (4.0.0-alpha-7). You can refer to our earlier blog on Getting started with the TestNG framework for a quick refresher of the framework.

Though Selenium 4 has a rich set of Action APIs that let you perform additional actions like zoom-in/zoom-out, pinch & zoom, and more, these enhancements are not applicable for Mouse Actions in Selenium. Hence, the implementation used for demonstrating how to perform Mouse Actions in Selenium WebDriver will work with Selenium Java 3.141.59.

Shown below is pom.xml used for downloading the requisite packages from the Maven Repository:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.actionchains</groupId>
    <artifactId>ActionChainsSelenium</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.9.10</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-nop</artifactId>
            <version>1.7.28</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>4.0.0-alpha-7</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-remote-driver</artifactId>
            <version>4.0.0-alpha-7</version>
        </dependency>
        <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-chrome-driver</artifactId>
            <version>4.0.0-alpha-7</version>
        </dependency>
    </dependencies>

    <build>
        <defaultGoal>install</defaultGoal>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
Enter fullscreen mode Exit fullscreen mode

The respective tests are executed on LambdaTest Online Selenium Grid. Access related details (i.e. user-name and access-key) which are used for executing the test on the LambdaTest Grid are available in the profile section. Shown below is the overall project structure from IntelliJ IDE that is used for demonstrating mouse actions in Selenium WebDriver:

Here is the implementation of the methods under the @ BeforeTest and @ AfterTest annotations. The methods used for demonstrating Mouse Actions in Selenium should be included under the @ Test annotation.

package ActionChainsSel; 
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.Duration;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import static org.testng.AssertJUnit.assertEquals;

public class TestActionChains
{
    public WebDriver web_driver;
    public static String username = "user-name";
    public static String access_key = "access-key";

    @BeforeTest
    public void testSetUp() throws MalformedURLException
    {
        DesiredCapabilities capabilities = new DesiredCapabilities();

        capabilities.setCapability("build", "How to perform mouse actions in Selenium WebDriver");
        capabilities.setCapability("name", "How to perform mouse actions in Selenium WebDriver");
        capabilities.setCapability("platform", "Windows 10");
        capabilities.setCapability("browserName", "Chrome");
        capabilities.setCapability("version","latest");

        web_driver = new RemoteWebDriver(new URL("http://" + username + ":" + access_key + "@hub.lambdatest.com/wd/hub"), capabilities);
    }

/* Methods demonstrating Mouse Actions Class should be added here under the @Test annotation */

    @AfterTest
    public void tearDown()
    {
        if (web_driver != null)
        {
            web_driver.quit();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Run your Playwright test scripts instantly on 50+ browser and OS combinations using the LambdaTest cloud.

How to perform Mouse Click action in Selenium WebDriver

Mouse click (single click) is one of the basic mouse actions in Selenium WebDriver that you would be required to perform during the Selenium test automation process. Mouse clicks are primarily used to perform click actions on buttons, checkboxes, radio buttons, etc. When we refer to a mouse click, it is always the ‘left click’ since right-click opens up the Context Menu.

Test Scenario

  1. Go to www.amazon.in

  2. Locate the search box

  3. Search for iPhone

  4. Perform a click of the Search Button on the page for executing the search operation

  5. Assert if the page title does not match

Implementation

@Test(description="Demo of Action Chain Click", enabled = true)
    public void test_click() throws InterruptedException
    {
        web_driver.navigate().to("https://www.amazon.in/");
        web_driver.manage().window().maximize();

        try
        {
            /* create an object for the Actions class and pass the driver argument */
            Actions action = new Actions(web_driver);

            /* specify the locator of the search box in which the product has to be typed */
            WebElement elementToType = web_driver.findElement(By.cssSelector("#twotabsearchtextbox"));

            /* pass the value of the product */
            action.sendKeys(elementToType, "iphone").build().perform();

            /* specify the locator of the search button */
            WebElement elementToClick = web_driver.findElement(By.xpath("//input[@value='Go']"));

            Thread.sleep(5000);

            /* perform a mouse click on the search button */
            action.click(elementToClick).build().perform();

            Thread.sleep(5000);

            /* verify the title of the website after searching the product */
            Assert.assertEquals(web_driver.getTitle(), "Amazon.in : iphone");
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
Enter fullscreen mode Exit fullscreen mode

Execution

Once the search string is entered, the Mouse Click is performed on the search button. The perform() action of action class in Selenium performs the required mouse action.

/* specify the locator of the search button */
WebElement elementToClick = web_driver.findElement(By.xpath("//input[@value='Go']"));
/* perform a mouse click on the search button */
action.click(elementToClick).build().perform();
Enter fullscreen mode Exit fullscreen mode

Shown below is the execution snapshot which indicates that requisite action was completed successfully:

A comprehensive end to end Testing tutorial that covers what E2E Testing is, its importance, benefits, and how to perform it with real-time examples

How to perform Double Click action in Selenium WebDriver

Double click mouse action in Selenium WebDriver is one of the prime actions used for Selenium test automation. To demonstrate the usage of double click action in Selenium, we navigate to https://unixpapa.com/js/testmouse.html and double-click on the link “click here to test”.

Test Scenario

  1. Go to https://unixpapa.com/js/testmouse.html

  2. Double click on “click here to test”

  3. Search for “dblclick” in the text area

  4. Assert if the Double click operation is not successful

Implementation

@Test(description="Demo of Double Click", enabled = true)
    public void test_double_click() throws InterruptedException
    {
        String str_dblclick = "dblclick";

        web_driver.navigate().to("https://unixpapa.com/js/testmouse.html");
        web_driver.manage().window().maximize();
        Thread.sleep(3000);

        try
        {
            /* create an object for the Actions class and pass the driver argument */
            Actions action = new Actions(web_driver);

            WebElement elem_clear = web_driver.findElement(By.xpath("//a[.='click here to clear']"));
            Thread.sleep(2000);
            elem_clear.click();

            WebElement elem_test_btn = web_driver.findElement(By.xpath("//a[.='click here to test']"));
            Thread.sleep(2000);
            action.doubleClick(elem_test_btn).build().perform();

            /* Verify whether the double click operation was successful or not */
            WebElement text_area = web_driver.findElement(By.cssSelector("textarea"));
            String textattr = text_area.getAttribute("value");
            System.out.println(textattr);

            String bodyText = web_driver.findElement(By.tagName("textarea")).getText();
            Assert.assertFalse(bodyText.contains(str_dblclick), "Text found!");
           System.out.println("Double Click test case successful\n");
           Thread.sleep(3000);
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
Enter fullscreen mode Exit fullscreen mode

In this System testing tutorial, learn why System testing is important and all the intricacies of the System testing process.
Code Walkthrough

1. The text area which gives an indication of the mouse operation is cleared. The WebElement is located using the XPath selector and click() action on the WebElement clears the textarea.


WebElement elem_clear = web_driver.findElement(By.xpath("//a[.='click here to clear']"));
elem_clear.click();
Enter fullscreen mode Exit fullscreen mode

2. The WebElement “click here to test” is located using the XPath.

WebElement elem_test_btn = web_driver.findElement(By.xpath("//a[.='click here to test']"));
Enter fullscreen mode Exit fullscreen mode

3. Create an object of the Actions Class. The doubleClick() method of the Actions Class in Selenium is used for performing double click action on the WebElement searched in step(2). The build() method of mouse actions in Selenium WebDriver builds the chain of actions and perform() method performs the required action.

Actions action = new Actions(web_driver);
action.doubleClick(elem_test_btn).build().perform();
Enter fullscreen mode Exit fullscreen mode

4. Now that the double click action is performed, we first locate WebElement using TagName in Selenium. Next, we read the contents in the WebElement with tagname “textarea” through the usage of the getText() method.


String bodyText = web_driver.findElement(By.tagName("textarea")).getText();
Enter fullscreen mode Exit fullscreen mode

5. Mark the test as ‘failed’ if the textarea does not contain the string

Assert.assertFalse(bodyText.contains(str_dblclick), "Text found!");
Enter fullscreen mode Exit fullscreen mode

Execution

Shown below is the execution snapshot of the test that demonstrated mouse actions in Selenium WebDriver. It is captured from the Automation Dashboard of LambdaTest:

As shown from the IntelliJ IDE snapshot, double click (dblclick) operation was performed successfully.

In this Appium automation tutorial, learn about Appium and its benefits for mobile automation testing. Take a look at how Appium works and see how to perform Appium testing of your mobile applications

How to perform Context Click action in Selenium WebDriver

Context Menu (or browser context menu) is the menu that is available when the user does a right-click operation on a web page (or web element). The items in the context menu depend on the WebElement on which right-click is performed.

Here is an example of a context menu when we right-clicked on an empty area of the web page:

Here is another example of a context menu where custom menu items come up when the WebElement (right click me) on the page is clicked.

Test Scenario

  1. Go to http://medialize.github.io/jQuery-contextMenu/demo.html

  2. Locate the element “right click me”

  3. Right click on the element located in Step(2)

  4. Select the item “paste” in the Context Menu

  5. Assert if the required item in the Context Menu is not clicked

In this Ad hoc testing tutorial, let’s deep dive into what Ad hoc testing is, its advantages, disadvantages, types, characteristics, and their best practices.

Implementation

@Test(description="Demo of Context Click", priority = 3, enabled = true)
    public void test_context_click() throws InterruptedException
    {
        web_driver.navigate().to("http://medialize.github.io/jQuery-contextMenu/demo.html");
        web_driver.manage().window().maximize();

        try
        {
            /* create an object for the Actions class and pass the driver argument */
            Actions action = new Actions(web_driver);

            By locator = By.xpath("/html/body/div/section/div/div/div/p/span");

            WebDriverWait wait = new WebDriverWait(web_driver, Duration.ofSeconds(5));
            wait.until(ExpectedConditions.presenceOfElementLocated(locator));
            WebElement element = web_driver.findElement(locator);
            action.contextClick(element).build().perform();

            WebElement element_edit = web_driver.findElement(By.xpath
                    ("/html/body/ul/li[4]/span"));

            Thread.sleep(5000);
            element_edit.click();

            Alert alert = web_driver.switchTo().alert();
            String textEdit = alert.getText();
            System.out.println(textEdit);
            Assert.assertEquals(textEdit, "clicked: paste", "Context Click successful");
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }    
Enter fullscreen mode Exit fullscreen mode

Code Walkthrough

1. Navigate to the test page http://medialize.github.io/jQuery-contextMenu/demo.html

web_driver.navigate().to("http://medialize.github.io/jQuery-contextMenu/demo.html");
Enter fullscreen mode Exit fullscreen mode

2.An object of the class By is created to locate the button “right click me” with its XPath.

By locator = By.xpath("/html/body/div/section/div/div/div/p/span");
Enter fullscreen mode Exit fullscreen mode

3.The method ExpectedConditions.presenceOfElementLocated is used to see if the WebElement — “right click me” button is present on the DOM of the page. It is only checked for its presence and not its visibility. Visibility means that the element is not only displayed but its height & width properties are greater than zero. You can use the appropriate Selenium locators to locate the WebElement on the page.

WebDriverWait wait = new WebDriverWait(web_driver, Duration.ofSeconds(5));
wait.until(ExpectedConditions.presenceOfElementLocated(locator));
Enter fullscreen mode Exit fullscreen mode

4.As the “right click me” button is present in the DOM, the find_element() method is used for locating the element. Once the element is located, contextClick method of the Action Class in Selenium is performed on the WebElement. This is when the context menu with items Edit, Cut, Copy, etc. appears on the page.

WebElement element = web_driver.findElement(locator);
action.contextClick(element).build().perform();
Enter fullscreen mode Exit fullscreen mode

5.As per the test scenario, we have to click the item “paste” in the context menu. The find_element method of Selenium WebDriver is used for locating the item “paste” through the XPath of the WebElement. The click() method offered by Selenium WebDriver (not Action Chains class in Selenium) is used for clicking the menu item.

WebElement element_edit = web_driver.findElement(By.xpath
                    ("/html/body/ul/li[4]/span"));
element_edit.click();
Enter fullscreen mode Exit fullscreen mode

6.Once the “paste” item in the Context Menu is clicked, an alert window is shown. The switchTo() method of Selenium WebDriver is used for switching to the alert window. The getText() method of the Alert class gets the text in the alert window.

Alert alert = web_driver.switchTo().alert();
String textEdit = alert.getText();
System.out.println(textEdit);
Enter fullscreen mode Exit fullscreen mode

7.Assert (equals) if the text in the alert window contains “clicked paste”.

Assert.assertEquals(textEdit, "clicked: paste", "Context Click successful");
Enter fullscreen mode Exit fullscreen mode

Execution

As seen in the execution snapshot, the content in the alert window is “clicked: paste”.

As seen in the execution snapshot from the automation dashboard in LambdaTest, context click operation of mouse actions in Selenium WebDriver was successfully performed on the Web Element “right click me” button.

In this Data driven testing tutorial, let us deep dive into what data driven testing is, its pros & cons, its types, data driven testing in an agile environment, benefits, and their best practices.

How to automate Slider movement using moveByOffset in Selenium WebDriver

For automating test scenarios where a WebElement like Slider is involved, you have to use moveByOffset with the X & Y coordinates by which you want the slider to move. The moveByOffset method can also be used for clicking anywhere on the page where the offset is in the form of X & Y coordinates pair.

For moving the Slider horizontally in Selenium Java, we have to perform the following set of mouse actions in Selenium WebDriver:

  1. Click & Hold (clickAndHold) the slider element

  2. Move the slider element by the specified offset using the moveByOffset method

  3. Release the mouse at the resultant X and Y position

  4. Perform the set of actions

Test Scenario

  1. Go to https://jqueryui.com/slider/

  2. Locate the Slider element

  3. Move the slider by an offset of (40,0)

Implementation

@Test(description="Demo of MoveByOffset (ClickAndHold)", priority = 4, enabled = true)
    public void test_clickhold_move_by_offset() throws InterruptedException
    {
        web_driver.navigate().to("https://jqueryui.com/slider/");
        web_driver.manage().window().maximize();
        Thread.sleep(3000);

        try
        {
            /* create an object for the Actions class and pass the driver argument */
            Actions action = new Actions(web_driver);
            web_driver.switchTo().frame(0);
            WebElement elem_slider = web_driver.findElement(By.cssSelector(".ui-slider-handle"));
            Thread.sleep(2000);
            action.clickAndHold(elem_slider).moveByOffset(40,0).release().perform();

            System.out.println("Drag & Drop test case successful\n");
            Thread.sleep(3000);
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
Enter fullscreen mode Exit fullscreen mode

Code Walkthrough

1. Create an object of the Actions class in Selenium and pass the Selenium WebDriver instance to the same.

Actions action = new Actions(web_driver);
Enter fullscreen mode Exit fullscreen mode

2.Switch to the frame with ID 0

web_driver.switchTo().frame(0);
Enter fullscreen mode Exit fullscreen mode

3.Locate the Slider element on the page. We use the CSS Selector web locator to locate the element for performing Selenium test automation

WebElement elem_slider = web_driver.findElement(By.cssSelector(".ui-slider-handle"));
Enter fullscreen mode Exit fullscreen mode

4.The sequence of actions — clickAndHold(elem_slider) 🡪 moveByOffset(40,0) 🡪 release() is performed. With this, the slider moves by an offset (40,0) with respect to the previous slider position.

action.clickAndHold(elem_slider).moveByOffset(40,0).release().perform();
Enter fullscreen mode Exit fullscreen mode

Execution

Shown below is the position of the Slider element before the test is executed:

Here is snapshot which indicates that the Slider element has moved by an offset of (40, 0). It is just before the release operation is performed due to which the slider element is still in focus.

Here, the slider is moved by the supplied offset and the element is released using the release() method.

In this Data driven testing tutorial, let us deep dive into what data driven testing is, its pros & cons, its types, data driven testing in an agile environment, benefits, and their best practices.

How to perform Drag & Drag operation in Selenium WebDriver

There are scenarios in Selenium web automation where you would need to drag a WebElement and drop it at the target location. Here the location where you need to drop the element is prominent in the UI so that the user has complete visibility about where the source element has to be dropped.

There are three distinct ways in which you can carry out a ‘Drag and Drop’ operation using the Actions Class in Selenium:

  1. Using the dragAndDrop(WebElement elem_source, WebElement elem_target) method of action class in Selenium to drag the ‘elem_source’ element and drop at the ‘elem_target’ location.

  2. Using the series of actions [clickAndHold(WebElement elem_source) 🡪 moveToElement(WebElement elem_target) 🡪 release()] of action class in Selenium for manually dragging and dropping the source element to the target location.

  3. Using the dragAndDropBy(WebElement elem_source, int x_Offset, int y_Offset) method of action class in Selenium for dragging and dropping the source element by a specified X & Y offset. This is not a preferred approach, as the details of the target element are not taken into account

Let’s look at each of these approaches that demonstrate mouse actions in Selenium WebDriver in more detail for the following test scenario:

Test Scenario

  1. Go to https://jqueryui.com/droppable/

  2. Locate the element with ID ‘draggable’

  3. Locate the element with ID ‘dropabble’

  4. Use the appropriate method to drag the source element at the target location (with ID droppable)

Implementation — 1 (using dragAndDrop method)

@Test(description="Demo of Drag and Drop", priority = 5, enabled = true)
    public void test_drag_drop() throws InterruptedException
    {
        web_driver.navigate().to("https://jqueryui.com/droppable/");
        web_driver.manage().window().maximize();
        Thread.sleep(3000);

        try
        {
           Actions action = new Actions(web_driver);
        web_driver.switchTo().frame(0);

            WebElement elem_source = web_driver.findElement(By.id("draggable"));
            ((JavascriptExecutor)web_driver).executeScript("arguments[0].scrollIntoView();",elem_source);
            Thread.sleep(2000);

            WebElement elem_destination = web_driver.findElement(By.id("droppable"));
            Thread.sleep(2000);

            action.dragAndDrop(elem_source, elem_destination).build().perform();

            System.out.println("Drag & Drop test case successful\n");
            Thread.sleep(3000);
            Assert.assertEquals("Dropped!", elem_destination.getText());
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
Enter fullscreen mode Exit fullscreen mode

Implementation — 2 (using clickAndHold and moveToElement methods)

@Test(description="Demo of Drag and Drop", priority = 5, enabled = true)
    public void test_drag_drop() throws InterruptedException
    {
        web_driver.navigate().to("https://jqueryui.com/droppable/");
        web_driver.manage().window().maximize();
        Thread.sleep(3000);

        try
        {
           Actions action = new Actions(web_driver);
           web_driver.switchTo().frame(0);
            WebElement elem_source = web_driver.findElement(By.id("draggable"));
            ((JavascriptExecutor)web_driver).executeScript("arguments[0].scrollIntoView();",elem_source);
            Thread.sleep(2000);

            WebElement elem_destination = web_driver.findElement(By.id("droppable"));
            Thread.sleep(2000);

            action.clickAndHold(elem_source).moveToElement(elem_destination,100, 100).release().perform();
            System.out.println("Drag & Drop test case successful\n");
            Thread.sleep(3000);
            Assert.assertEquals("Dropped!", elem_destination.getText());
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
Enter fullscreen mode Exit fullscreen mode

Implementation — 3 (using dragAndDropBy method method)

@Test(description="Demo of Drag and Drop", priority = 5, enabled = true)
    public void test_drag_drop() throws InterruptedException
    {
        web_driver.navigate().to("https://jqueryui.com/droppable/");
        web_driver.manage().window().maximize();
        Thread.sleep(3000);

        try
        {
           Actions action = new Actions(web_driver);
           web_driver.switchTo().frame(0);
            WebElement elem_source = web_driver.findElement(By.id("draggable"));
            ((JavascriptExecutor)web_driver).executeScript("arguments[0].scrollIntoView();",elem_source);
            Thread.sleep(2000);

            WebElement elem_destination = web_driver.findElement(By.id("droppable"));
            Thread.sleep(2000);

            action.dragAndDropBy(elem_source, 160, 10).build().perform();

            System.out.println("Drag & Drop test case successful\n");
            Thread.sleep(3000);
            Assert.assertEquals("Dropped!", elem_destination.getText());
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
Enter fullscreen mode Exit fullscreen mode

As a major part of the WebDriver implementation is unchanged across different approaches, we do a code walkthrough for all the approaches in one go!

Code Walkthrough

1.Create an object of the Actions class in Selenium and the Selenium WebDriver instance is passed as an argument to the Actions method.

Actions action = new Actions(web_driver);
Enter fullscreen mode Exit fullscreen mode

2.This is the most important step where we switch to frame(0) as the WebElements — draggable and droppable are located in that iFrame.



web_driver.switchTo().frame(0);
Enter fullscreen mode Exit fullscreen mode

3.Locate the WebElement ‘draggable’ using the ID web locator.

WebElement elem_source = web_driver.findElement(By.id("draggable"));
Enter fullscreen mode Exit fullscreen mode

4.Scroll into the view using the JavaScript executor. The method scrollIntoView() in JavaScript scrolls the page until the ‘draggable’ element is in full view.


WebElement elem_source = web_driver.findElement(By.id("draggable"));
((JavascriptExecutor)web_driver).executeScript("arguments[0].scrollIntoView();",elem_source);
Enter fullscreen mode Exit fullscreen mode

5.Locate the WebElement ‘droppable’ using the ID web locator.



WebElement elem_destination = web_driver.findElement(By.id("droppable"));
Enter fullscreen mode Exit fullscreen mode

6.Now that the required web elements are located, we use the corresponding approach to perform the ‘drag and drop’ operation.

6.1)Approach — 1 (using dragAndDrop method)

The dragAndDrop method takes the input arguments — Source (elem_source) and Destination (elem_destination) elements. The perform() method of action class in Selenium is used for performing the dragAndDrop action.

action.dragAndDrop(elem_source, elem_destination).build().perform();
Enter fullscreen mode Exit fullscreen mode

6.2)Approach — 2 (using clickAndHold and moveToElement methods)

The source element (elem_source) is held using the clickAndHold method. The next action in the chain is moving to the destination location which is done by using the moveToElement method on the destination element (elem_destination) with offset set to (100,100). The offset needs to be correct else the source element will be dropped at the incorrect location (in terms of coordinates).

At the right offset (w.r.t the destination element), release the mouse using the release() action. Finally, perform the actions in the chain by triggering the perform() method offered by mouse actions in Selenium WebDriver

action.clickAndHold(elem_source).moveToElement(elem_destination,100, 100).release().perform();
Enter fullscreen mode Exit fullscreen mode

6.3) Approach — 3 (using dragAndDropBy method)

The dragAndDropBy method in mouse actions in Selenium WebDriver performs a click-and-hold operation at the ‘elem_source’ location, moves by the offset (160,10), and releases the mouse.

action.dragAndDropBy(elem_source, 160, 10).build().perform();
Enter fullscreen mode Exit fullscreen mode

7. Mark the test as ‘passed’ if the text in the destination element is ‘Dropped’.

Assert.assertEquals("Dropped!", elem_destination.getText());
Enter fullscreen mode Exit fullscreen mode

Execution

Here is the execution snapshot that shows the series of mouse actions in Selenium WebDriver that were performed in the ‘drag and drop’ operation in Selenium:

Scroll to the view where draggable element is located

Draggable element is dragged at the location where droppable is present

Mouse is released as the draggable element is dropped at the location where droppable is present

Run your Puppeteer testing scripts instantly on 50+ browser and OS combinations using the LambdaTest cloud.

Bonus Tip — Click a link in ‘Hover Menu’ in Selenium WebDriver

In case you want to use the potential offered by mouse actions in Selenium WebDriver to automate clicking on a link that is in a Hover menu, this ‘Bonus Section’ might be of super-help to you! Here are the steps to automate clicking on a link that is inside the Hover Menu:

  1. Use the moveToElement() action of mouse actions in Selenium WebDriver for moving the the control (or pointer) to the WebElement that contains the link in the Hover Menu.

  2. Trigger the perform() action of mouse actions in Selenium WebDriver for running the action prepared in step(a).

  3. With this, the Hover menu should be visible. Use the findElement method to locate the Hover Menu.

  4. Use moveToElement() action to move the mouse to the WebElement that contains the body of the Hover Menu [i.e. element identified in step(c)].

  5. Locate the required link in the Hover Menu using a suitable Web Locator (e.g. linkText).

  6. Wait for a certain duration (a couple of seconds) with ExpectedConditions set to presenceOfElementLocated. Perform a click() operation on the link identified using linkText [obtained from step (e)]. This additional delay is used to ensure that the desired WebElement is present in the DOM before performing Selenium test automation on it.

  7. Get the Window Handle of the parent window. Using the getWindowHandles() method, obtain the window handles of the windows that are currently open.

  8. Using the switchTo() method, switch to the window which is opened due to the click operation on the link in the Hover Menu.

Test Scenario

  1. Go to https://www.lambdatest.com/pricing

  2. Find the element ‘What are parallel tests?’

  3. Move to the element obtained in step(2)

  4. Click on the link inside the Hover Menu

  5. Switch to the window opened due to click on link inside the Hover Menu

  6. Assert if the page title of the new window does not match with the expected page title (i.e. Concurrency Calculator For LambdaTest Selenium Automation Gird).

Implementation

@Test(description="Demo of Mouse Hover", priority = 6, enabled = true)
    public void test_mouse_hover() throws InterruptedException {
        web_driver.navigate().to("https://www.lambdatest.com/pricing");
        web_driver.manage().window().maximize();
        Thread.sleep(3000);

        try {
            /* create an object for the Actions class and pass the driver argument */
            Actions action = new Actions(web_driver);

            WebElement elem_accept_btn = web_driver.findElement(By.cssSelector("a.cbtn:nth-child(1)"));
            Thread.sleep(2000);
            elem_accept_btn.click();

            ((JavascriptExecutor)web_driver).executeScript("window.scrollBy(0,300)", "");
            WebElement elem_parallel = web_driver.findElement(By.xpath("//div[@class='col-sm-3 pricingcol ng-scope mostpopularpricecol']//p[.='What are parallel tests?']"));
            Thread.sleep(2000);
            action.moveToElement(elem_parallel).build().perform();

            WebElement elem_hover_body = web_driver.findElement(By.xpath("//div[@class='popover-body']"));
            Thread.sleep(2000);
            action.moveToElement(elem_hover_body).build().perform();

            /* Click on the Link */
            By locator = By.linkText("Calculate how many you need");

            /* Selenium Java 3.141.59 */
            /* WebDriverWait wait = new WebDriverWait(web_driver, 5); */
            WebDriverWait wait = new WebDriverWait(web_driver, Duration.ofSeconds(5));
            wait.until(ExpectedConditions.presenceOfElementLocated(locator)).click();

            String parentWindowHandle = web_driver.getWindowHandle();

            /* Check if the link is clicked by comparing the window title */
            Set<String> allWindowHandles = web_driver.getWindowHandles();
            Iterator<String> iterator = allWindowHandles.iterator();

            while(iterator.hasNext())
            {
                String chld_window = iterator.next();
                if (!parentWindowHandle.equalsIgnoreCase(chld_window))
                {
                    web_driver.switchTo().window(chld_window);
                    System.out.println("Switched to the child window");
                }
            }

            System.out.println("Current Window title is: " + web_driver.getTitle());
            Assert.assertEquals(web_driver.getTitle(), "Concurrency Calculator For LambdaTest Selenium Automation Gird");
            System.out.println("Mouse Hover test case successful\n");
            Thread.sleep(3000);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
Enter fullscreen mode Exit fullscreen mode

Code Walkthrough

1.Navigate to the test URL https://www.lambdatest.com/pricing

web_driver.navigate().to("https://www.lambdatest.com/pricing");
web_driver.manage().window().maximize();
Enter fullscreen mode Exit fullscreen mode

2.Create an object of the Actions Class in Selenium and pass the WebDriver instance to the object.


Actions action = new Actions(web_driver);
Enter fullscreen mode Exit fullscreen mode

3.Use the window.scrollBy method in JavaScript to perform a vertical scroll by 300 pixels. Click on the ‘I Accept’ button to accept the T&C.

WebElement elem_accept_btn = web_driver.findElement(By.cssSelector("a.cbtn:nth-child(1)"));
Thread.sleep(2000);
elem_accept_btn.click();
((JavascriptExecutor)web_driver).executeScript("window.scrollBy(0,300)", "");
Enter fullscreen mode Exit fullscreen mode

4.Locate the required WebElement that has the text ‘What are parallel tests?’. We use the XPath element locator in Selenium to locate the required element.


WebElement elem_parallel = web_driver.findElement(By.xpath("//div[@class='col-sm-3 pricingcol ng-scope mostpopularpricecol']//p[.='What are parallel tests?']"));
Enter fullscreen mode Exit fullscreen mode

5.Once the WebElement is located, use the moveToElement() method of Actions class in Selenium to move to the searched element. Perform the built action using the perform() method.

Thread.sleep(2000);
action.moveToElement(elem_parallel).build().perform();
Enter fullscreen mode Exit fullscreen mode

6.Locate the WebElement that contains the body of the hover menu. Instead of Inspect in Chrome, we have used the POM Builder add-on to locate the element using the XPath property.


WebElement elem_hover_body = web_driver.findElement(By.xpath("//div[@class='popover-body']"));
Enter fullscreen mode Exit fullscreen mode

7.Move the mouse to the middle of the web element (i.e. elem_hover_body) that contains body of the hover menu. Use the build().perform() to compile and execute the action class.

Thread.sleep(2000);
action.moveToElement(elem_hover_body).build().perform();
Enter fullscreen mode Exit fullscreen mode

8.Locate the required link in the Hover using the linkText property. Perform a wait of 5 seconds till the presence of the element (located using linkText) is detected. Click on the link [with text ‘Calculate how many you need’ ] inside the Hover Menu.

By locator = By.linkText("Calculate how many you need");

/* Selenium Java 3.141.59 */
/* WebDriverWait wait = new WebDriverWait(web_driver, 5); */
WebDriverWait wait = new WebDriverWait(web_driver, Duration.ofSeconds(5));
wait.until(ExpectedConditions.presenceOfElementLocated(locator)).click();
Enter fullscreen mode Exit fullscreen mode

9.Using the getWindowHandles() method in Selenium WebDriver to get the window handles of the two (i.e. parent and child) open windows. Switch to the newly opened window using the switchTo().window(child_window) method where ‘window handle’ of the child window is passed to the method.

10.Assert if the title of the window (that is opened due to click on the link in the hover menu) does not match with the expected title.

Assert.assertEquals(web_driver.getTitle(), "Concurrency Calculator For LambdaTest Selenium Automation Gird");
Enter fullscreen mode Exit fullscreen mode

Execution

Here is the execution snapshot obtained from IntelliJ IDEA IDE. As seen in the output, we are able to switch to the new window and the window title matches with the expected title (i.e. Concurrency Calculator For LambdaTest Selenium Automation Gird).

Here is the snapshot of the sequences performed on the LambdaTest Grid:

The mouse is moved to the element that contains the Hover Menu.

The link in the hover menu is clicked and the focus is shifted to the newly opened window.

In this XCUITest tutorial, learn about XCUITest framework and its benefits for mobile automation testing. Take a look at how XCUITest works and see how to use it to test your mobile applications.

Wrapping It Up!

Automation of low-level mouse interactions is one of the widely-used strategies in Selenium test automation. Action Class in Selenium provides the necessary methods for automating mouse interactions on the web page. The actions class provides methods like click(), doubleClick(), contextClick(), and more for automating mouse-related actions.

In this detailed blog, we had a detailed look at how to perform mouse actions in Selenium WebDriver. Though Selenium 4 provides a rich set of Action APIs to perform Selenium test automation, mouse-related actions are still retained (with minor changes/optimizations) in the framework.

How do you leverage Action Class in Selenium to perform Selenium test automation? Do leave your experience in the comments section…

Happy Testing☺

Top comments (0)