I have successfully written a QUnit test for a success case and another for a failure case, as you can see from this jsFiddle . I used Mockjax to fake Ajax responses and simulate success / failure conditions. Notably, I configured Ajax calls synchronously, so that I could write synchronous tests since I was unable to figure out how to run the tests after the asynchronous Ajax callbacks were run.
I also use the Sinon.JS library to fake dependencies and check, for example, dialogs start correctly.
The following is a working test code, see my question for the function under test ( statusmod.init ). Let me know if something you think I forgot.
var dialogSpy = null; var windowSpy = null; var id = "srcId"; var binId = "binId"; var url = $.validator.format("/api/binid/?id={0}", id); var btnId = "#button-status"; module("Open status page", { setup: function() { // Allow us to run tests synchronously $.ajaxSetup({ async: false }); windowSpy = sinon.spy(window, "open"); dialogSpy = sinon.spy(); sinon.stub($.fn, "dialog", function() { return { "dialog": dialogSpy }; }); statusmod.init(id); }, teardown: function() { windowSpy.restore(); $.fn.dialog.restore(); $.mockjaxClear(); // Remove click event handler for each test $(btnId).unbind(); } }); test("Successfully open status page", function() { expect(4); $.mockjax({ url: url, contentType: "text/json", responseText: { Id: binId } }); var spinner = statusmod._spinner; var spinnerSpy = sinon.spy(spinner, "show"); $(btnId).click(); ok(spinnerSpy.calledOnce, "Spinner shown"); ok(dialogSpy.withArgs("open").calledOnce, "Dialog opened"); ok(dialogSpy.withArgs("close").calledOnce, "Dialog closed"); equal(windowSpy.lastCall.args[0], $.validator.format("http://status/?Page=Status&Id={0}", binId), "Window opened"); }); test("Binary ID not found on server", function() { expect(3); $.mockjax({ url: url, contentType: "text/json", status: 404 }); $(btnId).click(); ok(dialogSpy.withArgs("open").calledTwice, "Dialogs opened"); ok(dialogSpy.withArgs("close").calledOnce, "Progress dialog closed"); ok(!windowSpy.called, "Window not launched"); });
aknuds1
source share