1

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]
   });
 });
user1032531
  • 24,767
  • 68
  • 217
  • 387

1 Answers1

2

$.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>
Win
  • 5,498
  • 2
  • 15
  • 20