Search code examples
jqueryqunitmockjax

QUnit: How to test ajax call without modifying the ajax call


How can I write a QUnit test for this:

function doSomethingWithAjax() {
    $.ajax({
        url: '/GetHelloWorld',
        success: function(data) { $("#responseFromServer").text(data); },
    });
}

Mockjax+qunit requires a start() call in the ajax complete() method.


Solution

  • test("should mock ajax", function() {
    
        $.ajax = function(options) {
            equals(options.url, "/GetHelloWorld");
            options.success("Hello");
        };
    
        doSomethingWithAjax();
    
        equal($("#responseFromServer").text(), "Hello");
    });