Chadams
Chadams

Reputation: 1933

Stubbing dojo requests

given the following...

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);
});

I wish to test "theUserID" and if there is a problem bypass the remote request completely, and have the returned promise object fire it's error method.

I would also like to stub out the remote request for testing purposes, by returning a promise object but auto calling the "success/result" function passing it JSON, with out actually making the remote call.

Upvotes: 0

Views: 91

Answers (1)

Frances McMullin
Frances McMullin

Reputation: 5696

Assuming by your code that you're using AMD, dojo 1.7 or 1.8. This should do the trick:

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;
};

You may also want to check the docs on dojo/Deferred.

Upvotes: 1

Related Questions