How to use waits in selenium webdriver using c#? I have been asked not to use the foolowing statement by my test manager.
System.Threading.Thread.Sleep(6000);
How to use waits in selenium webdriver using c#? I have been asked not to use the foolowing statement by my test manager.
System.Threading.Thread.Sleep(6000);
It is generally a bad idea to use thread.sleep in UI tests, mostly because what if the web server was just going slower for some reason and it took longer than 6000ms to load that page. Then the test will fail with a false negative. Generally what we use in our tests is the wait for methods in selenium, the documentation can be found at http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp basically the idea is you "wait for" a particular element that you expect to be on the page. By doing this you don't have to manually wait 6000ms when in reality the page took 100ms to load the element that your expecting, so now it only waited for 100ms instead of 6000ms.
Below is some code that we use to wait for an element to appear:
public static void WaitForElementNotPresent(this ISearchContext driver, By locator)
{
driver.TimerLoop(() => driver.FindElement(locator).Displayed, true, "Timeout: Element did not go away at: " + locator);
}
public static void WaitForElementToAppear(this ISearchContext driver, By locator)
{
driver.TimerLoop(() => driver.FindElement(locator).Displayed, false, "Timeout: Element not visible at: " + locator);
}
public static void TimerLoop(this ISearchContext driver, Func<bool> isComplete, bool exceptionCompleteResult, string timeoutMsg)
{
const int timeoutinteger = 10;
for (int second = 0; ; second++)
{
try
{
if (isComplete())
return;
if (second >= timeoutinteger)
throw new TimeoutException(timeoutMsg);
}
catch (Exception ex)
{
if (exceptionCompleteResult)
return;
if (second >= timeoutinteger)
throw new TimeoutException(timeoutMsg, ex);
}
Thread.Sleep(100);
}
}
In cases where you do need to wait, the Task.Delay method will provide more predictable results
Task.Delay(1000).Wait(); // Wait 1 second
There is also a trick in Selenium (I am using version 4, not sure if this is in earlier version), but in case you do an action and want to wait for x amount of time till that action is done. For example when you login to system it might take some time.
The solution for that is:
new WebDriverWait(driver, TimeSpan.FromSeconds(5))
.Until(d => d.FindElement(By.Id("success_page")).Displayed);