HTML and CSS Reference
In-Depth Information
var url = "/url";
ajax.get(url);
assertEquals(["GET", url, true], this.xhr.open.args);
}
});
Much better. Re-running the tests confirm that they now all pass. Moving for-
ward, we can add stubs to the
fakeXMLHttpRequest
object as we see fit, which
will make testing
ajax.get
significantly simpler.
12.4.2.4 Feature Detection and
ajax.create
ajax.get
now relies on the
ajax.create
method, which is not available in the
case that the browser does not support the
XMLHttpRequest
object. To make sure
we don't provide an
ajax.get
method that has no way of retrieving a transport,
we will define this method conditionally as well. Listing 12.27 shows the required
test.
Listing 12.27
Bailing out if
ajax.create
is not available
(function () {
var ajax = tddjs.namespace("ajax");
if (!ajax.create) {
return;
}
function get(url) {
/* ... */
}
ajax.get = get;
}());
With this test in place, clients using the
ajax.get
method can add a similar
test to check for its existence before using it. Layering feature detection this way
makes it manageable to decide what features are available in a given environment.
12.4.3 Handling State Changes
Next up, the
XMLHttpRequest
object needs to have its
onreadystatechange
handler set to a function, as Listing 12.28 shows.