How to test ajax error callback?
Asked Answered
F

4

18

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) {

    } 

    }); 
Fiord answered 17/9, 2012 at 8:49 Comment(3)
Are you implementing plain AJAX or it's using jQuery ?Dumond
feed the xmlhttprequest object with a false url (something like mydomain.com/thisurldoesntexist)Affection
@KPBird please see question edit, im using jQueryFiord
C
21

You could simply put an incorrect URL into the URL attribute of the AJAX call.

Civilize answered 17/9, 2012 at 9:43 Comment(4)
This is not working for me! I have typed url : "asdjasfd.php" inside my $.ajax() function! and I have set error : function(jqXHR, textStatus, errorThrown){ alert(testStatus); }, inside the $.ajax() function! I don't see any Javascript alert!Valuer
Nothing... I use chrome, and the AJAX request just goes seamlessly.. I have also added an alert for success : function(data, textStatus, jQxhr). Even this alert I did not get. Rightnow, for the correct url, I get success as the alert message!Valuer
If you see nothing in your network panel, you Xhr request is not happening.Civilize
To emulate error on the server write smth like: header("HTTP/1.0 404 Not Found"); exit; - in such case error section of your js code will workPersis
C
3

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.

Civilize answered 17/9, 2012 at 8:51 Comment(0)
D
1

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.

Disarmament answered 17/9, 2012 at 8:54 Comment(0)
S
1

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.

Shea answered 13/5, 2016 at 16:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.