if selenium script run faster than code which we want to test, it could happen that can’t find element. there are some ways to handle this problem depends on different cases
- Sleep
This is the easiest but inefficient way. It mean wait fixed time , then try again. Usually we don’t use this way since it depends on the load time and it is not efficient.
public static void Wait(int miniseconds) { Thread.Sleep(miniseconds); }
- WebDriverWait
This Method can resolve most of cases if there is no ajax load. Code wait until one element is present.
private static void WaitElement(By by, double seconds) { try { var wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(seconds)) { Message = @by.ToString() + " is not exist" }; wait.Until((d) => d.FindElement(@by)); } catch(Exception e) { GetScreenShot(e); } }
- AjaxWait
Below method is generally assert that if ajax call finished.
public static void WaitForAjaxCallFinish() { WaitForConditions("return window.jQuery.active == 0"); } public static void WaitForConditions(string script) { var wait = new DefaultWait<bool>(((bool)((IJavaScriptExecutor)Driver).ExecuteScript(script) == true)) { Timeout = TimeSpan.FromSeconds(_stepTimeout) }; }
- But no jquery connection doesn’t mean expected element is present. so the below method is the way to finnaly resolve wait problem.
// try to find element every 5 seconds, until element is exist or it's time out. public static IWebElement GetElementUntilPresent(By by) { for (int i = 0; i < _stepTimeout; i = i + 5) { try { return Driver.FindElement(by); } catch (Exception e) { Wait(5000); } } return null; }
- Sometimes we get test case fail with below message
The HTTP request to the remote WebDriver server for URL http://localhost:13915/session/01ab4ef8075bba3d64e8fc3062aa79b5/element timed out after 60 seconds.
I try : 1. set page time out
private static void OpenBrowser(string pageTitle) { Driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromMinutes(_pagetimeout)); Driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromMinutes(_pagetimeout)); Driver.Navigate().GoToUrl(WebsiteUrl); }