Automation QA Testing Course Content

Wait Commands in Selenium WebDriver


What are WebDriver waits/Synchronisation commands?

Waits are commands or techniques used to pause the execution of test scripts for a specified duration or until a certain condition is met. They are fundamental for handling synchronization issues between your test automation and the web application being tested.

WebDriver enables the user to choose amongst the available waits to handle situations where the execution flow may require a sleep for few seconds in order to load the web elements or to meet a specific condition. 

There are three types of waits available in WebDriver.
  •  Types of Waits:

    - Implicit Waits: These are set globally and apply to all elements in the test script. They instruct the WebDriver to wait for a certain amount of time before throwing an exception if an element is not found.
    - Explicit Waits: Explicit waits are used for specific elements and conditions. They wait until a certain condition is met or a timeout occurs before proceeding. This allows precise synchronization with elements on the page.
    - Fluent Waits: Fluent waits are a variation of explicit waits that allow you to define polling intervals, ignoring specific exceptions during the wait period.

When and Why Are Waits Necessary?

- Loading Delays: Web applications may load content dynamically, causing elements to appear or disappear. Waits ensure scripts don't proceed until the page is fully loaded.
- Animations and Transitions: UI animations and transitions can affect element visibility. Waits help scripts interact with elements once they become stable.
- Server Response Times: If your test depends on data retrieved from a server, you should wait for the server's response.
- Asynchronous Operations: When performing asynchronous actions like clicking a button that triggers a background process, waits ensure that the process completes before proceeding.

Implementing Waits:

1. Identify Conditions: Determine what condition(s) you need to wait for, such as element visibility, invisibility, or a specific text value.
2. Choose the Right Wait: Decide whether implicit, explicit, or fluent waits are appropriate for your use case.
3. Set Timeout Values: Define appropriate timeout values to avoid excessive waiting.
4. Apply in Test Scripts: Integrate waits before interacting with elements that require synchronization.

Implicit Wait

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0. Once set, the implicit wait is set for the life of the WebDriver object instance.
  • How to wait for a page to load in WebDriver
  • WebDriver wait for AJAX call to complete
  • WebDriver – open new browser window with Javascript

Syntax:
driver.manage().timeOuts().implicitlyWait(time,TimeUnit.SECONDS/MILLISECONDS/MINUTES);

ex:
driver.manage().timeOuts().implicitlyWait(5,TimeUnit.SECONDS);
driver.manage().timeOuts().implicitlyWait(5000,TimeUnit.MILLISECONDS);
driver.manage().timeOuts().implicitlyWait(1,TimeUnit.MINUTES);

SELENIUM 4 Chnages:
driver.manage().timeOuts().implicitlyWait(Duration.ofSeconds(30));
driver.manage().timeOuts().implicitlyWait(Duration.ofMilliSeconds(3000));
driver.manage().timeOuts().implicitlyWait(Duration.ofMinutess(1));

Explicit Wait

An explicit wait is a code that you define to wait for a certain condition to occur before proceeding further in the code. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully.

 //create an object for WebDriverWait class
WebDriverWait wait=new WebDriverWait(driver,time);

SELENIUM4 Changes:
WebDriverWait wait=new WebDriverWait(driver,Duration.ofSeconds(30));

wait.until(ExpectedConditions.staticmethodname());
--------------------
anonymous object:if you create an object for a class without reference variable then that object is called ananymous object

new WebDriverWait(driver,time).until(ExpectedConditions.staticmethodname());


When should we use explicit waits?
We would normally use explicit wait if an element takes a long time to load. We also used explicit wait to check CSS property of an element (presence, clickability. etc) which can change in Ajax applications.


ExpectedConditions class provides a great help to deal with scenarios where we have to ascertain for a condition to occur before executing the actual test step.

