I have an html page with a button like this:
<input id='btnSubmit' type='button'/>
which triggers a click handler defined within the document.ready function like this:
$(document).ready(function () {
$("#btnSubmit").click(function () {
$.ajax({
url: myUrl,
data: { 'startDate': startDateId, 'endDate': endDateId },
dataType: "json",
type: "POST",
cache: false,
success: function (data) {
alert('yay!');
},
error: function (request, status, error) {
LogError(request, startDate, error);
location.href = "error/error";
}
});
}
}
Now I want to test this functionality with QUnit, so I have built the following unit test in a separate html file that references the .js file containing the code blocks above:
QUnit.test("Test", function (assert) {
var fixture = $("#qunit-fixture");
fixture.append("<input type='button' id='btnSubmit'/>");
$("#btnSubmit").trigger("click");
assert(something);
});
I have numerous other tests within this file that are all executing properly, but whenever I try to create a test that exercises the event handler of an element within the qunit-fixture, it fails to call the actual handler.
I understand that I will need to mock the ajax call to truly test this function. But I first need to determine how to trigger the event. How do I properly trigger and test events with qunit?
here is list of events present in QUnit and simple implementation
EVENT and there DESCRIPTION
testStart : Fire when a test starts
OK, I ended up just adding the button within the body of the test html document rather than through the qunit-fixture element. Now $("#btnSubmit").trigger("click"); triggers the actual event handler within the JS file under test. Oh, one other thing I did was mark the button as hidden which isn't necessary, but cleans up the test document. So the final version looks like this:
html document to test:
JavaScript to test:
QUnit test file: