eb80
eb80

Reputation: 4738

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

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?

Upvotes: 30

Views: 47291

Answers (3)

Eitan Peer
Eitan Peer

Reputation: 4345

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

beforeEach(module('myApp'));

Demo

Upvotes: 26

Dave Keane
Dave Keane

Reputation: 737

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

Upvotes: 11

eb80
eb80

Reputation: 4738

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');
    });
 });

Upvotes: 19

Related Questions