Testing a simple AngularJS service using Jasmine

angularjs, angularjs-service, jasmine, karma-runner

Solution

The following should work for a service without parameter, maybe this can be a starting point:

describe("Unit: Testing Services", function() {
    describe("Search Service:", function() {

        beforeEach(function() {
            angular.module('app');
        });

        it('should contain a searchService',
           inject(function(searchService) {
                expect(searchService).not.to.equal(null);
        }));

        it('should contain two search options',
            inject(function(searchService) {
                expect(searchService.getSearchOptions()).to.equal(2);
        }));

   });
});

(You can also have a look here: How do I test an AngularJS service with Jasmine?)

Problem

I have a simple service that I am trying to unit test. No matter what I try, either the searchService is an unknown provider, or service is null (which oddly enough won't cause my test to fail!!). Anyone have an insight on what I might be doing wrong?? ``` angular.module('app').service('searchService', function( $q, _ ) { // _ is lodash var cache = [ { id: "current", name: "Current", description: "Search current data" }, { id: "historical", name: "Historical", description: "Search historical data" } ]; this.getSearchOptions = function() { var deferred = $q.defer(); deferred.resolve( angular.copy( cache ) ); return( deferred.promise ); }; this.getSearchOptionsByID = function( id ) { var deferred = $q.defer(); var searchOption = _.findWithProperty( cache, "id", id ); if ( searchOption ) { deferred.resolve( angular.copy( searchOption ) ); } else { deferred.reject(); } return( deferred.promise ); }; } ); ``` I am trying to create a unit test that loads in the searchService so I can check the cached values: ``` describe("Unit: Testing Services", function() { describe("Search Service:", function() { var service = null; beforeEach(function() { angular.module('app').service('_'); }); // I've also tried the commented out code below //beforeEach(inject(function(searchService) { //this.service = searchService; //})); //it('should contain an searchService', invoke(function(service) { it('should contain an searchService', function(searchService) { expect(searchService).not.to.equal(null); }); it('should contain two search options', function(searchService) { expect(searchService.getSearchOptions()).to.equal(2); }); }); }); ```

Original source