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

Jugi picture Jugi · Jun 22, 2015 · Viewed 22.4k times · Source

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?

Answer

nilesh picture nilesh · Jun 22, 2015

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');