Last Updated: February 25, 2016
·
8.232K
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside