I'm testing my frontend code using qunit and mockjax. The structure of AJAX tests in mockjax's own test code looks like this (jsfiddle):
var testURL = "/test/data",
testData = { a: 1, b: "c" };
asyncTest("AJAX response test", 1, function() {
$.mockjax({
url: testURL,
responseText : JSON.stringify(testData)
});
$.ajax({
url: testURL,
dataType: "json",
success: function(data) {
deepEqual(data, testData, 'AJAX response is OK');
},
complete: function() {
start();
}
});
$.mockjaxClear();
});
According to the mockjax documentation:
* $.mockjaxClear()
Removes all mockjax handlers.
What I don't understand is why mockjaxClear
is called right after the $.ajax()
call. The problem is if it does some sort of cleanup, as the documentation says, this cleanup will run before the AJAX response arrives (pls. see the console of this jsfiddle). It seems more logical for me to do the cleanup in the handler of the complete
event. Can anyone explain me why it is better to call mockjaxClear after $.ajax()
?
If you take a look at the code, you will see that the cleanup does not affect already "running" calls. It just makes sure that any subsequent
$.ajax()
will call jQuery's original method and that other internal state (but again, not affecting already pending "requests") is cleaned.This may help to ensure that the
$.ajax()
call under test test is only sent once (if more are sent they will fail, moreover thestart()
method will be called again, reporting the error to Qunit).It could also be this way just to keep code clean (less stuff in the callback handlers).