Search code examples
javascriptjqueryqunitmockjax

Testing with qunit and mockjax


I am trying to figure out how to test this javascript function aduequately using qunit and mockjax

My javascript is set up with the revealing module pattern, im new to unit testing so this is kind of driving me up a wall

my.someMethod = function (someId, completedHandler) {
        $.ajax({
            dataType: "json",
            url: my.someUrl,
            traditional: true,
            data: {
                someId : someId
            },
            success: function () {

                if (completedHandler !== undefined) {
                    completedHandler();
                }
            }
        });
    };

Like i want to test if the correct url is being used, if the id being passed in is the right one, making sure the ajax is being called etc.


Solution

  • How about that, figured it out myself finally.

    Structure it somethng like so

    In your javascript method

    my.someMethod = function (someId, completedHandler) {
            $.ajax({
                dataType: "json",
                url: my.someUrl,
                traditional: true,
                data: {
                    someId : someId
                },
                success: function (data) {
    
                    if (completedHandler !== undefined) {
                        completedHandler(someId, my.someUrl, data.testResult);
                    }
                }
            });
        };
    

    Set up your mockjax

    $.mockjax({
                url: "someActualUrl",
                dataType: 'json',
                responseText:
                    {
                        testResult: 'AJAX Called'                           
                    }
            });
    

    And in your actual qunit test

    test("someMethod calls ajax", function () {
    
            namespace.someMethod("id1",
                function (someId, someUrl, someTestResult) {
                    test("someMethod ajax test", function () {
    
                        assert.strictEqual(someId, "id1");
                        assert.strictEqual(someUrl, "someActualUrl");
                        assert.strictEqual(someTestResult, "AJAX Called");
                });
    
            start();
        });
    
        ok(true, "Ajax Called");
    });