ExpectedConditions class comes with a wide range of expected conditions that can be accessed with the help of the WebDriverWait reference variable and until() method.
Let us discuss a few of them:
#1) elementToBeClickable() – The expected condition waits for an element to be clickable i.e. it should be present/displayed/visible on the screen as well as enabled.
Sample Code
wait.until(ExpectedConditions.elementToBeClickable(By.xpath(“//div[contains(text(),'COMPOSE')]”)));
#2) textToBePresentInElement() – The expected condition waits for an element having a certain string pattern.
Sample Code
wait.until(ExpectedConditions.textToBePresentInElement(By.xpath(“//div[@id= ‘forgotPass'”), “text to be found”));
#3) alertIsPresent()- The expected condition waits for an alert box to appear.
Sample Code
wait.until(ExpectedConditions.alertIsPresent()) !=null);
#4) titleIs() – The expected condition waits for a page with a specific title.
Sample Code
wait.until(ExpectedConditions.titleIs(“gmail”));
#5) frameToBeAvailableAndSwitchToIt() – The expected condition waits for a frame to be available and then as soon as the frame is available, the control switches to it automatically.
Sample Code
wait.until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.id(“newframe”)));
#6)invisibilityOf(WebElement element): An expectation for checking the element to be invisible
Sample Code
wait.until(ExpectedConditions.invisibilityOf(elementname));
#7)presenceOfElementLocated(By locator): An expectation for checking that an element is present on the DOM of a page.
Sample code:
wait.until(ExpectedConditions.presenceOfElementLocated(By.locator("locatorvalue")));
#8)titleContains(java.lang.String title): An expectation for checking the partial title of a page.

Sample code:
wait.until(ExpectedConditions.titleContains("partial title of the page"));

#9)urlContains(java.lang.String fraction): An expectation for the URL of the current page to contain specific text.
Sample Code:
wait.until(ExpectedConditions.urlContains("partial url");

#10)visibilityOf(WebElement element):

An expectation for checking that an element, known to be present on the DOM of a page, is visible.

Sample code:
wait.until(ExpectedConditions.visibilityOf(element));

#11)visibilityOfElementLocated(By locator):
An expectation for checking that an element is present on the DOM of a page and visible.
Sample Code:wait.until(ExpectedConditions.visibilityOfElementLocated(By.locator("locator value")));



Fluent Wait:
An implementation of the Wait interface that may have its timeout and polling interval configured on the fly.
When using the FluentWait instance, we can specify:
  • The frequency with which FluentWait has to check the conditions defined.
  • Ignore specific types of exception waiting such as NoSuchElementExceptions while searching for an element on the page.
  • The maximum amount of time to wait for a condition
Example of using FluentWait
// Waiting 30 seconds for an element to be present on the page, checking
// for its presence once every 5 seconds.
Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
    .withTimeout(30, SECONDS)
    .pollingEvery(5, SECONDS)
    .ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function<WebDriver, WebElement>() 
{
  public WebElement apply(WebDriver driver) {
  return driver.findElement(By.id("foo"));
}
});

𝐔𝐧𝐝𝐞𝐫𝐬𝐭𝐚𝐧𝐝𝐢𝐧𝐠 𝐭𝐡𝐞 𝐒𝐜𝐞𝐧𝐚𝐫𝐢𝐨:
File downloads are a common obstacle in automated testing scenarios. Ensuring your automation script waits patiently until a file is fully downloaded is crucial for robust and reliable testing.

✅ 𝐓𝐡𝐞 𝐒𝐨𝐥𝐮𝐭𝐢𝐨𝐧: Using Fluent Wait

Here's a step-by-step approach:

1) 𝐒𝐞𝐭𝐭𝐢𝐧𝐠 𝐔𝐩 𝐭𝐡𝐞 𝐄𝐧𝐯𝐢𝐫𝐨𝐧𝐦𝐞𝐧𝐭:
Configure your WebDriver instance to handle file downloads smoothly. Adjust browser preferences, manage pop-ups, and disable notifications for a streamlined process.

2)𝐍𝐚𝐯𝐢𝐠𝐚𝐭𝐞 𝐭𝐨 𝐭𝐡𝐞 𝐝𝐨𝐰𝐧𝐥𝐨𝐚𝐝 𝐩𝐚𝐠𝐞 & 𝐜𝐥𝐢𝐜𝐤 𝐨𝐧 𝐚 𝐝𝐨𝐰𝐧𝐥𝐨𝐚𝐝 𝐥𝐢𝐧𝐤 :
For Example, I am trying to install JDK file from given link :-https://lnkd.in/dpmFrbnW.

3) 𝐖𝐚𝐢𝐭𝐢𝐧𝐠 𝐟𝐨𝐫 𝐂𝐨𝐦𝐩𝐥𝐞𝐭𝐢𝐨𝐧:
Employ FluentWait to monitor the file system, allowing your script to wait until the downloaded file is fully available at the specified path.

