0

I'm just starting with Angular2 but I try to test every component I write.

When I write component tests I have to initialize TestBed so component under test have all its (transitive) dependencies resolved.

Now I can think of three approaches

  1. Import whole module containing the component under test - it should declare or import all the required dependencies
  2. Explicitly declare all dependencies in test code
  3. Mock all dependencies - so they do not have its own dependencies

I think first solution may cause problems when I need to mock things that are already declared in main module. The second require me to manually change all dependent tests when I try add any new dependency to component. I did not test the third one so I do not know if it is doable.

What is the best way to handle this?

AGrzes
  • 209
  • 2
  • 5

1 Answers1

0

I implemented mocks of dependent components with the same selectors and inputs as original but with no logic.

That way I can test my component in isolation - check if it uses dependent components correctly but without concern of any transitive dependencies and other implementation details.

I was inspired by: angular2 test, how do I mock sub component

Community
  • 1
  • 1
AGrzes
  • 209
  • 2
  • 5
  • While this is one valid approach it has lots of limitations since you are just mocking the tag not replacing the class implementation itself. Something like this will not work. `@ViewChild(SubComponent) sc; then later call sc.callFn()`. Testbed injector will never find this class since the mock implementation have different class name. – Julian Mar 17 '17 at 10:29