top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Mastering User Interactions with the Actions Class (Mouse and Keyboard Actions)

Selenium plays an exceptional role in testing Applications in todays world since it has variety of techniques to test web applications more effectively .It offers several methods and techniques to handle complex web UI which is easy to automate the whole process rather involving manual labor.

In Selenium WebDriver, user interactions like keyboard or mouse event occurs using Action Class.


What is Actions Class in Selenium WebDriver?

Actions class is used to handle Keyboard and Mouse Events. We need to import “org.openqa.selenium.interactions.Actions” in order to use Actions class. This class includes keyboard and mouse actions such as double click, right click, drag & drop, mouse hover and clicking multiple elements.

 

Actions Class commands can be classified in two categories:

  1. Mouse Actions

  2. Keyword Actions


Mouse Actions:

·       Mouse actions in Selenium are the actions that can be performed using a mouse, such as clicking, double-clicking, right-clicking, dragging and dropping, etc. These actions simulate a user’s interactions with a website through the mouse.


Getting started with Mouse Action Class:


1.     Creating an Instance of Action Class:  Import all the necessary classes as shown below

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Actions;


2.     Create an WebDriver Instance. Create a WebDriver instance

WebDriver driver = new chromedriver();


3.     Instantiate the Action Class using WebDriver Instance:

Actions actions = new Actions(driver); 

After following the above steps, Now we have an instance of Action class (actions) with which we can perform various mouse actions of web Elements.


Following are the few mouse actions

·       Clicking on Elements:

click() - performs a single mouse click on the specified element

Actions actions = new Actions(driver);

WebElement element = driver.findElement(By.id("elementId"));

actions.click(element).build().perform();

 

·       Click and Hold:

clickAndHold() - Sometimes, you may need to click and hold the mouse button on an element.

Actions actions = new Actions(driver);

WebElement element = driver.findElement(By.id("elementId"));

Actions.clickAndHold(element).build().perform();

 

·       Context Click (Right Click):

contextClick() - Simulating a right click on an element can be useful for interacting with context menus or triggering specific actions.

Actions actions = new Actions(driver);

WebElement element = driver.findElement(By.id("elementId"));

actions.contextClick(element).build().perform();

 

·       Double Clicking:

doubleClick() - Double clicking is used when you need to simulate a quick succession of two left mouse button clicks on an element.

Actions actions = new Actions(driver);

WebElement element = driver.findElement(By.id("elementId"));

actions.doubleClick(element).build().perform();

 

·       Drag and Drop:

dragAndDrop() - Dragging and dropping elements is a common interaction in many web applications. The Actions class provides the dragAndDrop() method to simulate this action.

Actions actions = new Actions(driver);

WebElement sourceElement = driver.findElement(By.id("sourceElementId"));

WebElement targetElement = driver.findElement(By.id("targetElementId"));

actions.dragAndDrop(sourceElement, targetElement).build().perform();

 

·       Releasing the Mouse Button:

release() -  releases the left mouse button on the specified element.

Actions actions = new Actions(driver);

WebElement element = driver.findElement(By.id("elementId"));

actions.clickAndHold(element).release().build().perform();

 

·       Moving to an Element:

moveToElement() -  moves the mouse cursor to the middle of the specified element.

Actions actions = new Actions(driver);

WebElement element = driver.findElement(By.id("elementId"));

actions.moveToElement(element).build().perform(); //Mouse Hover

 

·       Mouse Hover and Click:

There are scenarios in automation of mouse hover like clicking on a sub-menu link which appears only after moving your cursor to menu link . That’s a very challenging action to be captured in automation . However , Selenium Action class has an way as shown in below example,

 

WebElement menuLink = driver.findElement(By.xpath("/html/some/xpath")); //Xpath for Menu

WebElement subMenuLink = driver.findElement(By.xpath("/html/some/xpath")); //Xpath for SubMenu

Actions actions = new Actions(driver); // Create object of Actions class 

actions.moveToElement(menuLink); // Move cursor to Menu link (Mouse hover on menu link so that sub menu is displayed)

actions.click(subMenuLink).build().perform(); // Click on Submenu link (which is displayed after mouse hovering cursor on menu link)

            The above snippet demonstrates how to perform a mouse hover and click action using the Actions class. First, we locate the menu and submenu elements using their Xpaths. Then, we create an object of the Actions class. Next, we use the moveToElement() method to move the cursor to the menu link, triggering the display of the submenu. Finally, we use the click() method to click on the submenu link and the build().perform() methods to build and execute the actions.


Keyboard Actions:

Keyboard actions in Selenium are the actions that can be performed using a keyboard, such as pressing keys, holding down keys, releasing keys, etc. These actions simulate a user’s interactions with a website through the keyboard.

Getting started with Keyboard Action Class:


1.     Import all the Required Action Class:  Import all the necessary classes as shown below

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.interactions.Actions;

import org.openqa.selenium.Keys;


2.     Create an WebDriver Instance. Create a WebDriver instance

WebDriver driver = new chromedriver();


3.     Instantiate the Action Class using WebDriver Instance:

Actions actions = new Actions(driver);

 

Following are the Keyboard actions

