Qunit parameterized tests and mocking

For mocking ajax requests, you can try something like this…

Here’s the function you want to test:

    var functionToTest = function () {
        $.ajax({
            url: 'someUrl',
            type: 'POST',
            dataType: 'json',
            data: 'foo=1&foo=2&foo=3',
            success: function (data) {
                $('#main').html(data.someProp);
            }
        });
    };

Here’s the test case:

    test('ajax mock test', function () {
        var options = null;
        jQuery.ajax = function (param) {
            options = param;
        };
        functionToTest();
        options.success({
            someProp: 'bar'
        });
        same(options.data, 'foo=1&foo=2&foo=3');
        same($('#main').html(), 'bar');
    });

It’s essentially overriding jQuery’s ajax function and then checks the following 2 things:
– the value that was passed to the ajax function
– invokes the success callback and asserts that it did what it was supposed to do

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)