How could I mock bad ajax request and test

124 views
Skip to first unread message

yuxuan

unread,
Mar 25, 2013, 11:26:05 AM3/25/13
to js-test...@googlegroups.com
Hi guys,

I would like to mock a bad status response using mockjax and test the response handler works well or not.

My test code is 

AsyncTestCase("anotherMock"

    "test fail status" : function (queue) {

        queue.call("step 1 setup mockjax", function (callbacks){

            $.mockjax({
                url:'/mocktest',
                status : 400,
                responseTime:1,
                responseText : "im wrong!" 
            });
        });

        queue.call("step 2 ajax fail test" , function (callbacks) {
            
            var successResponse = callbacks.add(function (data) {
                fail('i should not in success!');

            });     

            var errorResponse = callbacks.add(function (xhr) {

                jstestdriver.console.log(xhr.status);
                jstestdriver.console.log(xhr.responseText);
  
                assertEquals("error repsonseText test", "im wrong!", xhr.responseText);


            });

            $.ajax({
                url:'/mocktest',
                async : true,
                cache : false,
                timeout: 1000,
                dataType:'json',
                success: successResponse,
                error:errorResponse

            });
        });

        queue.call("setp 3 clean mockjax", function (callbacks) {
            jstestdriver.console.log('inside clean');

                $.mockjaxClear();

        });
    }
});

I used mockjax to set up 400 status, and expected errorResponse to handle it. However, the test result gave me callback expired. But I can see the Log shows out my mockjax setting is right, I got 400 status and correct responseText.

I did a mock success ajax test as well. It is 

AsyncTestCase("testMock", {

    "test mock": function (queue) {

        expectAsserts(1);

        queue.call("expecting a callback", function(callbacks){

            $.mockjax({
                url: "/mocktest",
                status: 200,
                responseTime: 1,
                responseText: {'hello': 'world'}
            });

            var handler = callbacks.add(function (data) {
                assertEquals("world", data.hello);


            });

            $.getJSON("/mocktest", null, handler);

            $.mockjaxClear();

        });

    }
});

This one works correctly, and the request is not expired.

Could I mock a bad response and using jstestdriver to test the response? Or are there any other ways to do that?

Thanks!
Reply all
Reply to author
Forward
0 new messages