Yulian
Yulian

Reputation: 6759

What's the difference between fixture.componentInstance and fixture.debugElement.componentInstance in Angular?

When performing unit tests with Angular, you usually use a ComponentFixture to get a reference of a component. The auto-generated unit-tests from the Angular CLI give you something like the following:

const fixture = TestBed.createComponent(TestComponent);
const component = fixture.debugElement.componentInstance;

However, I can also use the componentInstance property directly on fixture like so:

const fixture = TestBed.createComponent(TestComponent);
const component = fixture.componentInstance; // note that I don't reference `debugElement` here

What's the difference between the two and when should I use one over the other?

Upvotes: 8

Views: 6907

Answers (1)

Suyash Gupta
Suyash Gupta

Reputation: 576

This will give you much clearer picture: https://angular.io/guide/testing#debugelement

So, a short answer would be if you are running tests on a non-browser platform that doesn't have a DOM or whose DOM-emulation doesn't support the full HTMLElement API, then you MUST use fixture.debugElement.componentInstance, otherwise your tests would fail. Else, it doesn't matter, you can use either of those if you are using browser.

Also: fixture.debugElement.componentInstance gives componentInstance of type any whereas fixture.componentInstance gives you componentInstance of type T.

Upvotes: 12

Related Questions