Skip to content Skip to sidebar Skip to footer

Any Better Way Than Settimeout To Wait For Asnyc Callbacks When Testing Javascript?

Given this code: showForm = function (url) { return $.get(url, function (html) { $('body').append(); }); }; When using sinon.js, jQuery

Solution 1:

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);
    });
});

Solution 2:

You should use sinons fakeServer. This will call your ajax callback immediately, when the $.ajax call was made. See this jsFiddle

before(function(){
  var server = sinon.fakeServer.create();
  server.respondWith('response');
})

it("showForm calls jQuery.append", function () {
    var spy = sinon.spy($.fn, "append");             
    presenter.showForm('/fake');
    server.respond();
    expect(spy.called).to.be.equal(true);
});

Solution 3:

Use $.doTimeout plugin

Check the following documentation.

http://benalman.com/projects/jquery-dotimeout-plugin/

Hope this helps

Post a Comment for "Any Better Way Than Settimeout To Wait For Asnyc Callbacks When Testing Javascript?"