I have a function using jQuery like so:
function populate_messages_node() {
$.ajax({url: "/messages", type: "GET", success: populate_recent_messages});
}
I want to write an integration test for this function. My problem is that the test:
function test_simple() {
populate_messages_node();
// assert node content here
}
… will not wait for the Ajax success method (populate_recent_messages) to do its stuff. For this trivial example, doing $.ajaxSetup({async:false}) works, but I fear that will not always be true. There will be a large number of such tests for scenarios more complicated for this.
I guess my question really is: is there no way to wait on completion of XHR/Websocket operations in Javascript?
I would prefer not to modify production code (populate_messages_node), but returning the xhr result from .ajax() is prolly OK. (I apologize in advance for not having found the canonical SO post that surely describes exactly this problem.)
You could return the deferred object from
populate_message_node()then hook to the complete event as follows.