Dealing with Ajax asynchronous request and the elements Rendering

Currently I’m adding several test to validate that TeamMentor’s search functionality worked as expected. I added some test to confirm that the search results were correct based on the search pattern.

Since TeamMentor rely on Ajax and I’m trying to avoid the nasty Thread.Sleep() method, I’ve create the following method to determine if the Ajax request has finished.

public static void waitForAjax(this IWebDriver driver )
{
 while (true) // Handle timeout somewhere
 {
 var javaScriptExecutor = driver as IJavaScriptExecutor;
 var ajaxIsComplete = javaScriptExecutor != null
 && (bool)javaScriptExecutor.ExecuteScript("return jQuery.active == 0");
 if (ajaxIsComplete)
 break;
 Thread.Sleep(200);
 }
}

In this code example I’m also using Thread.Sleep(), but  the conditions are quite different because the main feature here is to determine if the Ajax request is done.

For some reason when this method returns true (which means that the request is done) and at the time of accessing Elements, the DOM changes performed by the Ajax requests (i.e label text changes) have not been rendered and it causes that the test fails.

It seems like there is a race condition to deal with.  If you look at the TeamCity report, then it seems like the expected condition was false because the search results have not been undated yet.

Image
TeamCity report

The problem here is that right after the Ajax request is done, WebDriver finds the elements which haven’t updated by the request and therefore the DOM is out of date. This is the reason why the Thread.Sleep(200) works fine, because that is the exact time required by the action to update the  DOM.

What to do now?

Some people say that understanding the problem it’s a 50% of the solution :). So one possible or temporary solution would be leave the Thread.Sleep method with a pretty short time less than two seconds.

I will spend some time researching about it and what would be the next course of action to address it.

Advertisements

About Michael Hidalgo

Michael is a Software Developer Engineer based on San José, Costa Rica. He leads the OWASP Chapter from Costa Rica. You can take a look at my blog at http://blog.michaelhidalgo.info/
This entry was posted in Browser Automation, JQuery, Selenium WebDriver, WebDriver and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s