Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

then method of resolved promise not called

I am trying to stub a method using sinon, jasmine and $q. I want that method to return my fake data.

The problem is that the defined then statement is never called and i can not figure out why. This already is a simplified version but it still isn't working:

  • The stub is called
  • The console log Steven Stub is called gets called
  • None of the then callbacks are called
  • No error message

Here is my code

var p = {steven: function() {console.log('original steven');}},
    pStub = sinon.stub(p, 'steven', function(){
      console.log('Steven Stub is called');
      var defer = $q.defer();
      defer.resolve({item: 5});
      return defer.promise;
});

var promise = p.steven();

promise.then(
  function(data){console.log('Peter?');},
  function(data) {console.log('ERROR?');},
  function(data) {console.log('progress?');});

Any idea?

like image 269
Andresch Serj Avatar asked Jan 11 '23 15:01

Andresch Serj


1 Answers

You need to call a digest in order to resolve a promise. In Angular 2.0 this will be fixed, (and Angular 1.2 is slightly better here than Angular 1.1) but in the meanwhile you have to call

$rootScope.$digest()

In order to cause the promises to resolve. This is because promises work via evalAsync. See this question to learn more about how the digest cycle interacts with $q promises lifecycle.

like image 72
Benjamin Gruenbaum Avatar answered Jan 23 '23 19:01

Benjamin Gruenbaum