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?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With