Any better way than setTimeout to wait for asnyc callbacks when testing JavaScript?

javascript, jquery, sinon

Solution

Pass your anonymous function to show form as a parameter and have it called in the callback after the append. To ensure its called you could make it an $.ajax request that covers the error callback as well.

This way it is called exactly when the get request finishes with no excess time or called too early.

showForm = function (url, callback) {
        return $.get(url, function (html) {
             $('body').append();   
             if(callback != undefined)
             callback();
        });
 };

it("showForm calls jQuery.append", function () {

    $.mockjax({
          url: '/fake'                    
    });

    var spy = sinon.spy($.fn, "append");

    presenter.showForm('/fake', function (){ 
        expect(spy.called).to.be.equal(true);
    });
});

Problem

Given this code: ``` showForm = function (url) { return $.get(url, function (html) { $('body').append(); }); }; ``` When using `sinon.js`, `jQuery.mockjax.js` and `expect.js`, I have the following passing test: ``` it("showForm calls jQuery.append", function () { $.mockjax({ url: '/fake' }); var spy = sinon.spy($.fn, "append"); presenter.showForm('/fake'); setTimeout(function () { expect(spy.called).to.be.equal(true); }, 1000); }); ``` Using the `setTimeout` function to wait on the callback from the asynchronous `$.get` smells bad and it will slow down my test suite if I do too much of it. However, I feel that the intent is reasonably clear and it does seem to test exactly what I want. Is there a better way and can you please explain what's going on in your answer?

Original source