HTML and CSS Reference
In-Depth Information
Listing 13.16 Expecting a new request to be scheduled upon completion
"test should schedule new request when complete":
function () {
var poller = Object.create(ajax.poller);
poller.url = "/url";
poller.start();
this.xhr.complete();
this.xhr.send = stubFn();
Clock.tick(1000);
assert(this.xhr.send.called);
}
The second stub deserves a little explanation. The ajax.request method
used by the poller creates a new XMLHttpRequest object on each request. How
can we expect that simply redefining the send method on the fake instance will
be sufficient? The trick is the ajax.create stub—it will be called once for each
request, but it always returns the same instance within a single test, which is why
this works. In order for the final assert in the above test to succeed, the poller needs
to fire a new request asynchronously after the original request finished.
To implement this we need to schedule a new request from within the com-
plete callback, as seen in Listing 13.17.
Listing 13.17 Scheduling a new request
function start() {
if (!this.url) {
throw new TypeError("Must specify URL to poll");
}
var poller = this;
ajax.request(this.url, {
complete: function () {
setTimeout(function () {
poller.start();
}, 1000);
}
});
}
 
Search WWH ::




Custom Search