✅ 𝐂𝐨𝐝𝐞:

𝐟𝐢𝐥𝐞 𝐟𝐢𝐥𝐞 = 𝐧𝐞𝐰 𝐟𝐢𝐥𝐞(𝐝𝐨𝐰𝐧𝐥𝐨𝐚𝐝𝐟𝐢𝐥𝐞𝐩𝐚𝐭𝐡,𝐟𝐢𝐥𝐞𝐧𝐚𝐦𝐞);
𝐟𝐥𝐮𝐞𝐧𝐭𝐰𝐚𝐢𝐭<𝐟𝐢𝐥𝐞> 𝐰𝐚𝐢𝐭 = 𝐧𝐞𝐰 𝐟𝐥𝐮𝐞𝐧𝐭𝐰𝐚𝐢𝐭<>(𝐟𝐢𝐥𝐞)
.𝐰𝐢𝐭𝐡𝐭𝐢𝐦𝐞𝐨𝐮𝐭(𝐝𝐮𝐫𝐚𝐭𝐢𝐨𝐧.𝐨𝐟𝐦𝐢𝐧𝐮𝐭𝐞𝐬(5))
.𝐩𝐨𝐥𝐥𝐢𝐧𝐠𝐞𝐯𝐞𝐫𝐲(𝐝𝐮𝐫𝐚𝐭𝐢𝐨𝐧.𝐨𝐟𝐬𝐞𝐜𝐨𝐧𝐝𝐬(5))
.𝐢𝐠𝐧𝐨𝐫𝐢𝐧𝐠(𝐞𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧.𝐜𝐥𝐚𝐬𝐬)
.𝐰𝐢𝐭𝐡𝐦𝐞𝐬𝐬𝐚𝐠𝐞("𝐟𝐢𝐥𝐞 𝐢𝐬 𝐧𝐨𝐭 𝐝𝐨𝐰𝐧𝐥𝐨𝐚𝐝𝐞𝐝 𝐜𝐨𝐦𝐩𝐥𝐞𝐭𝐞𝐥𝐲...");

𝐛𝐨𝐨𝐥𝐞𝐚𝐧 𝐢𝐬𝐟𝐢𝐥𝐞𝐝𝐨𝐰𝐧𝐥𝐨𝐚𝐝𝐞𝐝 = 𝐟𝐚𝐥𝐬𝐞;
𝐭𝐫𝐲 {
𝐢𝐬𝐟𝐢𝐥𝐞𝐝𝐨𝐰𝐧𝐥𝐨𝐚𝐝𝐞𝐝 = 𝐰𝐚𝐢𝐭.𝐮𝐧𝐭𝐢𝐥(𝐟->𝐟.𝐞𝐱𝐢𝐬𝐭𝐬() && 𝐟.𝐜𝐚𝐧𝐫𝐞𝐚𝐝());
} 𝐜𝐚𝐭𝐜𝐡 (𝐞𝐱𝐜𝐞𝐩𝐭𝐢𝐨𝐧 𝐞) {
𝐬𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐟𝐢𝐥𝐞 𝐢𝐬 𝐧𝐨𝐭 𝐝𝐨𝐰𝐧𝐥𝐨𝐚𝐝𝐞𝐝 𝐬𝐮𝐜𝐜𝐞𝐬𝐬𝐟𝐮𝐥𝐥𝐲..");
}

