【问题标题】:Angular 7 Jasmine unit test: how to get component NativeElement?Angular 7 Jasmine 单元测试:如何获取组件 NativeElement?
【发布时间】:2019-03-18 19:30:24
【问题描述】:

在我的主要组件 html 中有一个 my-grid 组件

main.component.html

 <my-grid
    id="myDataGrid"
    [config]="gridOptions"
 </my-grid>

在 main.component.specs.ts 我怎样才能得到my-grid NativeElement?

到目前为止,我有 1 个测试可以检查网格是否正在呈现

it('should render grid', () => {
     fixture = TestBed.createComponent(MainComponent);
     const compiled = fixture.debugElement.nativeElement;
     expect(compiled.querySelector('my-grid')).not.toBe(null);
})

【问题讨论】:

  • 我认为compiled.querySelector('my-grid') 是原生元素?我错过了什么?

标签: javascript angular jasmine karma-jasmine


【解决方案1】:

您可以使用debugElement 来查询您的组件:

示例

const debugElement = fixture.debugElement.query(By.directive(MyGridComponent));
const nativeElement = debugElement.nativeElement;
const component: MyGridComponent = debugElement.componentInstance;

【讨论】:

  • 如果我查询组件本身,我会得到null
猜你喜欢
  • 2017-04-04
  • 1970-01-01
  • 2017-03-06
  • 2018-10-28
  • 2020-11-03
  • 2017-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多