QUnit: How to test ajax call without modifying the ajax call
Asked Answered
P

3

11

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.

Pasquil answered 21/2, 2012 at 20:0 Comment(0)
P
16
test("should mock ajax", function() {

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

    doSomethingWithAjax();

    equal($("#responseFromServer").text(), "Hello");
});
Pasquil answered 22/2, 2012 at 18:11 Comment(0)
W
1

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

Walley answered 21/2, 2012 at 20:3 Comment(1)
Can you share a solution to the OP's question using jasmin-ajax?Radiotelegraph
A
0

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]);
    });
  });
Aldis answered 16/4, 2015 at 15:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.