Software Testing

Selenium 4 Waits and Timeout

Selenium 4 Waits and Timeout

In Selenium 4, the parameters received in Waits and Timeout have changed from expecting (long time, TimeUnit unit) to expect (Duration duration) which you will notice a deprecation message for all our tests.

When executing selenium automation tests, we use waits to make our tests reliable and robust. Most commonly, while running automation tests, we see ‘ElementNotVisibleException‘ if there is a delay in loading particular element which Webdriver wants to interact.

Waits and Timeout helps the user to overcome various issues while loading elements on a page after performing some action or navigating across different pages in the application.

Selenium 4 Implicit Wait

Let’s see how to define implicit wait after upgrading to Selenium 4.

Before Selenium 4 –

driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Now we will see this as deprecated

@Deprecated

WebDriver.Timeouts implicitlyWait(long time, TimeUnit unit);

After Selenium 4 –

driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

 

Same with the other waits like scriptTimeout and pageLoadTimeout :-

driver.manage().timeouts().scriptTimeout(Duration.ofMinutes(2));
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));

Selenium 4 Explicit Wait

WebDriverWait is also expects a ‘Duration’ instead of  timeout in seconds and milliseconds.

The method is now deprecated in selenium

public WebDriverWait(@NotNull org.openqa.selenium.WebDriver driver, long timeoutInSeconds)

Before Selenium 4 – old syntax

WebDriverWait wait = new WebDriverWait(driver,10);
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".classlocator")));

After Selenium 4 – new syntax

//Selenium 4 New Syntax
WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(".classlocator")));

Selenium 4 FluentWait

Before Selenium 4 – old syntax

Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
  .withTimeout(30, TimeUnit.SECONDS)
  .pollingEvery(5, TimeUnit.SECONDS)
  .ignoring(NoSuchElementException.class);

After Selenium 4 – new syntax

  Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)
  .withTimeout(Duration.ofSeconds(30))
  .pollingEvery(Duration.ofSeconds(5))
  .ignoring(NoSuchElementException.class);

Please do let us know if you face any issues upgrading to selenium 4 using comment form below. We will comment back to your query.