How can I get selenium to wait for something like a calendar widget to load? Right now I am just doing a Thread.sleep(2500)
after exporting the testcase to a junit program.
Moreover, the JavaScript Executor can be used to wait for an Ajax call. The executeScript method is used to run a JavaScript command in Selenium. The waiting is done till jQuery. active command yields 0.
Cut and paste whatever code you need to execute in the callback function passed to success . Some good answer is already provided.
AJAX sends HTTP requests from the client to server and then process the server's response without reloading the entire page. To handle AJAX controls, wait commands may not work. It's just because the actual page is not going to refresh.
For that, Selenium Webdriver has to use the wait method on this Ajax Call. So by executing this wait command, selenium will suspend the execution of current Test Case and wait for the expected or new value. When the new value or field appears, the suspended test cases will get executed by Selenium Webdriver.
I would use
waitForElementPresent(locator)
This will wait until the element is present in the DOM.
If you need to check the element is visible, you may be better using
waitForElementHeight(locator)
A more general solution than waiting for an element would be to wait for all the connections to the server to close. This will allow you to wait for all ajax calls to finish, even if they don't have any callback and thus don't affect the page. More details can be found here.
Using C# and jQuery, I have created the following method to wait for all AJax calls to complete (if anyone have more direct ways of accessing JS variables from C#, please comment):
internal void WaitForAjax(int timeOut = 15) { var value = ""; RepeatUntil( () => value = GetJavascriptValue("jQuery.active"), () => value == "0", "Ajax calls did not complete before timeout" ); } internal void RepeatUntil(Action repeat, Func<bool> until, string errorMessage, int timeout = 15) { var end = DateTime.Now + TimeSpan.FromSeconds(timeout); var complete = false; while (DateTime.Now < end) { repeat(); try { if (until()) { complete = true; break; } } catch (Exception) { } Thread.Sleep(500); } if (!complete) throw new TimeoutException(errorMessage); } internal string GetJavascriptValue(string variableName) { var id = Guid.NewGuid().ToString(); _selenium.RunScript(String.Format(@"window.$('body').append(""<input type='text' value='""+{0}+""' id='{1}'/>"");", variableName, id)); return _selenium.GetValue(id); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With