Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've had no problems sorting out mocking the success condition, but cannot seem to fathom how to mock the failure/timeout conditions when using Sinon and Qunit to test and ajax function:

My set up is 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 my success case test, running happily and receiving/passing through the received data to the success method is this:

test("The data fetch method reacts correctly to receiving data",
    function () {
        sinon.spy(MyObject.prototype, "ajaxSuccess");

        MyObject.prototype.fetchData();

        //check a call got heard
        equal(1, xhr.requests.length);

        //return a success method for that obj
        xhr.requests[0].respond(200, {
                "Content-Type": "application/json"
            },
            '[{ "responseData": "some test data" }]'
        );
        //check the correct success method was called
        ok(MyObj.prototype.ajaxSuccess.calledOnce);

        MyObj.prototype.ajaxSuccess.restore();
    }
);

However, I cannot work out what I should be putting instead of this:

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

to make my ajax call handler hear a failure or timeout method? The only thing I could think to try was this:

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

But it doesn't work.

What am I doing wrong or what have I misunderstood? All help much appreciated :)

like image 733
Caroline Avatar asked Sep 07 '25 11:09

Caroline


1 Answers

For the timeout, sinon’s fake timers could help. Using them you wouldn’t need to set the timeout to 1ms. As for the failures, your approach looks correct to me. Can you give us more code, especially the failure handler?

like image 134
Adrian Heine Avatar answered Sep 08 '25 23:09

Adrian Heine