angular - 如何在 Angular 中测试离子 Web 组件
问题描述
我在为我的一个使用 ionic4-components 的组件编写测试时遇到了问题。
我有一个非常简单的组件,如下所示:
export class SelectedBadgetComponent implements OnInit, OnChanges {
@Input() public all: number = 0;
@Input() public selected: number = 0;
public color: string = "light"
constructor() {
}
update() {
if(this.selected > 0) {
this.color = 'secondary'
return
}
this.color = 'light'
return;
}
ngOnInit(){
this.update();
}
ngOnChanges(){
this.update();
}
}
模板:
<div>
<ion-badge [color]="color" item-end>
{{ selected }} / {{ all }}
</ion-badge>
</div>
该组件用于显示所选项目的徽章。像这样 [ 2 / 10 ] (选择了十个项目中的两个)。如果所选计数大于 1,它还会更改类。
我对此组件的测试在ionic3中运行良好:
beforeEach(() => {
fixture = TestBed.createComponent(SelectedBadgetComponent);
component = fixture.componentInstance;
component.all = 5
component.selected = 1
fixture.detectChanges();
});
it('should have the class "ion-color-secondary"', () => {
const badge = fixture.nativeElement.querySelector('ion-badge');
expect(badge.classList.contains('ion-color-secondary')).toBe(true);
});
问题出现在预期中。永远不会设置给定的类。当我调试这个测试时,我可以看到,在检查期望时,实际上没有设置类,但过了一段时间,它被设置了。我猜这是因为测试不会等到呈现 web 组件“ion-badge”。
如何设置我的测试以等待模板中的所有子项都完全呈现?
我尝试了没有效果的 fixture.whenStable() 。此外,我将 CustomElement Schema ( schemas: [CUSTOM_ELEMENTS_SCHEMA]
) 添加到我的测试中,这也不是很有帮助。
编辑:
有了这个 hack,测试就可以工作了——但是,我认为这不是一个合适的解决方案:
it('should have the class "ion-color-secondary"', async(() => {
setTimeout(x => {
const badge = fixture.nativeElement.querySelector('ion-badge');
expect(badge.classList.contains('ion-color-secondary')).toBe(true);
}, 2000)
}));
解决方案
推荐阅读
- mysql - 连接表上的 MySQL 强制索引 - 当优化器首先从连接表中选择时
- php - fetch_object while 循环中的 if 语句
- c# - System.Xml.Serialization.IXmlSerializable'
- vhdl - 模拟 LVDS 软核 IP
- python - 如何更新混合了多个数据模型的 algolia 索引
- javascript - D3Plus 散点图 X axix 字符串
- excel - 如何基于另一个 Hlookup 进行 Hlookup?
- rest - websphere中的Spring Restful服务
- angular - 我应该如何将 Office js 函数中的值传递给角度语法函数
- css - 如何在移动设备上重新排序 div 类?