Last Updated: January 28, 2019
·
10.64K
· magalhini

Testing $.ajax calls with Jasmine 2

A quick and easy way of implementing tests for your applications Ajax calls (assuming jQuery here, but it will work with pretty much everything else).

It involves spying on the original ajax method, creating a spied callback, and providing some fake data that will be expected using a resolved promise.

So, a very simple implementation of the method we want to test could be something like:

Async.prototype.fetch = function (cb) {
$.ajax('/url')
    .done(function (data) {
        cb(data);
    });
};

Here we're simply grabbing a URL and run a callback against the returned data.

As for the Jasmine test, here's a sample full implementation:

describe("Async", function () {
    it("should fetch from a server", function () {
        var async = new Async();

        // creating our spied callback
        var callback = jasmine.createSpy('callback');
        var data = [
              {x: 0,  y: 0},
        ];

        spyOn($, 'ajax').and.callFake(function (req) {
            var d = $.Deferred();
           // resolve using our mock data
            d.resolve(data);
            return d.promise();
        });

        async.fetch(callback);

        // grabbing the returned arguments from the spied call:
        var fakeData = callback.calls.mostRecent().args[0];
        expect(fakeData[0].x).toEqual(data[0].x);
    });
}); 

And there you have it.