Phil,
I may be a bit of a heretic around here, but I use sinon.js for
mocking my ajax requests (sync and async) for similar reasons -- I can
tell it to respond serially without needing to use things like waits,
which I think make the tests harder to read.
I typically have something like this:
var server;
beforeEach(function(){
server = sinon.useFakeServer();
server.respondWith("GET", "/someUrl.json",
[200, { "Content-Type": "application/json" }, someJsonString]
);
});
afterEach(function(){
server.restore();
});
describe("someAsyncMethod", function(){
it("should load data asynchronously", function(){
var cb = jasmine.createSpy();
someAsyncMethodWhichInvokesCbOnCompetion(cb);
expect(cb).not.toHaveBeenCalled();
server.respond();
expect(cb).toHaveBeenCalledWith(someJsonString);
});
});
describe("someSyncMethod", function(){
it("should load data synchronously", function(){
var data = someSyncMethod();
expect(data).toEqual(someJsonString);
});
});
Note that in the second instance, I did not need to use server.respond
-- that is because sinon.js honors the async parameter of
XmlHttpRequest.open and immediately responds if appropriate, rather
than waiting for server.respond() to be called.
Using sinon in this way to test both my sync and async XHR has been
very nice, and my tests all feel very readable.
- Ben