·       sendKeys(CharSequence… keysToSend): sends a series of key presses to the specified element.

WebElement inputField = driver.findElement(By.xpath("//input[@id='input-field']")); // Locate the text input field

actions.sendKeys(inputField, "Hello").build().perform(); // Send "Hello" to the input field

 

·       keyDown and KeyUp(Keys theKey): holds down the specified key and releases the specified key.

actions.keyDown(Keys.SHIFT).build().perform(); // Press the SHIFT key

actions.keyUp(Keys.SHIFT).build().perform(); // Release the SHIFT key

 

Examples:

  WebElement FIRSTNAME = driver.findElement(By.name("firstname"));   // Store Location of Firstname

  Actions actions = new Actions(driver);

  actions.keyDown(Keys.SHIFT)   /* KeyUP and KeyDown */

  .sendKeys(FIRSTNAME, "john snow")   // This will type Username in Uppercase as we are typing using Shift key

  .keyUp(Keys.SHIFT)

  .build()

  .perform(); 

 

 Build and Perform the actions sequence:

·       Build method generates a composite action containing all actions so far which are ready to be performed.Notice that the build method returns the object type of Action. It is basically representing Composite Action which we built from a sequence of multiple actions.

Action action = actions.build();

action.perform();

·       And finally, perform the actions sequence using perform() method of Action Interface. Once its done , the execution passes this point, you will notice the action on the browser.


Combination of Keyboard actions :

By combining  multiple keyboard actions using the keyDown, keyUp, and sendKeys methods

// Press CTRL + A to select all actions.keyDown(Keys.CONTROL).sendKeys("a").keyUp(Keys.CONTROL).build().perform();

 

Chaining Multiple Actions Together

we chain multiple actions to move the mouse to element1, click it, then move to element2, and click it as well. The build() method builds the composite action, and the perform() method executes the action.

Actions actions = new Actions(driver);

actions.moveToElement(element1)

       .click()

       .moveToElement(element2)

       .click()

       .build()

       .perform();

 

Performing Actions on Nested Elements

In this example, we first move the mouse to the parentElement and then move to the nestedElement to perform a click action.

actions.moveToElement(parentElement)

       .moveToElement(nestedElement)

       .click()

       .build()

       .perform();

 

Waiting for Specific Conditions Before Performing Actions

In this example, we use an explicit wait to wait for the visibility of the element with the specified ID. Once the element is visible, we perform the desired action using the Actions class.

Actions actions = new Actions(driver);

WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("element-id")));

actions.moveToElement(element)

       .click()

       .build()

       .perform();

 

Advanced Techniques with the Actions Class:-


 Handling Dynamic Elements during Actions

In certain cases, the elements on a web page may change dynamically during the execution of an action. This can cause the action to fail if the element is no longer available. To handle this situation, you can use the moveToElement() method with the offset parameters to perform actions relative to the current mouse position. Here's an example:

Actions actions = new Actions(driver);

WebElement element = driver.findElement(By.id("dynamic-element"));

 

// Get the current position of the mouse cursor

int xOffset = 10;  // Adjust the X offset as per your requirements

int yOffset = 10;  // Adjust the Y offset as per your requirements

 // Move the mouse cursor to the element with the specified offset

actions.moveToElement(element, xOffset, yOffset)

       .click()

       .build()

       .perform();

In this example, we first locate the dynamically changing element using a suitable locator strategy. Then, we use moveToElement() with the desired offset values to move the mouse cursor relative to the element's position. Finally, we perform the desired action, such as a click, on the dynamic element.

 

Integrating with Explicit Waits for Synchronization

To ensure that our actions are performed on the correct elements at the right time, it is important to synchronize our test scripts with the application's behavior. Explicit waits can be used in combination with the Actions class to wait for specific conditions before performing actions. Here's an example:

 

Actions actions = new Actions(driver);

WebDriverWait wait = new WebDriverWait(driver, 10);

WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("element-id")));

actions.moveToElement(element)

       .click()

       .build()

       .perform();

 

Leveraging the Page Object Model (POM) Design Pattern

We can integrate the Actions class into your POM-based test scripts by creating methods in the page object classes that perform the desired actions

 

In this example, we have a HomePage class that contains a method hoverOnElement() to perform a mouse hover action on a given element. By encapsulating the actions within the page object class, you can easily reuse them across different test cases and keep your code organized.

 

public class HomePage {

    private WebDriver driver;

    private Actions actions;

 

    // Constructor

    public HomePage(WebDriver driver) {

        this.driver = driver;

        actions = new Actions(driver);

    }

    // Perform mouse hover action on an element

    public void hoverOnElement(WebElement element) {

        actions.moveToElement(element)

               .build()

               .perform();

    }}

Benefits of Using the Actions Class –

·       Support for Mouse and Keyboard Actions:

·       Enhanced User Interactions: 

·       Cross-Browser Compatibility

·       Handling Complex Scenarios:

·       Improved Test Coverage:

·       Integration with Explicit Waits:

·       Seamless Integration with Page Object Model (POM)

15 views0 comments

コメント

5つ星のうち0と評価されています。
まだ評価がありません

評価を追加
bottom of page