Error: [$injector:unpr] Unknown provider: in AngularJS Service Test

46,597

Solution 1

The following is what I used to get it working (finally)

 beforeEach(function() {
    module(cm.modules.app.name);

    module(function($provide) {
      $provide.service('defaultAlertFactoryA', myServiceName);
    });

    inject(function($injector) {
      defaultAlertFactory = $injector.get('defaultAlertFactoryA');
    });
 });

Solution 2

In order to bootstrap your module you need to provide its name

beforeEach(module('myApp'));

Demo

Solution 3

Sounds like you need to include the service files in your karma.conf.js file

files: [

  'app/bower_components/angular/angular.js',
  'app/bower_components/angular-mocks/angular-mocks.js',
  'app/bower_components/angular-ui-router/release/angular-ui-router.js',
  'app/app.js',
  'app/controllers/*.js',
  'app/services/*.js',
  'tests/**/*.js'
],

If the are not included here they can't be accessed in the unit tests

Share:
46,597
eb80
Author by

eb80

Updated on May 08, 2020

Comments

  • eb80
    eb80 about 4 years

    I am having a lot of trouble getting dependencies provided properly for an AngularJS service.

    I see a number of other posts with similar errors here on StackOverflow but none of them seem to resolve the issue.

    Here is the app code:

    cm.modules.app = angular.module('myApp', ['ngRoute', 'ngAnimate']);
    myServiceName = function($http) {
        // do stuff
    };
    myServiceName.prototype.value = 1;
    
    cm.modules.app.service('defaultAlertFactoryA', myServiceName);
    

    Here is the test code:

    describe('test alertFactoryA', function() {
      var $provide;
      var mAlertFactoryA;
    
      beforeEach(module(cm.modules.app));
    
      beforeEach(angular.mock.module(function(_$provide_) {
        $provide = _$provide_;
      }));
    
      beforeEach(function() {
        inject(function($injector) {
          mAlertFactoryA = $injector.get('defaultAlertFactoryA');
        });
      });
    
      it('should work', function() {
        expect(true).toBe(true);
      });
    });
    

    Here is the error:

    Error: [$injector:unpr] Unknown provider: defaultAlertFactoryAProvider <- defaultAlertFactoryA http://errors.angularjs.org/1.2.0-rc.2/$injector/unpr?p0=defaultAlertFactoryAProvider%20%3C-%20defaultAlertFactoryA

    Question: How do I fix this so the test passes?

  • seneyr
    seneyr about 6 years
    If you're using newer versions of webpack, make sure you're not running webpack in production mode otherwise it will uglify the angular sources in the bundle and you'll get this error in your test runs