user1184100
user1184100

Reputation: 6894

Callback function not get called in jasmine test code

I'm using jasmine 2.0 for testing and I'm spying on the jquery ajax and returning a promise. In the done() function method displayContent() doesn't get called but the console message above it gets shown up. Where am I going wrong ?

test.js

it(..., function() {
   var data = {"name" : "John Doe"};
   spyOn($, 'ajax').and.callFake(function (req) {
     var d = $.Deferred();
     d.resolve(data);   
     return d.promise();
   });

   app.doSomething();
   expect(app.doSomething).toHaveBeenCalled();
})

app.js

app.getData = function() {
  var jsonData = app.loadEmpData();   //gets replaced by spy and returns resolve(data);
  jsonData.done(function(data) {
      console.log("shows up in the console");
      app.displayContent(data);  // doesn't get called 
  });
  jsonData.fail(function(){
      console.log("error loading data");
  });
}

app.loadEmpData = function() {
   return $.getJSON("/employee.json");
}

app.displayContent = function() {
   console.log("some content");
}

app.doSomething = function() {
  app.getData();
}

Upvotes: 2

Views: 3113

Answers (2)

DotBert
DotBert

Reputation: 1298

Two possible options pop up in my head:

1) In some scenarios you should call $scope.apply() in your test code to ensure the promise's then function is executed.

2) You could use the done() function, like this:

it('', function(done){
  $promise.then(function(){
    expect(...);
    done();
  })
});

Upvotes: 2

Anand S
Anand S

Reputation: 1138

Spy on the displayContent() and check if it is called or not. I modified your test and displayContent() was called. Replace with this code and check.

it("some test", function() {
    var data = {"name" : "John Doe"};
    spyOn($, 'ajax').and.callFake(function (req) {
        var d = $.Deferred();
        d.resolve(data);   
        return d.promise();
    });
    spyOn(app, 'displayContent').and.callThrough();
    app.getData();
    expect(app.displayContent).toHaveBeenCalled();
});

In Jasmine 2.0 and.callThrough(); will delegate to the actual implementation of displayContent().

Upvotes: 1

Related Questions