首页 > 解决方案 > 将 nativeElement 转换为 Angular 中的 DebugElement

问题描述

我正在测试一个 Angular 组件,一切都很顺利,直到我遇到了一个我几天来一直试图解决的问题。我想要做的就是测试插入行时是否调用了方法“ajouterCompteurALaCampagne”,所以我尝试访问 dx-data-grid DOM 元素,以便发出事件“onRowInserting”,这就是问题发生的地方,我不能将该元素作为 DebugElement 访问,而只能作为 nativeElement 访问。因此,我无法发出 onRowInserting 事件并查看是否调用了该方法。所以我的问题是:“我可以对 nativeElement 进行某种转换,以便可以访问 DebugElement 属性吗?”

代码

<dx-tab-panel
  [height]="'auto'"
  [dataSource]="tabs"
  [selectedIndex]="0"
  [loop]="false"
  [animationEnabled]="true">

 
  <div *dxTemplate="let data of 'compteursTemplate'">
    <dx-data-grid
      #tabCompteurCampagne
      id = 'liste-compteur'
      [showBorders]="true"
      [dataSource]="listeCompteur"
      (onRowInserting)="ajouterCompteurALaCampagne($event)"
      (onRowRemoving)="supprimerCompteurCampagne($event)"
      (onRowUpdated)="modifierCompteurCampagne($event)">
    ...</dx-data-grid>
  ...</div>
...<dx-tab-panel>

打字稿代码

it("should call the method 'ajouterCompteurALaCampagne' once the event is emitted", async(()=>{
  let spy_ajouterCompteurALaCampagne = spyOn(component, "ajouterCompteurALaCampagne");
  let dxTabPanelElement = fixture.debugElement.query(
    By.directive(DxTabPanelComponent)
  );
 let dxGridElement = dxTabPanelElement.nativeElement.querySelector('#liste-compteur');
  dxGridElement.dispatchEvent(new Event("rowInserting")); //the event is not emmited
  expect(spy_ajouterCompteurALaCampagne).toHaveBeenCalledTimes(1);
  }));
 });

标签: angulartypescriptjasminekarma-jasmineangular-test

解决方案


我已经找到了解决这个问题的方法,谢谢你们的回答。这是代码:

it("should call the method 'ajouterCompteurALaCampagne' once the event is emitted", async(()=>{
let spy_ajouterCompteurALaCampagne = spyOn(component, "ajouterCompteurALaCampagne");
let dxGridElement = fixture.nativeElement.querySelector("dx-data-grid");
console.log(dxGridElement);
dxGridElement.dispatchEvent(new Event("onRowInserting"));
fixture.detectChanges();
expect(spy_ajouterCompteurALaCampagne).toHaveBeenCalledTimes(1);

}));

我希望这对将来的某人有所帮助。


推荐阅读