How to resolve promises in AngularJS, Jasmine 2.0 when there is no $scope to force a digest? How to resolve promises in AngularJS, Jasmine 2.0 when there is no $scope to force a digest? angularjs angularjs

How to resolve promises in AngularJS, Jasmine 2.0 when there is no $scope to force a digest?


You need to inject $rootScope in your test and trigger $digest on it.


there is always the $rootScope, use it

inject(function($rootScope){myRootScope=$rootScope;})....myRootScope.$digest();


So I have be struggling with this all afternoon. After reading this post, I too felt that there was something off with the answer;it turns out there is. None of the above answers give a clear explanation as to where and why to use $rootScope.$digest. So, here is what I came up with.

First off why? You need to use $rootScope.$digest whenever you are responding from a non-angular event or callback. This would include pure DOM events, jQuery events, and other 3rd party Promise libraries other than $q which is part of angular.

Secondly where? In your code, NOT your test. There is no need to inject $rootScope into your test, it is only needed in your actual angular service. That is where all of the above fail to make clear what the answer is, they show $rootScope.$digest as being called from the test.

I hope this helps the next person that comes a long that has is same issue.

Update


I deleted this post yesterday when it got voted down. Today I continued to have this problem trying to use the answers, graciously provided above. So, I standby my answer at the cost of reputation points, and as such , I am undeleting it.

This is what you need in event handlers that are non-angular, and you are using $q and trying to test with Jasmine.

something.on('ready', function(err) {    $rootScope.$apply(function(){deferred.resolve()});              });

Note that it may need to be wrapped in a $timeout in some case.

something.on('ready', function(err) {    $timeout(function(){      $rootScope.$apply(function(){deferred.resolve()});        });     });

One more note. In the original problem examples you are calling done at the wrong time. You need to call done inside of the then method (or the catch or finally), of the promise, after is resolves. You are calling it before the promise resolves, which is causing the it clause to terminate.