As seen in this jsFiddle, I have a function 'init' that configures a button so that when clicked it opens a progress dialog and issues an Ajax call. I want to unit test this JavaScript code (using QUnit), and check the following cases:
- Ajax call succeeds
- Ajax call fails
I need to mock out at least the Ajax call and the call to window.open
, and other calls I'm sure, depending on unit test implementation.
How can I write QUnit unit tests for my code that tests these two scenarios?
EDIT: The code that needs to be tested:
var statusmod = (function() {
var spinner = $("#spinner");
var init = function(id) {
var progressDialog = $("#progressdialog-content").dialog({
autoOpen: false,
title: "Launching Status Page"
});
var errorDialog = $("#errordialog-content").dialog({
autoOpen: false,
modal: true,
buttons: {
"OK": function() {
$(this).dialog("close");
}
}
});
var btn = $("#button-status");
btn.button().click(function() {
spinner.show();
progressDialog.dialog("open");
var url = $.validator.format("/api/binid/?id={0}", id);
// Call Web service to get binary ID
$.ajax({
url: url,
dataType: "json"
}).done(function(data) {
window.open($.validator.format("http://status/?Page=Status&Id={0}", data.Id), target = "_newtab");
}).fail(function(jqXHR, msg, errorThrown) {
errorDialog.dialog("open");
}).always(function() {
progressDialog.dialog("close");
});
return false;
});
};
return {
init: init,
_spinner: spinner
};
}());