Rekha
Rekha

Reputation: 57

Bypass Ajax request within javascript promise in Unit Testing

I have a function called getStudentData(),returns resolved data.

Inside getStudentData(), I have an Ajax request.

I want to Bypass Ajax request in my unit test case using Mocha , so that when i make a call to getStudentData(), the data should be returned.

Please find the code below:

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

Please let me know how to Bypass Ajax request By stubbing data using sinon.js .so that when i make a call to getStudentData() , data should be returned.

Upvotes: 1

Views: 216

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276286

First of all doing:

then(function(data){ return data; })

Is a no-op. So is:

catch(function(err){ throw err; });

Now, your code uses the explicit construction anti-pattern which is also a shame, it can be minimized to:

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

Now, that we're over that, let's talk about how you'd stub it. I'd do:

myObject.getStudentData = function() {
    return Promise.resolve({}); // resolve with whatever data you want to test
};

Which would let you write tests that look like:

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

Although in practice you'll test other objects that call that method and not the method itself.

Upvotes: 3

Related Questions