Do you know WebDriverWait in Selenium?
When do we use WebDriverWait in Selenium?
Interviewer: Do you know , What is WebdriverWait and when to use it?
Candidate: Yes Sir. I know it. WebDriverWait is an explicit wait in selenium. We use it for synchronization in automation.
Interviewer: What do you mean synchronization in this context?
Candidate: The different web applications take some time to load properly and every automation tool has some speed to act on the objects of the application. So both the automation tool(e.g. Selenium WebDriver API) and the application under test should be in sync with each other to avoid failures in test scripts.
Interviewer: Okay . Now lets’s get back to WebdriverWait. What exactly it is and how you use it?
Candidate: WebDriverWait is a kind of wait for a certain condition to occur before proceeding further in the test code . WebDriverWait in combination with ExpectedCondition is used.
Interviewer: Sounds good. Please elaborate more.
Candidate: There are some common conditions that are frequently encountered when automating web browsers. For example:
it means, my test script will wait till the application loads properly and when any web button / webtable etc. has loaded properly and now it can be clicked (elementToBeClickable) . This way we make selenium webdriver to wait for certain condition and then allow it to perform operations.
Interviewer: Could you please write the sample code for it?
Candidate: Sure. The code is as follows:
WebDriver driver = new FirefoxDriver(); driver.get("URL of the application"); WebElement slowLoadingElement = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.presenceOfElementLocated(By.id("slowLoadingElement")));
Another similar code with different expected conditions is given below:
WebElement slowLoadingElement = (new WebDriverWait(driver, 10)).until(ExpectedConditions.elementToBeClickable(By.id("slowLoadingElement")));
Here in this, we are creating the object of WebDriverWait and passing the driver and timeout as parameters and we are waiting until the given condition is not true for a given WebElement.