lundi 1 février 2016

How to mock angularjs $resource factory inside another service?

I have a service that calls a factory for fetching data from server.

angular
    .module('dataAccess.documentType', [])
    .factory('documentTypeResource', [ '$resource', 'CacheFactory', 'DRM_API_URL', function($resource,  CacheFactory, DRM_API_URL) {
        var cache = CacheFactory.createCache('documentTypeCache', {
              deleteOnExpire: 'aggressive',
              recycleFreq: 55 * 60 * 1000,
              maxAge: 60 * 60 * 1000,
              storageMode: 'sessionStorage'
            });

        return $resource(
                //DRM_API_URL + 'administrations/documentType/:lang',
                DRM_API_URL + 'administrations/documentType', 
                {lang:'@lang'}, 
                {
                    'query': {                  
                        method: 'GET',                          
                        headers: {
                            'Content-Type': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest'
                        },
                        cache: cache                            
                    }
                }
            );
    }])

    .service('documentTypeService', ['documentTypeResource', function(documentTypeResource) {


        function getDocumentType(lang) {
            var request = new documentTypeResource();
            var params = {};
            params.lang = lang;
            return request.$get(params);
        }

        return {
            getDocumentType: getDocumentType
        };
    }]);

I was trying to test the service and found a way to do that here.

This is what my script looks like:

describe('documentTypeService', function(){
        var mockResource, service, result, mockResourceFunc;

        beforeEach(function(){
            module('dataAccess.documentType');

            module(function($provide){
                $provide.factory('documentTypeResource', function(){
                    mockResource = jasmine.createSpyObj('documentTypeResource', ['$get', '$query']);

                    mockResourceFunc = function () {
                        return mockResource;
                    };

                    for(var k in mockResource){
                        mockResourceFunc[k]=mockResource[k];
                    }
                });
            });

            inject(function(documentTypeService){
                service = documentTypeService;
            });

            result = service.getDocumentType('en');
        });

        it('should call the factory', function(){
            expect(mockResource.$get).toHaveBeenCalled();
        });
    });

On execution of the script, I'm getting the error as - * TypeError: undefined is not a constructor (evaluating 'new documentTypeResource()')

I'm probably missing something small. Any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire