I have a basic jQuery ajax call, which I am mocking the response using jquery.mockjax.js:
$(document).ready(function() {
$("button.ajax").on("click", getAjaxResult);
});
function getAjaxResult() {
$.getJSON("/restful/get", function(response) {
if ( response.status == "success") {
$("p.ajax_result").html( response.result );
} else {
$("p.ajax_result").html( "There is a problem, cannot ajax get." );
}
});
}
jquery.mockjax.js stub:
$.mockjax({
url: "/restful/get",
responseText: {
status: "success",
result: "Your ajax was successful."
}
});
At the same time I am trying to write a Jasmine describe block to test when the event is triggered, the ajax as well as the result is successful:
it("ajax result should be shown after the button is clicked", function() {
spyEvent = spyOnEvent("button.ajax", "click");
$("button.ajax").trigger("click");
expect("click").toHaveBeenTriggeredOn("button.ajax");
expect(spyEvent).toHaveBeenTriggered();
getAjaxResult();
expect($("p.ajax_result")).toHaveText("Your ajax was successful.");
});
When I run the test, it always fails. I suspect the expect() was executed before the ajax has finished?
Any idea on how I can refactor it to make it work?