Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 480
Brian Low Avatar asked Feb 21 '12 20:02

Brian Low


People also ask

What is QUnit testing in jQuery?

QUnit is a powerful JavaScript unit testing framework that helps you to debug code. It's written by members of the jQuery team, and is the official test suite for jQuery. But QUnit is general enough to test any regular JavaScript code, and it's even able to test server-side JavaScript via some JavaScript engine like Rhino or V8.

Does QUnit test support JS async?

Following the example above, QUnit.test also supports JS async functions syntax out of the box. In ES5 and older environments, you can also return a Promise from your standard test function. This also supports other then-able, values such as jQuery.Deferred, and Bluebird Promise.

How do I assert a QUnit test using a callback?

Define a test using QUnit.test (). The assert argument to the callback contains all of QUnit’s assertion methods. Use this to make your test assertions. QUnit.test () can automatically handle the asynchronous resolution of a Promise on your behalf if you return a “then-able” Promise as the result of your callback function.

How to test the performance of Ajax requests?

Ajax requests are difficult to test since they have un-deterministic behavior. The client never knows when the Ajax request is finished. We will test our getPersons () function which will return a list of persons. Here is the implementation of the getPersons method.


2 Answers

test("should mock ajax", function() {

    $.ajax = function(options) {
        equals(options.url, "/GetHelloWorld");
        options.success("Hello");
    };

    doSomethingWithAjax();

    equal($("#responseFromServer").text(), "Hello");
});
like image 72
Brian Low Avatar answered Oct 13 '22 13:10

Brian Low


The jasmine-ajax library allows you to define mock responses for all ajax calls without touching the calls themselves.

like image 27
Jacob Mattison Avatar answered Oct 13 '22 12:10

Jacob Mattison