mercredi 8 juillet 2015

Karma-Jasmine: How to mock a service in angularJS that utilizes other services/factories/constants?

I have a service called "myService" for which I want to write test cases using Karma:

(function () {
    angular.module('myApp').factory('myService', myService);
    myService.$inject = ['$http', 'UrlsFactory'];

    function myService($http, UrlsFactory) {
        var service = {
            getData: getData          
        };
        return service;
        function getData() {
            return $http.get(UrlsFactory.url1)                
                .error(function(){
                    return;
                })
                .then(function (response) {
                    return response.data;
                });
        }
    }
})();

I call this service in my controller as:

myService.getData().then(function (response) {
    receivedData = response;
});

myService utilizes a factory called "UrlsFactory":

(function () {
    angular.module('myApp').factory('UrlsFactory', UrlsFactory);
    UrlsFactory.$inject = ['myBaseUrl'];
    function UrlsFactory(myBaseUrl) {
        return {
            'url1': myBaseUrl + '/-url1-here/',
            'url2': myBaseUrl + '/url2-here/'
        };
    }
})();

This factory again is utilizing a constant called "myBaseUrl" as:

(function () {
    angular.module('myApp')
        .constant('myBaseUrl', 'http://localhost:9000')
})();

Now I write the test case as:

describe("Testing: myService", function() {
    var myService, UrlsFactory, myBaseUrl, httpBackend;

    beforeEach(function () {
        module('myApp');

        inject(function ($injector) {
            httpBackend = $injector.get('$httpBackend');
            myService = $injector.get('myService');
            UrlsFactory = $injector.get('UrlsFactory');
            myBaseUrl = $injector.get('myBaseUrl');
        });
    });

    it('GET HTTP response for url1', inject(function () {
        var test = myService.getData();
        httpBackend.expectGET(myBaseUrl.url1).respond(200, test);
        httpBackend.flush();  
    }));
});

But this does not work! So, how do I write a mock for "myService" that utilizes the other factory as well as constant as a dependency? Thanks!

Aucun commentaire:

Enregistrer un commentaire