Is it best practice to use Thread.sleep() or explicit wait before click on any element in selenium web driver

24,491

Solution 1

Explicitly waiting for a certain element and its certain state is the best practice in selenium-webdriver. Sleeps are never a good idea since your sleep timeout could be less or more and therefore makes your test inconsistent and non-deterministic.

Using WebDriver wait until is the best solution for synchronizing issues. So in JS something like this,

var until = webdriver.until;
var searchBox = 
driver.wait(until.elementIsEnabled(driver.findElement(webdriver.By.name('q'))),5000,'Search button is not enabled');  

Solution 2

Using explicit wait/implicit wait is the best practice, Lets check what actually the explicit wait,Thread.sleep(), Implicit wait's working logic

Explicit wait: An explicit waits is a kind of wait for a certain condition to occur before proceeding further in the code.

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

Thread.sleep() In sleep code will always wait for mentioned seconds in side the parentheses even in case working page is ready after 1 sec. So this can slow the tests.

Solution 3

Using Explicit wait is suggested for waiting to perform any action on webelement instead of Thread.sleep() as best practice.

Explicit wait in Selenium is equivalent to Thread.sleep() with a specified condition. That means even if you used either Explicit or Implicit wait, you indirectly used Thread.sleep(). The difference is that you specify the conditions for your wait and know when to throw error if your wait is timeout.

If you know the exact time for your wait Thread.sleep() can be used but better avoid using it. You test may slow down if your wait time is more and may fail if your wait time is less.

Share:
24,491
Jugi
Author by

Jugi

Updated on July 09, 2022

Comments

  • Jugi
    Jugi almost 2 years

    I am new to web driver and I wrote a selenium script for web application which contains backbone.js and select2.

    I used to get NosuchElementException and Element is not clickable exceptions often. So I have decided to script as below, - before clicking on any element, it will wait for existence of element using explicit wait. i.e before clicking any element , it will wait until the element is loaded.

    Is it best practice to wait for each element before clicking?