0

I want test some service AService, which has some dependencies BService, which is depended on another service e.x. CService. We have chain like dependencies:

AService --> BService --> CService

AService constructor:

constructor(
  private bService: BService
) {}

BService constructor:

constructor(
   private cService: CService
) {}

If I want test AService in my test file I should write something like this:

beforeAll(() => {
      injector = ReflectiveInjector.resolveAndCreate([
            AService,
            BService,
            CService,
        ]);

        service = injector.get(AService);
   });

and if I have too many services, which are chained each other I'll get too much boilerplate.

Is there any way to doesn't inject all chained services in my AService testing file?

oto lolua
  • 499
  • 4
  • 16

1 Answers1

1

Ideally, actual dependencies should not be included when unit testing your code. Instead you should supply a mock serviceB and stub those dependencies.

    describe('AService', () => {
       beforeAll(() => {
          injector = ReflectiveInjector.resolveAndCreate([
              AService,
              {provide: BService, useClass: MockBService}
              ]);
          Aservice = injector.get(AService);
       });
    });


    class MockBService {
      // enter mock functions here that you want to invoke from Service A
      // this does not have dependency on Service C
    }

In your tests, you can spy on those calls to Service B and return whatever value you want.

   const BService = AService.injector.get(BService);
   spyOn(BService, 'someFunc').and.returnValue(1);
qdivision
  • 401
  • 2
  • 9