4

I have a ComponentA that uses an ServiceA. I'm writing a test for ComponentA, adding ServiceA into testbed providers. I run the test and get following error:

StaticInjectorError(DynamicTestModule)[ServiceA -> ServiceB]
NullInjectorError: No provider for ServiceB!

I add ServiceB to providers. I run the test again and now I get:

StaticInjectorError(DynamicTestModule)[ServiceB -> ServiceC]
NullInjectorError: No provider for ServiceC!

My project has many nested dependencies, all services have @Injectable decorator. How can I avoid providing long list of nested services?

Kirill
  • 406
  • 3
  • 11
  • Posible duplicate https://stackoverflow.com/questions/40319045/mock-custom-service-in-angular2-during-unit-test – Castro Roy Aug 09 '18 at 17:57
  • Possible duplicate of [Mock custom service in angular2 during unit test](https://stackoverflow.com/questions/40319045/mock-custom-service-in-angular2-during-unit-test) – Castro Roy Aug 09 '18 at 17:57

1 Answers1

4

In your .spec.ts file:

 providers: [
     {provide: YourService, useClass: YourMockService},
  ]

YourMockService will have the same methods as YourService but will just be typically empty methods. Here's a mock service:

import { Injectable } from '@angular/core'

@Injectable()
export class YourMockService {

  get user() {
    // this is mock data
    return {username: 'fred'}
  }

  public getFromLocalStorage(k: string) {
    return []
  }
}

YourService will have these same methods and getters but will, for example, perform HTTP requests, etc to get the username.

danday74
  • 52,471
  • 49
  • 232
  • 283
  • If DI service in turn depends on other services? Any way to 'not require' to create spies/stubs for those? something like 'NO_ERROR_SCHEMA' for components? – user3213604 Oct 04 '22 at 16:17