Search code examples
jqueryajaxjasminesinonspy

How to test the $.ajax success handler


Some portion of code is still using the old success handler which is currently making it difficult to test the lines inside them.

Below is my sample function:

function updateXYZExemption(partyId, payload) {

        if (!partyId) {
            throw new Error('partyId is required');
        }

        return $.ajax({
            dataType: 'json',
            contentType: 'application/json',
            type: 'PUT',
            data: JSON.stringify(payload),
            url: config.urls.updateXYZExemptionUrl.replace(/\{partyId\}/, partyId),
            headers: {
                'If-Match': eTag
            },
            success: function (data, textStatus, request) {
                if (request.getResponseHeader('ETag')) {
                    eTag = request.getResponseHeader('ETag');
                }
            }
        });
    }

I am able to test that this function returns a promise but the function which is assigned to success property is not reachable.


Solution

  • Move the function to its own testable unit:

    var myFunction = function (data, textStatus, request) {
        if (request.getResponseHeader('ETag')) {
            eTag = request.getResponseHeader('ETag');
        }
    };
    

    Then you can invoke that function independently, supply it mocks, and validate that its internal logic interacts with those mocks as expected and produces the expected results/effects.

    You can use it as the success handler just by referencing the function:

    $.ajax({
        //...
        success: myFunction,
        //...
    });
    

    This effectively separates the logic being tested (the function) from the framework plumbing (the call to $.ajax()). The framework plumbing itself is of lower value for unit testing, since at that point you're really just testing someone else's code (the framework's).