How to spyOn child components in Angular?

In the Angular tutorials they have an example of a HeroesComponent with a child HeroesListComponent.

The HeroesListComponent uses a HeroesService to getHeroes().

To spyOn getHeroes() inside heroes-list.component.spec.ts, we can do

spyOn(fixture.debugElement.componentInstance.heroesService, 'getHeroes').and.returnValue(Promise.resolve([]))

My question is: If I was inside of HeroesComponent spec file - heroes.component.spec.ts can I spyOn the child HeroesListComponent getHeroes() by doing something like this:

spyOn(fixture.debugElement.componentInstance.heroesListComponent.heroesService, 'getHeroes').and.returnValue(Promise.resolve([]))

Obviously this did not work, so I am asking if anyone can help me with a solution.

I want to do this, because I want to test if my <hero-list> loaded properly when I open HeroesComponent. This may seem repetitive as I already have a test to make sure HeroesListComponent works, but I think it's still an important test because I really want to make sure my HeroesComponent loaded properly and all of the child components too.

I also tried mocking the entire HeroesService inside of HeroesComponent, instead of using spyOn, but I can't get that syntax to work either. I don't know how to tell HeroesListComponent to use the mock object when i'm inside heroes.component.spec.ts

Thanks!



Read more here: https://stackoverflow.com/questions/45355421/how-to-spyon-child-components-in-angular

Content Attribution

This content was originally published by vinhboy at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: