Getting Selenium to wait for Ajax

In our application, we have a page that regenerates most of a certain page using Ajax that was a bit of a headache to test with Selenium.

The data that we pulled for the page was tested elsewhere but there was some non-trivial Ajax that we wanted to test. In much of our research, “people” test for the existence of elements or text on the page in a selenium.waitForCondition(). In our case however, the data may change and the elements are basically the same before and after. Also we wanted some solution that would work without having to tailor it to every single page; we just wanted to wait for Ajax to complete any pending requests before continuing with the test.

We (i.e. Michael Buckley) found a way to have Selenium wait for all in-flight Ajax requests to finish processing:

protected void waitForAjax() throws InterruptedException {
		selenium.waitForCondition("selenium.browserbot.getCurrentWindow() == 0;", DEFAULT_WAIT_PERIOD);

If you’re using something other than Dojo, (Prototype?), it may look something like this:

protected void waitForAjax() throws InterruptedException {
		selenium.waitForCondition("selenium.browserbot.getCurrentWindow().Ajax.activeRequestCount == 0;", DEFAULT_WAIT_PERIOD);

Also, if you’re using components that use multiple frameworks, you may need to test that all the in-progress Ajax requests are 0. Some related tips here: Integration Testing using Selenium

It's only fair to share...
Share on Facebook
Tweet about this on Twitter
Share on LinkedIn

Leave a Reply