Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test ajax error callback?

Within an ajax request how can the error callback be tested ? Is it possible to simulate a network connection error ?

    $.ajax({
        url: "myUrl",       
        type: 'post',
        dataType : "json",
        data : ({
            myJson
        }),
        success : function(jsonSaveResponse) {  

        },
        error: function (xhr) {

    } 

    }); 
like image 230
blue-sky Avatar asked Sep 17 '12 08:09

blue-sky


3 Answers

What I do is just turn my server off before I make the AJAX request, which will simulate the server not responding.

Remember it'll need to be switched back on before you can refresh for changes.

like image 145
Mild Fuzz Avatar answered Nov 16 '22 00:11

Mild Fuzz


You have to stub the ajax request, and return a custom response that will trigger the error callback. You can do this easily with Javascript testing frameworks such as Jasmine.

like image 38
gerky Avatar answered Nov 16 '22 01:11

gerky


If your URL is a PHP page, you can do something like this:

<?php
    header("HTTP/1.0 404 Not Found");
    exit();
    //the rest of your code

You can simply comment it out later when you're done testing your error function.

like image 32
ObiHill Avatar answered Nov 15 '22 23:11

ObiHill