angular - 将 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);
}));
});
解决方案
我已经找到了解决这个问题的方法,谢谢你们的回答。这是代码:
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);
}));
我希望这对将来的某人有所帮助。
推荐阅读
- android - 如何在 React Native for Android 中为文本输入定义插入符号颜色?
- wildfly-swarm - Wildfly Swarm 2018.5.0 不启动 HTTPS 监听
- python - 将参数传递给python中的装饰器
- bash - 如何在 curl 请求中扩展文件名
- vba - 如果语句在 VBA 中没有返回正确的值
- ios - 在 Swift 中同时 Deinit 两个 ViewController
- python-3.x - 无法单击使用 selenium 和 python 进行抓取的按钮
- octobercms - 如何在十月 CMS 中显示下一个和上一个项目
- django - 按组枚举查询集中的实例
- pyspark - 如何使用 Pyspark / Dataproc 监控 jvm 堆大小