Angular 4.x: No provider for Service

18,702

Your test for ContactService uses a testing module which only declares ContactService as provider. But ContactService needs a SkillsService. So SkillsService must also be part of the providers of the testing module:

TestBed.configureTestingModule({
  providers: [ContactService, SkillsService]
});

You could also use the whole application module in your test:

TestBed.configureTestingModule({
  imports: [AppModule]
});

But I wouldn't recommend that because your tests will become slower and slower while the application grows.

Share:
18,702
Baldy
Author by

Baldy

Fast computers breed lazy programmers

Updated on June 13, 2022

Comments

  • Baldy
    Baldy almost 2 years

    I am having trouble injecting a service into another service in Angular 4.x and receive the error: Error: No provider for SkillsService!

    I have created a repo that reproduces this error. You can run this locally by cloning the repo and simply running ng test from the repo root directory.

    Steps i took...

    1. Create app with ng new
    2. Create ContactService with ng g service contact
    3. Create SkillsService with ng g service skills
    4. Add SkillsService to constructor of ContactService (with @Inject annotation)
    5. Add both SkillsService and ContactService to app.module.ts as providers
    6. Run ng test and receive the error: Error: No provider for SkillsService!

    How do I add a provider to ContactService for the SkillsService?

    It seems like it must be something very simple, yet it's proving hard to work out from the documentation and searching around.

  • Baldy
    Baldy over 6 years
    Thanks. I was focusing on the app module configuration rather than the test setup. problem solved :)