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



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

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

但是,我也可以直接在fixture上使用componentInstance属性,如下所示:

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

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

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

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

另外:fixture.debugElement.componentInstance给出了any类型的componentInstancefixture.componentInstance为您提供T类型的componentInstance

最新更新