How to fake jquery.ajax() response?

前端 未结 6 514
孤独总比滥情好
孤独总比滥情好 2020-12-07 20:56

I am writing some QUnit tests for a JavaScript that makes AJAX calls.

For isolation I overwrite $.ajax to write the parameter array of an AJAX call to a

6条回答
  •  孤街浪徒
    2020-12-07 21:00

    This question has a few years and for the new versions of jQuery has changed a bit.

    To do this with Jasmin you can try Michael Falaga's approach

    Solution

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

    With Jasmine

      describe("Test test", function() {
        beforeEach(function() {
          spyOn($, 'ajax').and.returnValue(
            ajax_response([1, 2, 3])
          );
        });
        it("is it [1, 2, 3]", function() {
          var response;
          $.ajax('GET', 'some/url/i/fancy').done(function(data) {
            response = data;
          });
          expect(response).toEqual([1, 2, 3]);
        });
      });
    

    No Jasmine

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

提交回复
热议问题