𝐢𝐟(𝐢𝐬𝐟𝐢𝐥𝐞𝐝𝐨𝐰𝐧𝐥𝐨𝐚𝐝𝐞𝐝)
{
𝐬𝐲𝐬𝐭𝐞𝐦.𝐨𝐮𝐭.𝐩𝐫𝐢𝐧𝐭𝐥𝐧("𝐟𝐢𝐥𝐞 𝐢𝐬 𝐝𝐨𝐰𝐧𝐥𝐨𝐚𝐝𝐞𝐝 𝐬𝐮𝐜𝐜𝐞𝐬𝐬𝐟𝐮𝐥𝐥𝐲..");
}

Confirm the successful download within the specified timeout duration.
 Handle exceptions using Try-Catch block.
When should we use FluentWait?
When you try to test the presence of an element that may appear after every x seconds/minutes.

Difference Between WebDriverWait and FluentWait

WebDriverWait is a subclass of FluentWait. In FluentWait you have more options to configure, along with maximum wait time, like polling interval, exceptions to ignore etc.
So, instead of waiting and then using findElement:
WebDriverWait wait = new WebDriverWait(driver, 18);
wait.until(ExpectedConditions.elementToBeClickable(By.linkText("Account")));

WebElement element = driver.findElement(By.linkText("Account"));
element.sendKeys(Keys.CONTROL);
element.click();
we can use:

WebElement element = wait.until(
        ExpectedConditions.elementToBeClickable(By.linkText("Account")));



Wait Interface in Selenium:

Wait is the generic interface, which makes selenium to wait for particular time with associated event. 
Events like element to be click-able, element to present.

Wait interface present under org.openqa.selenium.support.ui package, 
FluentWait and WebdriverWait implements Wait interface.
Until Method in WebdriverWait :
until is a abstract method present in Wait interface, whichever driver implements Webdriver 
the also must implement Wait interface.

Which means browser classes (FirefxDriver, ChromeDriver...) must implement methods present
in Wait and Webdriver interfaces.

until method accepts a ExpectedConditions values as parameter, 
class must wait till the given condition neither becomes null nor false 
when they implement until method. So until methods implementation must not have return type as void.

FluentWait class implements Wait Interface and WebdriverWait class extends FluentWait class, 
this is called as multi-level inheritance in java.

FluentWait class implements Wait interface in selenium, FluentWait object defines the maximum amount
 of time to wait for a condition. Below is the example for common way of using Fluent Wait,

// create object for FluentWait class
FluentWait fw = new FluentWait(driver);
// max time limit is 30 seconds
fw.withTimeout(30, TimeUnit.SECONDS);

SELENIUM4 Chnages:
fw.withTimeout(Duration.ofSeconds(30));

User can configure the frequency with which to check the condition.

// polls once in every 5 seconds
fw.pollingEvery(5, TimeUnit.SECONDS);

SELENIUM4 Chnages:
fw.pollingEvery(Duration.ofSeconds(30));

User may configure the FluentWait to ignore specific types of exceptions whilst waiting for the condition.

// ignore the Exception
fw.ignoring(NoSuchElementException.class);

User can configure the error message to display in case of TimeoutException occurs

// custom message to show if exception occurs
fw.withMessage("Time exceeded");

Difference between Implicit and Explicit Wait Commands in Selenium

Implicit Wait
1)Applies to all elements in a test script
2)No need to specify “ExpectedConditions” on the element to be located
3)Most effective when used in a test case in which the elements are located with the time frame specified in implicit wait
Explicit Wait
1)Applies only to specific elements as intended by the user.
2) Must always specify “ExpectedConditions” on the element to be located
3)Most effective when used when the elements are taking a long time to load. Also useful for verifying property of the element such as visibilityOfElementLocated, elementToBeClickable, elementToBeSelected


No comments:

Post a Comment

Note: Only a member of this blog may post a comment.