Bradley Bradley - 1 year ago 95
AngularJS Question

Angular.js promise not resolving when unit testing service with karma

I am trying to unit test an Angular.js service, and need to set an expect on a promise returned from a Mock service (using Jasmine). I am using the karma unit testing framework. The relevant code snippet is below:

// I can't figure out how to do the equivalent of a $scope.$digest here.
var loginStatusPromise = FacebookService.getFacebookToken();
loginStatusPromise.then(function(token) {
expect(false).toBeTruthy(); // If this test passes, there is something going wrong!
expect(token).not.toBeNull(); // The token should be ValidToken

The complete unit test code can be seen here.

The problem is the promise.then statement never fires when karma is executing. Hence, none of my expect statements are executed.
In my controller tests, I use $scope.$digest() to resolve the promises, but I am not clear on how to do this in a service test. As I thought there was no notion of 'scope' in a service test.

Do I have the wrong end of the stick here? Do I need to injecct $rootScope into my service test and then use $digest? Or, is there another way?

Answer Source

Assuming that you are using ngFacebook/ngModule a quick note before the solution/ideas is that this project does not have unit tests ! Are you sure you want to use this project ?

I did a quick scan of your Unit Tests on Github and found following missing:-

1) Module initialization. ngFacebook needs that or you need to initialize your module that does the same thing.




2) Seriously consider mocking ngFacebook module

At unit level tests you are testing your code within a mocked bubble where outside interfaces are stubbed out.

Otherwise) Try adding calling the API as below:-

 $rootScope.$apply(function() {
        //your expect code here
 $httpBackend.flush();//mock any anticipated outgoing requests as per [$httpBackend][2]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download