【问题标题】:What's the difference between fixture.componentInstance and fixture.debugElement.componentInstance in Angular?Angular中的fixture.componentInstance和fixture.debugElement.componentInstance有什么区别?
【发布时间】:2019-09-30 18:59:19
【问题描述】:

使用 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

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

【问题讨论】:

    标签: angular unit-testing jasmine karma-runner


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2019-10-22
      • 1970-01-01
      • 2018-11-18
      • 1970-01-01
      • 2017-10-05
      • 2020-12-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      相关资源
      最近更新 更多