Angularjs – Angular / Karma: unknown provider

angularjskarma-jasmine

I am new to testing in Angular and finding difficult to understand how to do a simple test on my controller's injections, getting the error:

Error: [$injector:unpr] Unknown provider: localStorageServiceProvider <- localStorageService

Controller:

angular.module('myApp.home', [])
.controller('HomeCtrl', ['$scope','localStorageService',function($scope,localStorageService) {
// ...
}]);

Test:

describe('myApp.home module', function() {
    var $scope;
    var localStorageService;

    beforeEach(module('myApp.home'));

    describe('home controller', function(){

      it('should ....', inject(function($controller,_$rootScope_,_localStorageService_) {
        $scope = _$rootScope_.$new();
        localStorageService = _localStorageService_;

        var headerCtrl = $controller('HomeCtrl',{"$scope" : $scope, "localStorageService" : localStorageService});
        expect(headerCtrl).toBeDefined();
      }));

    });
});

In my karma.conf.js i referenced:

files : [
      'app/bower_components/angular/angular.js',
      'app/bower_components/angular-route/angular-route.js',
      'app/bower_components/angular-mocks/angular-mocks.js',
      'app/bower_components/angular-local-storage/dist/angular-local-storage.js',
      'app/js/controllers/*.js'
    ]

Best Solution

Assuming you are using this library https://github.com/grevory/angular-local-storage

The module is not loaded for the test.

Either do

angular.module('myApp.home', ['LocalStorageModule'])

to inject the module into your module.

or try

 beforeEach(module('LocalStorageModule'));
 beforeEach(module('myApp.home'));
Related Question