user1032531
user1032531

Reputation: 26301

How to mock an ajax response

How can one mock an ajax response?

https://stackoverflow.com/a/13915248/1032531 provides a link to an answer but the link is broken.

https://stackoverflow.com/a/29680013/1032531 provides the following answer but it errors with $.ajax is not a function. https://jsfiddle.net/bdw0gfan/

 function ajax_response(response) {
   var deferred = $.Deferred().resolve(response);
   return deferred.promise();
 }
 $(function() {

   $.ajax = ajax_response([1, 2, 3]);
   $.ajax('GET', 'some/url/i/fancy').done(function(data) {
     console.log(data); // [1, 2, 3]
   });
 });

Upvotes: 1

Views: 2436

Answers (1)

Win
Win

Reputation: 5584

$.ajax needs to be a function or else it won't return the promise.

function ajax_response(response) {
    var deferred = $.Deferred().resolve(response);
    return deferred.promise();
}

$.ajax = function() {
    return ajax_response([1, 2, 3]); 
};

$.ajax('GET', 'some/url/i/fancy').done(function(data) {
    console.log(data); // [1, 2, 3]
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Related Questions