[QUnit] How to test nested asynchronous function calls?
I'd like to test the following code to make sure:
1. setTimeout calls the function
2. ajax success callback is called
setTimeout(function() {
$.ajax({
url: './index.html',
success: function() {}
})
}, 100);
If I only have one nested asynchronous test like this, it works:
asyncTest('asyncTest', function() {
setTimeout(function() {
console.log(1);
ok(true, 'success');
start();
asyncTest('nested asyncTest', function() {
$.ajax({
url: './index.html',
success: function() {
console.log(2);
ok(true, 'ajax success');
start();
}
})
})
}, 100)
})
But if there are multiple tests, it works, but run out of order:
asyncTest('asyncTest', function() {
setTimeout(function() {
console.log(1);
ok(true, 'success');
start();
asyncTest('nested asyncTest', function() {
$.ajax({
url: './index.html',
success: function() {
console.log(2);
ok(true, 'ajax success');
start();
}
})
})
}, 100)
})
asyncTest('another asyncTest', function() {
setTimeout(function() {
console.log(3);
ok(true, 'another success');
start();
asyncTest('another nested asyncTest', function() {
$.ajax({
url: './index.html',
success: function() {
console.log(4);
ok(true, 'another ajax success');
start();
}
})
})
}, 100)
})
If you open firebug, you can see the order is "1,3,2,4", which can
cause disasters.
The real world problem is that I use setInterval to periodically check
location.hash to implement a cross-browser "onhashchange" event, and I
bind a function to this event, when the function gets called, it will
make an ajax call. I set a different value to location.hash in every
test to trigger the event, which is actually asynchronous. So how do I
use qunit to test this code?