2

I have quite a big class hierarchy in my project and I had to extract much of the duplicated code to parent class that would be extended, having children and even grandchildren. Parent class -> child class -> child of child class. Something like this. Trying to avoid duplicating constructors and super() call I used Injector.create({options}) in the parent class to inject some of the required services. The problem is now that all my tests are failing with TypeError: Cannot read property 'get' of undefined. Here is what I have:

export abstract class ParentClass implements OnInit {
   protected router: Router;
   
   protected constructor() {
      this.router = AppModuleServices.injector.get(Router);
   }
}

Now the AppModuleServices is just a wrapping class around the injector in order to have it used in my whole project.

export class AppModuleServices {
  static injector: Injector;
}

I'm setting the static injector in the app's module like this:

export class SomeModule {
  constructor(private injector: Injector) {
    AppModuleServices.injector = this.injector;
  }
}

Everything works just fine, it's correctly doing it's job but the UT are all failing.

I've tried Angular 2 instantiate global injector in parent in Karma Jasmine test but with no success Does anyone know what is to be done on the spec side to have this work?

Thank you

UPDATE: After debugging the tests I found that actually the error is:

ReferenceError: AppModuleServices is not defined

Info: AppModuleServices is not actually a module. It's just an exported class, if it matters. I've tried to put the injector into the actual app module, but trying to use it lower in the hierarchy creates a circular dependency. But still, as it works while running the application, I don't think that is the problem, something about mocking the injector should be my solution.

Robert
  • 255
  • 2
  • 15
  • 37
  • not answering the question, but to avoid chained constructors and super calls, you can define parents as abstract classes without constructors, with services as abstract, protected members. Then you need to inject them only in the "real" component class – Normunds Kalnberzins Jul 02 '21 at 21:06
  • I see, but that's one of the issue I had. Quite a lot of services in many components, so SonarQube was complaining about duplicated code for all the constructors. – Robert Jul 03 '21 at 19:49
  • Quite often such an error is a result of circular dependencies in your code. Hard to tell for sure without seeing the actual code that reproduces the problem. – amakhrov Jul 07 '21 at 19:41
  • 3
    Can you share unit test code? – Gourav Garg Jul 08 '21 at 17:33
  • it seems like `SomeModule` module is not imported to your unit test. But Yes unit test code would be useful. – Oleg Bondarenko Jul 12 '21 at 04:51

0 Answers0