jasmine Spies Spying on an angular service


Example

In this example we have a service, let's call it search service that has a method called search() which will initiate a get request to a back end API.

function SearchService($http) {
    const service = {};
    
    service.search = function() {
        return $http({method: 'GET', url: `/api/search`})
    }        

    return service;
}
angular.module('app').factory('searchService', SearchService);

Testing

describe('search service', function() {
    var $httpBackend;
    var searchService;
    beforeEach(angular.mock.module('app'));
    
    beforeEach(inject(function(_$httpBackend_, _searchService_) {
        $httpBackend = _$httpBackend_;            
        searchService = _searchService_;
    }));

    it('should perform http call to the search api', function(){
        searchService.search();
        $httpBackend.expectGET('/api/search');
    });

})