问题
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?
回答1:
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.
回答2:
It seems that nobody cares about mockAjax, so I found something better these days: sinonJS ! Do you know the feature autoResponse of this wonderful tool named Fiddler? sinonJS allows you to do the same on the client side, it's a kind of ajax by-pass proxy. if you are interested to see an example, let me know... so sinonJS can respond to any ajax request without accessing the server, that's kind of magic if you want to mock your client, if you want to unit test your javascript code.
来源:https://stackoverflow.com/questions/15673578/testing-for-a-function-that-contains-asynchronous-code