QUnit: How to test ajax call without modifying the

2019-03-15 14:07发布

How can I write a QUnit test for this:

function doSomethingWithAjax() {
    $.ajax({
        url: '/GetHelloWorld',
        success: function(data) { $("#responseFromServer").text(data); },
    });
}

Mockjax+qunit requires a start() call in the ajax complete() method.

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-15 14:49

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

查看更多
\"骚年 ilove
3楼-- · 2019-03-15 14:52
test("should mock ajax", function() {

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

    doSomethingWithAjax();

    equal($("#responseFromServer").text(), "Hello");
});
查看更多
Lonely孤独者°
4楼-- · 2019-03-15 14:55

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]);
    });
  });
查看更多
登录 后发表回答