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

时间:2019-09-30 18:59:19

标签: angular unit-testing jasmine karma-runner

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

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

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

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

两者之间有什么区别?何时应该使用另一种?

1 个答案:

答案 0 :(得分:3)

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

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

ext.kotlin_version = '1.3.41' 给出类型为fixture.debugElement.componentInstance的{​​{1}} 而fixture.debugElement.componentInstance为您提供componentInstance类型的any