How to Handle Mouse Actions in Selenium
Faisal Khatri
Posted On: September 13, 2024
321884 Views
16 Min Read
While automating a website using Selenium, you can realize specific scenarios by automating low-level interactions such as keypresses and mouse button actions with the WebElements in the Document Object Model (DOM).
Implementing Selenium tests that involve automating actions like accessing drop-down boxes and clicking or double-clicking on a button requires good know-how of the Actions class in Selenium. At a broad level, the Actions class comprises keyboard and mouse actions, but our focus would be on mouse actions in Selenium.
TABLE OF CONTENTS
What Are Mouse Actions in Selenium?
Mouse actions in Selenium provide a mechanism for automating low-level elementary interactions such as mouse clicks, mouse hover, and mouse button actions. It also helps with automating complex low-level interactions such as mouse hover, drag and drop, click and hold, and more.
Here is a brief list of methods for handling mouse actions that are provided by the Actions class in Selenium:
- click() method
- doubleClick() method
- clickAndHold() method
- contextClick() method
- dragAndDrop() method
- moveToElement() method
- moveByOffset() method
- release() method
Subscribe to the LambdaTest YouTube Channel for more such tutorials.
Handling Mouse Actions in Selenium
Now that we have known the methods for mouse actions in Selenium, let’s look at how to implement them.
Implementation:
Import the package org.openqa.selenium.interactions.Actions. Then, create an object of the Actions class and pass the Selenium WebDriver instance to the object.
1 2 |
WebDriver driver = new ChromeDriver(); Actions actions = new Actions(driver); |
Use the object to access the methods for automating mouse-related operations in the Selenium script.
We will use the TestNG framework and Selenium 4. At the time of writing this blog, the latest version of Selenium WebDriver in place was 4.23.1
1 2 3 4 5 |
<dependency> <groupId>org.seleniumhq.selenium</groupId> <artifactId>selenium-java</artifactId> <version>4.23.1</version> </dependency> |
The pom.xml file is used for downloading the requisite packages from the Maven repository. The respective tests are executed on cloud testing platforms like LambdaTest. It is an AI-driven test execution platform that lets you test mouse actions with Selenium online on various browsers and operating systems. It helps ensure consistent behavior of mouse interactions across different environments, reducing the need for local infrastructure.
You get access to your Username and Access Key from your LambdaTest Account Settings > Password and Security. Also, the automation capabilities can be generated using the LambdaTest Automation Capabilities Generator.
A new mouseactionsdemo package has been created inside the src/test folder that will have all the demo test scenarios for handling mouse actions in Selenium.
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
@BeforeTest public void setup() { final String userName = System.getenv("LT_USERNAME") == null ? "LT_USERNAME" : System.getenv("LT_USERNAME"); final String accessKey = System.getenv("LT_ACCESS_KEY") == null ? "LT_ACCESS_KEY" : System.getenv("LT_ACCESS_KEY"); final String gridUrl = "@hub.lambdatest.com/wd/hub"; try { this.driver = new RemoteWebDriver(new URL("http://" + userName + ":" + accessKey + gridUrl), getChromeOptions()); } catch (final MalformedURLException e) { System.out.println("Could not start the remote session on LambdaTest cloud grid"); } this.driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20)); } public ChromeOptions getChromeOptions() { final var browserOptions = new ChromeOptions(); browserOptions.setPlatformName("Windows 10"); browserOptions.setBrowserVersion("127.0"); final HashMap<String, Object> ltOptions = new HashMap<String, Object>(); ltOptions.put("project", "Mouse Actions Demo"); ltOptions.put("build", "LambdaTest Selenium Playground"); ltOptions.put("name", "Perform Mouse Actions using Selenium WebDriver"); ltOptions.put("w3c", true); ltOptions.put("plugin", "java-testNG"); browserOptions.setCapability("LT:Options", ltOptions); return browserOptions; } @AfterTest public void tearDown() { this.driver.quit(); } } |
The setup() method that has the @BeforeTest annotation over it will set up the configuration for running the tests on the LambdaTest cloud grid. The getChromeOptions() method will pass on the required capabilities for running the tests on the Chrome browser.
Likewise, the tearDown() method that has the @AfterTest annotation will close the WebDriver session gracefully.
Now, let’s look at different types of mouse actions in Selenium.
Single Click Action in Selenium
Single click is one of the basic mouse actions in Selenium that you will be required to perform during the Selenium test automation process. Left 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 the right click opens up the context menu.
For more details about mouse click action, refer to this blog on the Selenium click button method.
In this blog, we will use the LambdaTest eCommerce Playground website for our test scenarios.
Test Scenario:
|
Implementation:
A new testMouseClickAction() method has been added in the class TestMouseActions that implements the above test scenario.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Test public void testMouseClickAction() { driver.get("https://ecommerce-playground.lambdatest.io/"); WebElement searchBox = driver.findElement(By.name("search")); searchBox.sendKeys("iPhone"); WebElement searchBtn = driver.findElement(By.cssSelector("button[type=submit]")); searchBtn.click(); String pageHeader = driver.findElement(By.cssSelector("#entry_212456 h1")).getText(); assertEquals(pageHeader, "Search - iPhone"); } |
Code Walkthrough:
The test navigates the user to the home page of the LambdaTest eCommerce Playground website. It locates the search box using the name locator strategy of Selenium and types the word iPhone in it.
The search button will be located next using the CSS Selector locator strategy, and a click action will be performed on the button using the click() method.
The page header will be located at the end, and its text will be stored in the pageHeader variable in string format using the getText() method of Selenium. Finally, an assertion will be performed to check that the page header equals Search- iPhone.
Test Execution:
The following screenshot of the test execution on the LambdaTest platform:
Double Click Action in Selenium
Double click mouse action in Selenium is one of the prime actions used for Selenium test automation.
Test Scenario:
|
Implementation:
A new testDoubleClickAction() method has been created in the existing TestMouseActions class to implement the test scenario.
1 2 3 4 5 6 7 8 9 10 11 12 |
@Test public void testDoubleClickAction () { driver.get("https://unixpapa.com/js/testmouse.html"); WebElement clickHereText = driver.findElement(By.linkText("click here to test")); Actions actions = new Actions(driver); actions.doubleClick(clickHereText).build().perform(); WebElement textBox = driver.findElement(By.tagName("textarea")); String textBoxValue = textBox.getAttribute("value"); assertTrue(textBoxValue.contains("dblclick")); } |
Code Walkthrough:
This test script locates the click here to test link after navigating to the website. Next, the Actions class by Selenium performs a double-click action on the link.
The text box that shows the click action information is located using the tagName locator strategy and the CSS attribute value.
The last statement of the code performs an assertion to check that the text box contains the text dblclick in it.
Test Execution:
The following screenshot of the test execution on the LambdaTest platform:
Context Click Action in Selenium
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 WebElement). The items in the context menu depend on the WebElement on which right-click is performed.
Test Scenario:
|
Implementation:
A new testContextClickAction() method is added to the existing TestMouseActions class to implement the test scenario.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Test public void testContextClickAction() { driver.get("https://www.lambdatest.com/selenium-playground/context-menu"); WebElement contextClickBox = driver.findElement(By.id("hot-spot")); Actions actions = new Actions(driver); actions.contextClick(contextClickBox).build().perform(); Alert alert = driver.switchTo().alert(); String alertText = alert.getText(); assertEquals(alertText, "You selected a context menu"); alert.accept(); } |
Code Walkthrough:
The above test script will locate the context click-box using the id locator hot-spot on the context menu page of the LambdaTest Selenium Playground website. Using the contextClick() method of the Actions class of Selenium WebDriver, the right-click action will be performed.
After the right click is performed, an alert message will be displayed, and the text of this message will be stored in the alertText variable in string format. Finally, an assertion will be performed to check that the alert text equals You selected a context menu.
Test Execution:
Automate mouse actions across 3000+ real desktop browsers. Try LambdaTest Now!
Advanced Use Cases: Mouse Actions in Selenium
In the above section, we discussed handling different types of mouse actions in Selenium, such as click, double-click, and context click. Now, let’s look at some more advanced use cases of mouse actions in Selenium.
Automate Slider Movement
For automating test scenarios where a WebElement like slider is involved, we have to use the moveByOffset() method with the X and Y coordinates to move the slider. The moveByOffset() method can also be used for clicking anywhere on the page where the offset is in the form of an X and Y coordinate pair.
Let’s consider the following test scenario for demonstrating the slider movement using moveByOffset() in Selenium.
Test Scenario:
|
Implementation:
For moving the slider horizontally, we have to perform the following set of mouse actions:
- Click and hold the slider element.
- Move the slider element by the specified offset using the moveByOffset() method.
- Release the mouse at the resultant X and Y position.
- Perform the set of actions.
The test scenario has been implemented by creating a new testSliderAction() in the existing TestMouseActions class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
@Test public void testSliderAction() { driver.get("https://www.lambdatest.com/selenium-playground/drag-drop-range-sliders-demo"); WebElement slider = driver.findElement(By.cssSelector("input[type='range'][value='5']")); Point point = slider.getLocation(); int xcord = point.getX(); int ycord = point.getY(); System.out.println("x: " + xcord); System.out.println("y: " + ycord); Actions actions = new Actions(driver); actions.clickAndHold(slider).moveByOffset(-145,0).release().build().perform(); String outputResult = driver.findElement(By.cssSelector("output#range")).getText(); assertEquals(outputResult, "20"); } |
Code Walkthrough:
The slider on the Slider Demo page is located using the CSS Selector locator strategy combining the type and value attributes. Now, as we need to drag the slider using the offset, we need the X and Y coordinates of the slider.
Hence, we will be retrieving the X and Y coordinates of the slider using the getX() and getY() methods of the point class. We can then use the Y coordinates to drag the slider using the moveByOffset() method from the Actions class.
When we execute the test, the X and Y coordinates are printed in the console as X: 60 and Y: 282.
These coordinates are actually the points in the center of the slide. So, in order to move the slide to 20, we need to provide a negative value of -145 in the offset X coordinate (value between 0 and -282 as point 282 is the center, i.e., 50). Similarly, if we need to move the slider above 50, then we need to provide positive values between 0 to 282.
We will be chaining the actions, i.e., click and hold, moveByOffset() method, and then release the mouse to drag the slider. This chaining will be performed using the Actions class in Selenium.
After the slider is dragged successfully, an assertion will be performed to check that the slider was dragged successfully to 20 pixels.
Test Execution:
Shown below is the position of the slider element before the test is executed:
Here is a snapshot that indicates that the slider element has moved by an offset of (-145, 0). It is just before the release operation is performed, due to which the slider element is still in focus.
The test execution details with video and screenshots can be found on the LambdaTest Web Automation Dashboard page.
Drag and Drop Operation
There are scenarios in Selenium web automation where you will 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 methods that can be used to carry out a drag-and-drop operation using the Actions class in Selenium:
Let’s look at each of these approaches that demonstrate mouse actions in Selenium for the following test scenario:
- dragAndDrop() method
- clickAndHold() and moveToElement() methods
- dragAndDropBy() method
Test Scenario:
|
dragAndDrop() Method
In this method, we will be using the dragAndDrop() method of the Actions class to drag and drop the WebElement. Let’s create a new testDragAndDrop() method in the existing test TestMouseActions class to implement the test scenario.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Test public void testDragDrop() { driver.get("https://www.lambdatest.com/selenium-playground/drag-and-drop-demo"); WebElement draggable = driver.findElement(By.cssSelector("#todrag > span:nth-child(2)")); WebElement dropZone = driver.findElement(By.id("mydropzone")); Actions actions = new Actions(driver); actions.dragAndDrop(draggable,dropZone).build().perform(); String droppedItemList = driver.findElement(By.cssSelector("#droppedlist span")).getText(); assertEquals(droppedItemList, "Draggable 1"); } |
Code Walkthrough:
The draggable item will be located using the CSS Selector locator strategy #todrag > span:nth-child(2) as there are two draggable items on the screen. CSS Selectors make it easy to locate the WebElements using the nth-child selector.
Next, the drop zone is located using the ID locator strategy. The dragAndDrop() method from the Actions class is used to perform the drag and drop action where we need to supply the draggable item as the source WebElement and drop zone as the target WebElement.
An assertion is finally performed to verify that the drag and drop actions were performed as required, where we check that the Dropped Item List has the value Draggable 1 in it.
Test Execution:
The following screenshot from LambdaTest Web Automation Dashboard shows the test execution details with a video of the test execution and different test steps.
clickAndHold() and moveToElement() Methods
Let’s create a new testDragDropApproachTwo() method for implementing this approach in the existing test TestMouseActions class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
@Test public void testDragDropApproachTwo() { driver.get("https://www.lambdatest.com/selenium-playground/drag-and-drop-demo"); WebElement draggable = driver.findElement(By.cssSelector("#todrag > span:nth-child(2)")); WebElement dropZone = driver.findElement(By.id("mydropzone")); Actions actions = new Actions(driver); actions.clickAndHold(draggable).moveToElement(dropZone).release().build().perform(); String droppedItemList = driver.findElement(By.cssSelector("#droppedlist span")).getText(); assertEquals(droppedItemList, "Draggable 1"); } |
Code Walkthrough:
This script will navigate to the Drag and Drop Demo page and locate the draggable WebElement using the CSS Selector strategy. Next, it will locate the drop zone WebElement using the ID locator strategy.
The following lines of code will help in dragging and dropping of WebElements using clickAndHold() and moveToElement() methods.
Finally, it will perform the assertion to check that the Dropped Items List has the Droppable 1 WebElement in it.
Test Execution:
The following screenshot from LambdaTest Web Automation Dashboard shows the test execution details.
dragAndDropBy() Method
Let’s create a new testDragDropApproachThree() method to implement the third approach and use the dragAndDropBy() method to implement the test scenario.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
@Test public void testDragDropApproachThree() { driver.get("https://www.lambdatest.com/selenium-playground/drag-and-drop-demo"); WebElement draggable = driver.findElement(By.cssSelector("#todrag > span:nth-child(2)")); Actions actions = new Actions(driver); actions.dragAndDropBy(draggable, 477, 0).build().perform(); String droppedItemList = driver.findElement(By.cssSelector("#droppedlist span")).getText(); assertEquals(droppedItemList, "Draggable 1"); } |
Code Walkthrough:
The script will navigate to the Drag and Drop Demo page, locating the draggable WebElement using the CSS Selector strategy. The drag and drop action will be performed using the dragAndDropBy() method of the Actions class.
This dragAndDropBy() method needs three parameters, i.e., source element, xOffset, and yOffset. The source element is draggable, which we located earlier. Now, to locate the X and Y offset, there is a quick tip that can be used.
The X offset can be quickly located using the following steps:
- Locate the WebElement using the DevTools window in Chrome.
- On the right hand of the DevTools window, click on the Computed tab and check the center point of the WebElement. Currently, it shows 477.500 x 0.
We can use the X offset as 477 and Y offset as 0 for performing the drag and drop action. The following line of code will allow us to achieve the action we intend to perform.
After the drag and drop action is complete, an assertion will be performed to check that the draggable item was moved to the correct drop zone.
Test Execution:
The following screenshots are of the test execution performed using IntelliJ IDE, showing that the drag-and-drop action was completed.
The test execution details can be found on the LambdaTest Web Automation Dashboard with video and other insights like logs, screenshots, test steps, etc.
Click a Link in Hover Menu
Here are the steps to automate clicking on a link that is inside the hover menu:
- Use the moveToElement() method to move the pointer to the WebElement containing the link in the hover menu.
- Trigger perform() method to execute the prepared action, making the hover menu visible.
- Locate the hover menu using the findElement() method.
- Use moveToElement() method again to move the pointer to the body of the hover menu.
- Locate the required link in the hover menu using a suitable locator (e.g., linkText).
- Wait for a certain duration using ExpectedConditions.presenceOfElementLocated, then perform a click() method on the located link, ensuring it is present in the DOM before proceeding.
You can also check out this blog to learn about mouse hover in Selenium.
Test Scenario:
|
Implementation:
Let’s create a new testMouseHover() method in the TestMouseActions class for implementing this test scenario.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
@Test public void testMouseHover() { driver.get("https://ecommerce-playground.lambdatest.io/"); WebElement myAccountLink = driver.findElement(By.cssSelector("#widget-navbar-217834 > ul > li:nth-child(6) > a")); Actions actions = new Actions(driver); actions.moveToElement(myAccountLink).build().perform(); WebElement loginLink = driver.findElement(By.linkText("Login")); loginLink.click(); List<WebElement> pageHeaders = driver.findElements(By.tagName("h2")); String loginHeader = pageHeaders.get(1).getText(); assertEquals(loginHeader, "Returning Customer"); } |
Code Walkthrough:
The script navigates to the LambdaTest eCommerce Playground website and locates the My account link using the CSS Selector strategy. The mouse hover action will be performed using the moveToElement() method of the Actions class in Selenium WebDriver.
The moveToElement() method takes the target element as the parameter, which in our case is the My account link. When the My account link is hovered over by mouse, the menu should open, and next the Login link will be located using the linkText locator strategy of Selenium WebDriver.
An assertion needs to be performed next to check that the Login page was navigated successfully after clicking on the Login link. The page header text on the Login page is located using the tagName locator strategy. As there are multiple h2 tags on this page, we will be using the findElements() method of locator that will return a list of WebElements.
Finally, an assertion is done to check that the page header text equals the text Returning Customer.
Test Execution:
The following screenshot from LambdaTest Web Automation Dashboard shows the test execution details.
Wrapping 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.
In this detailed blog, we had a detailed look at how to perform mouse actions in Selenium and its different approaches. How do you leverage the Action class in Selenium to perform Selenium test automation? Try your hands on it and share your experience.
Frequently Asked Questions (FAQs)
How to use mouse actions in Selenium?
Selenium provides the Actions class to perform mouse actions like clicking, double-clicking, right-clicking, dragging, and hovering. You can use methods like moveToElement(), click(), and perform() to control these actions.
What are the actions of the mouse?
Mouse actions include clicking, double-clicking, right-clicking, hovering, dragging and dropping, scrolling, and clicking and holding. These actions allow users to interact with elements on a screen in various ways.
Can Selenium control a mouse?
Yes, Selenium can control a mouse using the Actions class, which simulates mouse movements and interactions with web elements, allowing automated testing of complex UI behavior.
Got Questions? Drop them on LambdaTest Community. Visit now