QUnit: How to test ajax call without modifying the ajax call

你说的曾经没有我的故事 提交于 2019-12-03 02:51:16
test("should mock ajax", function() {

    $.ajax = function(options) {
        equals(options.url, "/GetHelloWorld");
        options.success("Hello");
    };

    doSomethingWithAjax();

    equal($("#responseFromServer").text(), "Hello");
});

The jasmine-ajax library allows you to define mock responses for all ajax calls without touching the calls themselves.

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

If you don't want to use jasmine-ajax you can try Michael Falaga's approach

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

  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]);
    });
  });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!