In our last tutorial, we examined the technical aspects of incorporating logging into a framework. We had an in-depth discussion on the log4j tool. We dove into the fundamental elements that make up log4j from a usability perspective. Through the use of Appenders and layouts, the users can select their preferred logging format/pattern and data source/location.
In this 27th part of our all-inclusive free selenium online training series, we are going to shift our focus onto a few seemingly minor but important topics that can assist in troubleshooting repeated issues. While these topics may not be utilized daily, they can be extremely useful in the long haul.
Recommended IPTV Service Providers
- IPTVGREAT – Rating 4.8/5 ( 600+ Reviews )
- IPTVRESALE – Rating 5/5 ( 200+ Reviews )
- IPTVGANG – Rating 4.7/5 ( 1200+ Reviews )
- IPTVUNLOCK – Rating 5/5 ( 65 Reviews )
- IPTVFOLLOW -Rating 5/5 ( 48 Reviews )
- IPTVTOPS – Rating 5/5 ( 43 Reviews )
We will be delving into advanced topics like mouse and keyboard events, and accessing multiple links with the help of lists. So, let’s begin our exploration of these subjects through relevant scenarios and code snippets.
Lessons You Will Take Away:
JavaScript Executors
In the automation of test scenarios, some actions become an inherent part of the test scripts.
These actions might entail:
- Clicking on buttons, hyperlinks, etc.
- Inputting text in a textbox
- Scrolling horizontally or vertically until the desired object comes into view
- And more
As we gathered from previous tutorials, the ideal way to automate these tasks is by utilizing Selenium commands.
But, what happens if the Selenium commands fail to execute?
There could be instances where basic Selenium commands may not function as expected.
In such instances, we can resort to JavaScript executors to find a solution to the problem.
What Exactly are JavaScript Executors?
The JavascriptExecutor interface, part of org.openqa.selenium, implements the java.lang.Object class. It enables the execution of JavaScript directly within the web browsers. It offers methods and a set of specifics parameters to execute JavaScript.
Methods
executeScript (String script, args)
This method executes JavaScript in the current window, alert, frame, etc. (the window that WebDriver instance is currently targeting).
executeAsyncScript (String script, args)
This method executes JavaScript asynchronously in the current window, alert, frame, etc. (the window that WebDriver instance is currently targeting).
Both executor methods possess common parameters and an import statement.
Parameters
Script – the script to execute
Arguments – the parameters required for the script’s execution (if any)
Import statement
To enable JavascriptExecutors in our test scripts, we need to import the package with the following syntax:
import org.openqa.selenium.JavascriptExecutor;
Sample Code
#1) Clicking a Web Element
// Identifying the web element using id WebElement element = driver.findElement(By.id("id of the webelement")); // Initializing JavascriptExecutor JavascriptExecutor js = (JavascriptExecutor) driver; // Clicking the web element js.executeScript("arguments[0].click();", element);
#2) Typing in a Text Box
// Initializing JavascriptExecutor JavascriptExecutor js = (JavascriptExecutor) driver; // Typing the test data into Textbox js.executeScript("document.getElementById('id of the element').value='test data';");
#3) Scrolling until the Web Element is in View
WebElement element = driver.findElement(By.xpath("//input[contains(@value,'Save')]")); // Initializing the JavascriptExecutor and scrolling into view in one test step ((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
There are several ways to script the code for using JavascriptExecutors.
Handling Multiple Elements in a List
Occasionally, we come across many similar types of elements, such as numerous hyperlinks or images grouped in an ordered or unordered list. In these instances, it’s best to manage these elements using a single code by leveraging a WebElement List. The screenshot below shows the elements I am referring to.
In the image above, we notice that various service providers are part of an unordered list. Hence, we can verify the clickability and visibility of these elements using one code by employing a list of elements.
Import statement
To implement a WebElement list in our test scripts, we need to import the package using the following syntax:
import java.util.List;
Sample Code
// Storing the list ListserviceProviderLinks = driver.findElements(By.xpath("//div[@id='ServiceProvider']//ul//li")); // Determining the size of the list int listSize = serviceProviderLinks.size(); for (int i = 0; i < listSize; i++) { // Clicking on each service provider link serviceProviderLinks.get(i).click(); // Navigating back to the previous page that contains links to service providers driver.navigate().back(); }
There are various other situations where lists can be used to verify elements by making suitable implementation amendments.
Controlling Keyboard and Mouse Events
Managing Keyboard Events
As stated earlier, there exist plentiful approaches to address the same issues in different contexts.
There might be scenarios when it becomes critical to deviate from the traditional handling strategy and adopt a more advanced one. I have experienced situations where it was difficult to manage alerts and pop-ups using only Selenium commands, and therefore had to resort to different Java utilities to manage them via keyboard strokes and mouse events.
The Robot class is one such option for performing keyboard and mouse events.
Let's explore this concept through an implementation based on a scenario.
Scenario:
Envision a situation where an unwanted pop-up appears on the screen which cannot be confirmed or dismissed using the Alert Interface. In such a case, the only feasible option is to close the window using shortcut keys - "Alt + spacebar + C". Let's see how we can close the pop-up using the Robot Class.
Before beginning the implementation, we need to import the necessary package to use the Robot class in our test script.
Import Statement
import java.awt.Robot;
Sample Code
// Initializing Robot class Robot rb = new Robot(); // Calling KeyPress event rb.keyPress(KeyEvent.VK_ALT); rb.keyPress(KeyEvent.VK_SPACE); rb.keyPress(KeyEvent.VK_C); // Calling KeyRelease event rb.keyRelease(KeyEvent.VK_C); rb.keyRelease(KeyEvent.VK_SPACE); rb.keyRelease(KeyEvent.VK_ALT);
The Robot class can also handle mouse events, but for now, let's stick to Selenium's capabilities to control mouse events.
Managing Mouse Events
WebDriver provides numerous interaction utilities that users can leverage to automate mouse and keyboard events. The Action Interface is such a utility that simulates single-user interactions.
In the forthcoming scenario, we will observe the use of the Action Interface to perform a mouse hover on a dropdown menu, subsequently displaying a list of options.
Scenario:
- Mouse hover on the dropdown
- Select one of the items from the options list
Import Statement
import org.openqa.selenium.interactions.Actions;
Sample Code
// Initializing Action Interface Actions actions = new Actions(driver); // Hovering on the dropdown actions.moveToElement(driver.findElement(By.id("id of the dropdown"))).perform(); // Selecting one of the items from the options list WebElement subLinkOption = driver.findElement(By.id("id of the sub link")); subLinkOption.click();
Conclusion
In this tutorial, we went over advanced topics related to effective scripting and resolving scenarios that require handling mouse and keyboard events. We also went over how to store multiple web elements in a list. I believe this knowledge will aid you in resolving these hurdles should you come across them.
Next Tutorial #28: In the upcoming tutorial in this series, we will examine the principle of Database Testing using Selenium WebDriver. We will delve into the mechanisms of database connection, execution of Selenium queries, and fetching results through Selenium WebDriver code.