使用 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
类型的componentInstance
而fixture.componentInstance
为您提供T
类型的componentInstance
。