Angular 中的 fixture.componentInstance 和 fixture.debugElement.componentInstance 有什么区别?

Yul*_*ian 3 unit-testing jasmine karma-runner angular

使用 Angular 执行单元测试时,您通常使用 aComponentFixture来获取组件的引用。来自 Angular CLI 的自动生成的单元测试为您提供如下内容:

const fixture = TestBed.createComponent(TestComponent);
const component = fixture.debugElement.componentInstance;
Run Code Online (Sandbox Code Playgroud)

但是,我也可以像这样componentInstance直接使用该属性fixture

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

两者之间有什么区别,我什么时候应该使用一个而不是另一个?

Suy*_*pta 7

这会给你更清晰的画面:https : //angular.io/guide/testing#debugelement

因此,简短的回答是,如果您在没有 DOM 或其 DOM 模拟不支持完整 HTMLElement API 的非浏览器平台上运行测试,那么您必须使用fixture.debugElement.componentInstance,否则您的测试将失败。否则,没关系,如果您使用浏览器,您可以使用其中任何一个。

另外: fixture.debugElement.componentInstance给出componentInstance类型anyfixture.componentInstance给你componentInstance类型T