我有一个名为getStudentData()的函数,返回已解析的数据。
在getStudentData()中,我有一个Ajax请求。
我想在我的单元测试用例中使用Mocha绕过Ajax请求,这样当我调用getStudentData()时,应该返回数据。
请找到以下代码:
getStudentData: function() {
return studentData || (studentData = new Promise(function(resolve, reject) {
var request = {
//request data goes here
};
var url = "/student";
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
dataType: "json",
contentType: "application/json",
success: function(response, status, transport) {
//success data goes here
},
error: function(status, textStatus, errorThrown) {
reject(status);
}
});
}).then(function(data) {
return data;
})['catch'](function(error) {
throw error;
}));
}
请让我知道如何绕过Ajax请求通过使用sinon.js .so来存根数据,当我调用getStudentData()时,应该返回数据。
答案 0 :(得分:3)
首先要做的事:
then(function(data){ return data; })
是无操作。所以是:
catch(function(err){ throw err; });
现在,您的代码使用了explicit construction anti-pattern这也是一种耻辱,它可以最小化为:
getStudentData: function() {
var request = {
//request data goes here
};
var url = "/student";
return studentData ||
(studentData = Promise.resolve($.ajax({
url: url,
type: "POST",
data: JSON.stringify(request),
dataType: "json",
contentType: "application/json" })));
}
现在,我们已经 ,让我们谈谈你是如何存根的。我做了:
myObject.getStudentData = function() {
return Promise.resolve({}); // resolve with whatever data you want to test
};
这可以让你编写看起来像的测试:
it("does something with data", function() { // note - no `done`
// note the `return` for promises:
return myObj.getStudentData().then(function(data){
// data available here, no ajax request made
});
});
虽然在实践中你会测试调用该方法的其他对象而不是方法本身。