Dependency injection problems in Angular unit tests

Asked

Viewed 84 times

0

I’m trying to perform unit tests in Angular, but I have some problems with injection dependencies in the services. In the application there are several services that depend on each other, for example:

  1. Service A is dependent on Service B
  2. Service B is dependent on Service C
  3. Service C is dependent on Service D
  4. Service D is dependent on Httpclient and Angular Router

Due to these multiple dependency levels I cannot perform the injection of providers into the test class. It was raised the possibility of creating mocks for the services, but due to the amount of dependencies it would be necessary to create a mock for each service.

Is there any way to facilitate injection of dependencies into services?

1 answer

1

You can use the useValue or useClass to use something that would be a stub or a mock of your service. For example, let’s assume that you have a service that returns a user via http:

providers:[{
     provide: SeuServico,
     useValue: { getUser: (userId) => of({ name: 'Joao', idade: 13 }) }
}]

So you have a service that has no role, ending this cycle.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.