Testing angular services with Jasmine

Testing an Angular service with Jasmine

by eitanp461

HTML

<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
<script src="http://code.angularjs.org/1.2.9/angular.js"></script>
<script src="http://code.angularjs.org/1.2.9/angular-mocks.js"></script>

JavaScript

//--- CODE --------------------------
var myApp = angular.module('myApp', []);

// Create a map-based configuration service 
myApp.service('ConfigurationService', function () {
    var map = {};
    this.get = function (key) {
        return map[key];
    }
});

// Create a service with dependencies
myApp.provider('MyService', function () {
    this.$get = ['$http', '$q', 'ConfigurationService',

    function ($http, $q, ConfigurationService) {
        function doGet(value) {

            // Get server url from configuration service dependency
            var url = ConfigurationService.get('url');

            var defer = $q.defer();

            // Perform the actual HTTP call with query parameters
            // e.g. GET <server url>/someUrl?key=value1
            $http({
                method: 'GET',
                url: url,
                headers: {
                    'Accept-Language': 'en'
                },
                params: {
                    key1: value
                }
            }).
            success(function (data, status, headers, config) {
                // this callback will be called asynchronously
                // when the response is available
                defer.resolve();
            }).
            error(function (data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                defer.reject();
            });

            return defer.promise;
        }
        return {
            sendHttp: function (value) {
                return doGet(value);
            }
        };
    }];
});

// --- SPECS -------------------------

describe('myApp', function () {
    var myService,
    $httpBackend,
    ConfigurationServiceMock,
    url = '/someUrl',
        paramUrl = '/someUrl?key1=value1';

    beforeEach(function () {
        // Initialize myApp injector
        module('myApp');

        // Replace...