Reputation: 569
I have a project I'm working on using Cucumber/Selenium for front end testing. I have been told to use WebDriverWait instead of Thread.sleep()
to complete the testing. However, in this case I am not looking for an expected condition. I literally need the test to pause while the page loads. If it searches for the xPath before waiting, it will click on the first item in a search and proceed to test the wrong things.
Upvotes: 2
Views: 494
Reputation: 2760
Use following method with Java + Selenium :
public boolean isPageReady(WebDriver driver){
boolean readyStateComplete = false;
while (!readyStateComplete){
JavascriptExecutor executor = (JavascriptExecutor) driver;
readyStateComplete = executor.executeScript("return document.readyState").equals("complete");
}
return readyStateComplete;
}
For C# + Selenium :
private void WaitUntilDocumentIsReady(TimeSpan timeout){
var javaScriptExecutor = WebDriver as IJavaScriptExecutor;
var wait = new WebDriverWait(WebDriver, timeout);
// Check if document is ready
Func<IWebDriver, bool> readyCondition = webDriver => javaScriptExecutor
.ExecuteScript("return (document.readyState == 'complete' && jQuery.active == 0)");
wait.Until(readyCondition);
}
Upvotes: 1
Reputation: 530
Why you need to pause tour test?
If you need to wait untli element will be visible use: new WebDriverWait(WebDriver driver, String timeToWait).until(ExpectedConditions.visibilityOf(WebElement element));
If you need to wait untli element will be clickable use: new WebDriverWait(WebDriver driver, String timeToWait).until(ExpectedConditions.elementToBeClickable(WebElement element));
If you need to wait untli element will be present on the DOM use: webDriver.manage().timeouts().implicitlyWait(String timeToWait, TimeUnit.SECONDS);
Using Thread.sleep() or pause your test for a indicated time is a bad practise.
Upvotes: 2
Reputation: 193108
If you intend to use WebDriverWait without using any ExpectedConditions while you need the test to pause while the page loads you can also use Java lambda
expression as follows:
new WebDriverWait(driver, 20)
.until(d -> ((JavascriptExecutor)d).executeScript("return document.readyState")
.equals("complete"));
Upvotes: 1