0

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?

2
  • do you add .hero class to a component using @HostBinding ? Or you use it in @Component selector? Commented Nov 21, 2016 at 21:17
  • The complete example from the docs is here: angular.io/resources/live-examples/testing/ts/… Looks like it uses the component selector. Commented Nov 21, 2016 at 21:36

1 Answer 1

3

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));
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.