0

I have a factory that returns a promise from $http

angular.module('app.core')
    .factory('dataService', dataService);
dataService.$inject = ['$http'];
function dataService($http){
    return $http.get('/getLocalSession')
        .then(function(response){
            return response.data;
        });
}

Here is another service using the above factory

angular.module('app.core')
    .service('analytics', analytics);
analytics.$inject = ['dataService'];
function analytics(dataService){
    dataService.then(function(data){
        //do something with data
    });
}

Here is the test for analytics service

describe('analytics service', function(){
    var analytics, $q, dataService, $rootScope;
    var testLanId = 'user001';
    beforeEach(module('app.core'));
    beforeEach(module({
        dataService: $q.when({
            lanId: testLanId
        })
    }));
    beforeEach(inject(function(_analytics_, _$q_, _$rootScope_){
        analytics = _analytics_;
        $q = _$q_;
        $rootScope = _$rootScope_;
    }));

    it('expect it to do something', function(){
        $rootScope.$apply();
        //expect specs
    });
});

However this won't work because $q is not defined before the call to inject. I've seen this post, but there they have a service returning a function which returns a promise.

How can we mock a factory returning a promise?

duggi
  • 556
  • 5
  • 13

1 Answers1

0

Use the function argument for angular.mock.module and provide $q as a dependency.

beforeEach(module(function($provide){
    $provide.factory('dataService', function($q){
        return $q.when({lanId: testLanId});
    });
}));
duggi
  • 556
  • 5
  • 13