javascript - How do I mock a 'timeout' or 'failure' response using Sinon / Qunit? -


i've had no problems sorting out mocking success condition, cannot seem fathom how mock failure / timeout conditions when using sinon , qunit test , ajax function:

my set this:

$(document).ready( function() {      module( "mytests", {         setup: function() {             xhr = sinon.sandbox.usefakexmlhttprequest();             xhr.requests = [];             xhr.oncreate = function (request) {                 xhr.requests.push(request);             };              myobj = new myobj("#elemselector");         },         teardown: function() {             myobj.destroy();             xhr.restore();         }     }); 

and success case test, running happily , receiving / passing through received data success method this:

    test( "the data fetch method reacts correctly receiving data", function () {         sinon.spy(myobject.prototype, "ajaxsuccess");          myobject.prototype.fetchdata();          //check call got heard         equal(1, xhr.requests.length);          //return success method obj         xhr.requests[0].respond(200, { "content-type": "application/json" },                 '[{ "responsedata": "some test data" }]');          //check correct success method called         ok(myobj.prototype.ajaxsuccess.calledonce);          myobj.prototype.ajaxsuccess.restore();     }); 

however, cannot work out should putting instead of this:

        xhr.requests[0].respond(200, { "content-type": "application/json" },                 '[{ "responsedata": "some test data" }]'); 

to make ajax call handler 'hear' failure or timeout method? thing think try this:

        xhr.requests[0].respond(408); 

but doesn't work.

what doing wrong or have misunderstood? appreciated :)

doing this

requests[0].respond(         404,         {             'content-type': 'text/plain',             'content-length': 14         },         'file not found' ); 

works trigger 'error' callback in jquery ajax requests.

as timouts, can use sinons fake clock this:

test('timeout-test', function() {     var clock = sinon.usefaketimers();     var errorcallback = sinon.spy();      jquery.ajax({         url: '/foobar.php',         data: 'some data',         error: errorcallback,         timeout: 20000 // 20 seconds     });      // advance 19 seconds in time     clock.tick(19000);      strictequal(errorcallback.callcount, 0, 'error callback not called before timeout');      // advance 2 seconds in time     clock.tick(2000);      strictequal(errorcallback.callcount, 1, 'error callback called once after timeout'); }); 

Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -