xiotee
xiotee

Reputation: 1559

Angular 2 - Mocking Services in Components that depend on other services

How do I mock a service that depends on another service that is in a component? Please check code below.

a.component.ts

@Component({
  selector: 'my-comp',
  templateUrl: './my.component.html',
  providers: [ MyServiceA ]
})
export class MyComponent {

my-service-a.service.ts

@Injectable()
export class MyServiceA{
  constructor(private myServiceB: MyServiceB) {}

my-service-b.service.ts

export class MyServiceB{
constructor(private myServiceC: MyServiceC,
              private myServiceD: MyServiceD) {}

How do I mock the service in the a.component.spec.ts in the TestBed configuration? Please help. Thank you.

Upvotes: 1

Views: 1200

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 208944

You can mock it however you want. The other services don't matter. I think maybe the problem you are facing is with the @Component.providers. Using this, any mocks you configure in the TestBed aren't used as the @Component.providers take precedence, causing Angular to try to create it, instead of using the mock.

To get around that, Angular offers the TestBed.overrideComponent method, so that we can override things like the template and providers of the @Component

beforeEach(() => {
  let myMockService = new MyMockService();

  TestBed.configureTestingModule({
    providers: [
      // the following will not be used
      { provide: MyService, useValue: myMockService }
    ]
  });
  TestBed.overrideComponent(MyComponent, {
    set: {
      providers: [
        // this will override the @Component.providers:[MyService]
        { provide: MyService, useValue: myMockService }
      ]
    }
  });
})

Upvotes: 5

Related Questions