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.
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.
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.
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.
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.
test("should mock ajax", function() {
$.ajax = function(options) {
equals(options.url, "/GetHelloWorld");
options.success("Hello");
};
doSomethingWithAjax();
equal($("#responseFromServer").text(), "Hello");
});
The jasmine-ajax library allows you to define mock responses for all ajax calls without touching the calls themselves.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With