我有一个基本的 jQuery ajax 调用,我使用 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 存根:
$.mockjax({
url: "/restful/get",
responseText: {
status: "success",
result: "Your ajax was successful."
}
});
同时我正在尝试编写一个茉莉花描述块来测试何时触发事件,ajax以及结果是否成功:
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.");
});
当我运行测试时,它总是失败。我怀疑在ajax完成之前执行了expect()?
关于如何重构它以使其工作的任何想法?