【发布时间】:2019-02-26 20:37:33
【问题描述】:
我有一个对 json api 发出 $.ajax 请求的脚本。所以我想做的是构建单元测试,这样我就可以测试ajax请求的结果。例如,如果我得到 json 对象。我知道结果应该包括“项目”和“结果”,这是一个数组。问题是我不知道如何初始化
中的 $.ajax 函数$("#button").click(function() { });
这是我的 javascript index.js 文件的框架。文件不完整。因为它更长。我只是包括了相关部分。但它有效。这是在线直播的应用http://pctechtips.org/apps/books/
$(document).ready(function() {
var item, tile, author, publisher, bookLink, bookImg;
var outputList = document.getElementById("list-output");
var bookUrl = "https://www.googleapis.com/books/v1/volumes?q=";
var searchData;
$("#search").click(function() {
outputList.innerHTML = ""; //empty html output
searchData = $("#search-box").val();
//handling empty search input field
if(searchData === "" || searchData === null) {
displayError();
}
else {
// console.log(searchData);
// $.get("https://www.googleapis.com/books/v1/volumes?q="+searchData, getBookData()});
$.ajax({
url: bookUrl + searchData,
dataType: "json",
success: function(response) {
console.log(response)
if (response.totalItems === 0) {
alert("no result!.. try again")
}
else {
$("#title").animate({'margin-top': '5px'}, 1000); //search box animation
$(".book-list").css("visibility", "visible");
displayResults(response);
}
},
error: function () {
alert("Something went wrong.. <br>"+"Try again!");
}
});
}
$("#search-box").val(""); //clearn search box
});
});
【问题讨论】:
标签: javascript jquery ajax unit-testing