简体   繁体   中英

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.

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");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM