With qUnit, I understand how to use asyncTest()
if you have asynchronous code within your tests, but what if you have a function that contains asynchronous code?
In other words, the asynchronous request is not within the test, but is simply part of the code that is being tested.
Take this code for example:
function makeAjaxCall(){
$.get('/mypage', {}, function(data){
// Do something with `data`
},'json');
}
How can I call makeAjaxCall()
within a test and then run tests on the data
that is returned from the ajax request?
You could use the jQuery Global Ajax Event Handlers in this situation. Bind it before calling, unbind it once you finish the test, possibly via the module method in Qunit.
Something like (untested):
asyncTest(function() {
expect(1);
$(document).ajaxSuccess(function(e, xhr, settings) {
var jsonRep = JSON.parse(xhr.responseText);
// assert on jsonRep
//ok(true);
});
$(document).ajaxError(function(e) {
ok(false);
});
$(document).ajaxComplete(function() {
start();
$(document).unbind('ajaxSuccess ajaxError ajaxComplete');
});
makeAjaxCall();
});
Note that the global handlers do not have access to the parsed contents, and you have to reparse them yourself using JSON.parse. Not ideal, but I don't know of another way.