Reputation: 21
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?
Upvotes: 2
Views: 645
Reputation: 13273
You guessed correctly. The mockjax plugin preserves the async nature of the ajax call, and thus your expect()
fires before the ajax call is complete. You would need to alter the getAjaxResult()
function to use a callback in order to know when it is complete within your test:
function getAjaxResult(cb) {
$.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." );
}
cb(response);
});
}
Then your test looks like this...
it("ajax result should ...", function(done) { // <<< Note the `done` arg!
spyEvent = spyOnEvent("button.ajax", "click");
$("button.ajax").trigger("click");
expect("click").toHaveBeenTriggeredOn("button.ajax");
expect(spyEvent).toHaveBeenTriggered();
getAjaxResult(function() { // <<< Added the callback here
expect($("p.ajax_result")).toHaveText("Your ajax was successful.");
done(); // <<< Don't forget to tell jasmine you're done
});
});
Upvotes: 1