Qunit parameterized tests and mocking

Noel picture Noel · Feb 6, 2009 · Viewed 12.3k times · Source

I have two questions:

Can you have parameterised unit tests in qunit?

How do you do mocking with qunit e.g. mocking a getJSON call?

Thanks

Answer

Johnny Oshika picture Johnny Oshika · Jan 24, 2010

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