Selenium, jQuery and pending ajax requests

We use selenium extensively at work for automated acceptance tests. If you’ve never used selenium, it allows you to record and playback browser sessions and create integration tests from the perspective of a browser. Its generally a great tool, and really helps make sure we don’t release broken code. Recently, however I’ve found Selenium can have adverse reactions with jQuery.ajax.

A growing number of FreshBooks are created client side with a considerable amount of ajax. There are a number of calls that should never fail, but we include error cases in the rare event that a customer’s network connection fails, or our servers are too busy. For example:

Show Plain Text
  1. var xhr = jQuery.ajax({
  2.     url: '/client/get/' + clientid,
  3.     dataType: 'json'
  4. });
  5. xhr.done(function (resp) {
  6.     // good things.
  7. }).fail(function (xhr) {
  8.     alert('We were not able to fetch your client, try again in a moment.');
  9. });

jQuery.ajax only allows binding a success and error callback The error callback is called in every error state including an aborted request. Normally aborted requests don’t happen. Normal users aren’t fast enough to end up with aborted requests. However, selenium is more than capable of performing actions faster than requests can complete. This resulted in a number of our automated selenium tests failing with unexpected alert calls. After some digging, I figured out the root cause was aborted requests. My solution to this problem was to ignore aborted requests, as they are not failures we really need to worry about.

Show Plain Text
  1. var xhr = jQuery.ajax({
  2.     url: '/client/get/' + clientid,
  3.     dataType: 'json'
  4. });
  5. xhr.done(function (resp) {
  6.     // good things.
  7. }).fail(function (xhr) {
  8.     // Aborted request
  9.     if (xhr.status === 0) {
  10.         return;
  11.     }
  12.     alert('We were not able to fetch your client, try again in a moment.');
  13. });

By ignoring aborted requests, selenium can continue moving faster than any human and not hit any potholes. Hopefully this saves you some hair pulling if you use selenium.

Comments

We also recently started to adapt Selenium into our testing-workflow, so this will come in as a handy bookmark for the near future!

Many thanks.

Hyra on 3/4/12

Comments are not open at this time.