存根dojo请求

Stubbing dojo requests

本文关键字:请求 dojo 存根      更新时间:2023-09-26

给定如下…

api.checkIn = function (theUserID) {
    var uri;
    uri = 'some/uri/here/' + theUserID;
    return req.get(uri, {
        handleAs: 'json'
    });
};
api.checkIn(userID).then(function (res) {
  _displayMessage("Attendance Saved.");
},
function(error){
  console.log("An error occurred: " + error);
});

我想测试"theUserID",如果有问题完全绕过远程请求,并有返回的承诺对象触发它的错误方法。

我还想存根远程请求的测试目的,通过返回一个承诺对象,但自动调用"成功/结果"函数传递JSON,而不是实际进行远程调用。

假设您使用的是AMD, dojo 1.7或1.8。这应该能奏效:

api.checkIn = function (theUserID) {
    var promise = new Deferred(); // you'll want to require dojo/Deferred
    if(notValid(theUserID)){ // you'll need to implement your own validity test here
        promise.reject("your error of choice here");
    } else {
        promise.resolve("your response of choice here");
    }
    return promise;
};

您可能还需要查看dojo/Deferred上的文档