Friday, May 4, 2012

How do I verify jQuery AJAX events with Jasmine?


I am trying to use Jasmine to write some BDD specs for basic jQuery AJAX requests. I am currently using Jasmine in standalone mode (i.e. through SpecRunner.html). I have configured SpecRunner to load jquery and other .js files. Any ideas why the following doesn't work? has_returned does not become true, even thought the "yuppi!" alert shows up fine.




describe("A jQuery ajax request should be able to fetch...", function() {

it("an XML file from the filesystem", function() {
$.ajax_get_xml_request = { has_returned : false };
// initiating the AJAX request
$.ajax({ type: "GET", url: "addressbook_files/addressbookxml.xml", dataType: "xml",
success: function(xml) { alert("yuppi!"); $.ajax_get_xml_request.has_returned = true; } });
// waiting for has_returned to become true (timeout: 3s)
waitsFor(function() { $.ajax_get_xml_request.has_returned; }, "the JQuery AJAX GET to return", 3000);
// TODO: other tests might check size of XML file, whether it is valid XML
expect($.ajax_get_xml_request.has_returned).toEqual(true);
});

});



How do I test that the callback has been called? Any pointers to blogs/material related to testing async jQuery with Jasmine will be greatly appreciated.



thanks in advance


Source: Tips4all

3 comments:

  1. I guess there are two types of tests you can do:


    Unit tests that fake the AJAX request (using Jasmine's spies), enabling you to test all of your code that runs just before the AJAX request, and just afterwards. You can even use Jasmine to fake a response from the server. These tests would be faster - and they would not need to handle asynchronous behaviour - since there isn't any real AJAX going on.
    Integration tests that perform real AJAX requests. These would need to be asynchronous.


    Jasmine can help you do both kinds of tests.

    Here is a sample of how you can fake the AJAX request, and then write a unit test to verify that the faked AJAX request was going to the correct URL:

    it("should make an AJAX request to the correct URL", function() {
    spyOn($, "ajax");
    getProduct(123);
    expect($.ajax.mostRecentCall.args[0]["url"]).toEqual("/products/123");
    });

    function getProduct(id) {
    $.ajax({
    type: "GET",
    url: "/products/" + id,
    contentType: "application/json; charset=utf-8",
    dataType: "json"
    });
    }


    Here is a similar unit test that verifies your callback was executed, upon an AJAX request completing successfully:

    it("should execute the callback function on success", function () {
    spyOn($, "ajax").andCallFake(function(options) {
    options.success();
    });
    var callback = jasmine.createSpy();
    getProduct(123, callback);
    expect(callback).toHaveBeenCalled();
    });

    function getProduct(id, callback) {
    $.ajax({
    type: "GET",
    url: "/products/" + id,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: callback
    });
    }


    Finally, you have hinted elsewhere that you might want to write integration tests that make real AJAX requests - for integration purposes. This can be done using Jasmine's asyncronous features: waits(), waitsFor() and runs():

    it("should make a real AJAX request", function () {
    var callback = jasmine.createSpy();
    getProduct(123, callback);
    waitsFor(function() {
    return callback.callCount > 0;
    });
    runs(function() {
    expect(callback).toHaveBeenCalled();
    });
    });

    function getProduct(id, callback) {
    $.ajax({
    type: "GET",
    url: "data.json",
    contentType: "application/json; charset=utf-8"
    dataType: "json",
    success: callback
    });
    }

    ReplyDelete
  2. Look at the jasmine-ajax project: http://github.com/pivotal/jasmine-ajax.

    It's a drop-in helper that (for either jQuery or Prototype.js) stubs at the XHR layer so that requests never go out. You can then expect all you want about the request.

    Then it lets you provide fixture responses for all your cases and then write tests for each response that you want: success, failure, unauthorized, etc.

    It takes Ajax calls out of the realm of asynchronous tests and provides you a lot of flexibility for testing how your actual response handlers should work.

    ReplyDelete
  3. When I specify ajax code with Jasmine, I solve the problem by spying on whatever depended-on function initiates the remote call (like, say, $.get or $ajax). Then I retrieve the callbacks set on it and test them discretely.

    Here's an example I gisted recently:

    https://gist.github.com/946704

    ReplyDelete