Last Updated: February 25, 2016
·
7.923K
· macie

Proper way to jQuery.ajax mocking

jQuery.ajax method returns Deferred object, so it's ease to write parametrized version of ajax mock (example in Jasmine):

// Synchronous jQuery.ajax mock
spyOn($, 'ajax').and.callFake(function(url) {
    var ajaxMock = $.Deferred();

    switch (url) {
        case undefined:
            ajaxMock.resolve({
                'error': 'Please use POST request'
            });
            break;
        case 'valid_url':
            ajaxMock.resolve('some data');
            break;
        default:  // invalid url
            ajaxMock.reject();
    }

    return ajaxMock.promise();
});

And that is the equivalent of ajax synchronous request. But it's better not to use that type of requests, because they can lock a browser (remember that A in AJAX means asynchronous?).

To get asynchronous request you need to add timeout:

// Asynchronous jQuery.ajax mock
spyOn($, 'ajax').and.callFake(function(url) {
    var ajaxMock = $.Deferred();

    setTimeout(function() {
        switch (url) {
            case undefined:
                ajaxMock.resolve({
                    'error': 'Please use POST request'
                });
                break;
            case 'valid_url':
                ajaxMock.resolve('some data');
                break;
            default:  // invalid url
                ajaxMock.reject();
        }
    }, 5);

    return ajaxMock.promise();
});

That's all. Enjoy your new mock.