Tuesday, July 12, 2011

How to Make Selenium Wait for Ajax Calls

I needed to be able to wait for Selenium to complete an Ajax call before checking the effects.  After looking at many different solutions, I came up with this one.

Add a hidden field to the master page to store the number of Ajax requests that have been done.
<input type="hidden" id="NumAjaxRequests" value="0" />
Hook into the jQuery Ajax framework to automatically increment the field for each request that completes.
$('.ajaxindicator').ajaxStop(function ()
{
    $('#NumAjaxRequests').val(parseInt($('#NumAjaxRequests').val() + 1));
});
You can then reset the field before performing the action that causes the Ajax call, perform that action and tell Selenium to wait until the expected number of Ajax calls have taken place.
| type         | NumAjaxRequests | 0                 |
| select       | Mb_SpouseId     | label=Spouse Name |
| waitForValue | NumAjaxRequests | 1                 |

2 comments:

  1. Why not just use a deferred - unless I'm missing the point?

    $.when(
    $.post("/controller/method1",
    $.postify(postData1)),
        $.post("/controller/method2",
    $.postify(postData2)))
    .done(function (a1, a2) {
       //a1 and a2 are the results of the data calls
    })
    .fail( NotifyFailure);

    ReplyDelete
  2. Selenium is a test automation framework. In this case I'm automating the clicking of a button and behind the button is a lot of JavaScript that among other things do some Ajax calls.

    What I need to be able to do is click the button and then wait until a certain number of Ajax call have taken place, but I don't have any control over the thing doing the actual calls at that point.

    ReplyDelete