在Angular中将一个nativeElement转换为DebugElement



我正在测试一个角度组件,一切都很顺利,直到遇到一个我已经尝试解决了好几天的问题。我想做的只是测试方法";ajouterCompteurALaCampagne";是在插入行时调用的,所以我试图访问dx数据网格DOM元素,这样我就可以发出事件";onRowInserting";,这就是问题发生的地方,我不能作为DebugElement访问该元素,只能作为nativeElement访问。因此,我无法发出onRowInserting事件并查看是否调用了该方法。所以我的问题是:;我可以对nativeElement进行某种类型的转换吗?这样我就可以访问DebugElement属性了">

HTML代码

<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);
}));
});

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

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);

}));

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

为什么不能使用debugElement?在这种情况下,我认为你可以使用triggerEventHandler,我认为它来自Angular。

试试这个:

it("should call the method 'ajouterCompteurALaCampagne' once the event is emitted", async(()=>{
let spy_ajouterCompteurALaCampagne = spyOn(component, "ajouterCompteurALaCampagne");
// use fixture.
let dxGridElement = fixture.debugElement.query(By.css('dx-data-grid'));
dxGridElement.triggerEventHandler('onRowInserting', { /* here you can mock the $event object */ });
expect(spy_ajouterCompteurALaCampagne).toHaveBeenCalledTimes(1);
}));

最新更新