Raven
Raven

Reputation: 1523

Instantiate a provider in TestBed with the instance of another provider

How do you instantiate a provider in TestBed.configureTestingModule() with an instance of another provider?

An example (doesn't work obviously):

beforeEach(() => {
  TestBed.configureTestingModule({
    providers: [
      { provide: ServiceOne, useValue: new ServiceOne('parameterOne')},
      { provide: ServiceTwo, useValue: new ServiceTwo(TestBed.get(ServiceOne), 'parameterTwo')}
    ]
  });
});

Upvotes: 1

Views: 677

Answers (1)

Paul Samsotha
Paul Samsotha

Reputation: 209012

Use a factory provider

providers: [
  { provide: ServiceOne, useValue: new ServiceOne('parameterOne')},
  { 
    provide: ServiceTwo, 
    deps: [ ServiceOne ],
    useFactory: (serviceOne: ServiceOne) => {
      return new ServiceTwo(serviceOne, 'parameterTwo')
    }
  }
]

Upvotes: 2

Related Questions