With jQuery, you can use the xhr object that .ajax()
returns as a promise, so you can add more handlers (see below) than just the single success
, complete
and error
tags that you define in the options. Therefore, if your async function can return an xhr object, you can add test-specific handlers.
As for the URL, this is a little trickier. I sometimes set up a very simple Node server on localhost, which simply serves up saved responses that were copied from a real server. If you run the test package from the same server, your URLs must be absolute paths to get to the test server instead of the production server. And you also get a record of the requests themselves, as the server sees them. Or you can have a test server to send back errors or bad answers with a goal if you want to see how the code handles it.
But this, of course, is a rather complicated decision. It would be easier to identify your URLs in a place where you can redefine them from a test suite. For instance:
var X = function () { this.fire = function () { return $.ajax({ url: this.constructor.url, ... }); }; }; X.url = "someURL.php";
In addition, QUnit has an asyncTest
function that calls stop()
for you. Add a tiny helper to keep track of when to start again, and you have a pretty good solution.
Here is what I did before
Basically, countDown
is a function that counts down to zero from what you specified, and then calls start()
. In this case, one asynchronous call, so countDown
will count from this. And this will be done when the ajax call completes, no matter how it happened, as it is configured as an always
callback.
And since asyncTest
told to expect 2 statements, it will report an error if the .done()
never called, since there will be no statements. Therefore, if the call fails completely, you will know it too. If you want to register something on error, you can add the .fail()
to the promise chain.