Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 464
Yulian Avatar asked Dec 31 '22 15:12

Yulian


1 Answers

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.

like image 190
Suyash Gupta Avatar answered Jan 03 '23 04:01

Suyash Gupta