Allen
Allen

Reputation: 3374

Testing: How to lookup component instance for sub-component

I have a component I am testing that has a large number of subcomponents. In my test I would like to get a reference to the objects for some of these subcomponents to I can check their properties to see if they are behaving correctly and to interactively cause them to change. (ex: check what state a segment button component is in or manually force it into a different state)

I have been looking at the testing documentation for angular, but I can't see a way to do this. I had expected that maybe I could do a query on the fixture's debugElement to find the debug element for the subcomponent and then access it's componentInstance, but that seems to always be null.

For example looking at the docs: https://angular.io/docs/ts/latest/guide/testing.html#!#component-inside-test-host

beforeEach( async(() => {
  TestBed.configureTestingModule({
   declarations: [ DashboardHeroComponent, TestHostComponent ], //     declare both
 }).compileComponents();
}));

beforeEach(() => {
  // create TestHostComponent instead of DashboardHeroComponent
  fixture  = TestBed.createComponent(TestHostComponent);
  testHost = fixture.componentInstance;
  heroEl   = fixture.debugElement.query(By.css('.hero')); // find hero
  fixture.detectChanges(); // trigger initial data binding
});

I would like a way to get a reference to the DashboardHeroComponent inside the TestHostComponent. Does anyone know how to do this?

Upvotes: 0

Views: 1362

Answers (1)

RomanHotsiy
RomanHotsiy

Reputation: 5138

Class .hero is set not on a component but on inner div of component view. That's why it doesn't have componentInstance attached

To get componentInstance use an appropriate selector (in this case tag name - you can find this in property selector of @Component annotation):

heroEl = fixture.debugElement.query(By.css('dashboard-hero')); // find hero

or use By.directive

heroEl = fixture.debugElement.query(By.directive(DashboardHeroComponent));

Upvotes: 3

Related Questions