Angular 如何使用jasmine测试在ngOnInt中设置超时的角度分量
我正在用jamsine编写单元测试,并使用nvd3显示图表 图表.组件.tsAngular 如何使用jasmine测试在ngOnInt中设置超时的角度分量,angular,jasmine,karma-jasmine,Angular,Jasmine,Karma Jasmine,我正在用jamsine编写单元测试,并使用nvd3显示图表 图表.组件.ts export class ChartComponent implements OnInit { chartConfigs = []; @Input chartDetails; ngOnInit() { if(chartDetails.data) { setTimeout(() => { this.chartConf
export class ChartComponent implements OnInit {
chartConfigs = [];
@Input chartDetails;
ngOnInit() {
if(chartDetails.data) {
setTimeout(() => {
this.chartConfigs.push('1');
});
}
}
}
it('shall render the chart', fakeAsync(() => {
component.chartComponent.data = [
{ x: 0, y: 3.160340011 },
{ x: 1, y: 5.16379641 },
{ x: 2, y: 1.16379641 },
{ x: 3, y: -1.16379641 },
{ x: 4, y: 0.379641 },
{ x: 5, y: 0 },
{ x: 6, y: -15.16379641 },
{ x: 7, y: -111.16379641 }
]];
fixture.detectChanges();
expect(component.chartComponent.chartConfigs.length).toBe(0);
tick();
fixture.detectChanges();
const chartElement = fixture.debugElement.nativeElement.querySelector('nvd3');
expect(chartElement.hasChildNodes()).toBeTruthy(); // error: Cannot read property 'hasChildNodes' of null
expect(component.chartComponent.chartConfigs.length).toBe(1); // error: length is 0
}));
图表组件规范ts
export class ChartComponent implements OnInit {
chartConfigs = [];
@Input chartDetails;
ngOnInit() {
if(chartDetails.data) {
setTimeout(() => {
this.chartConfigs.push('1');
});
}
}
}
it('shall render the chart', fakeAsync(() => {
component.chartComponent.data = [
{ x: 0, y: 3.160340011 },
{ x: 1, y: 5.16379641 },
{ x: 2, y: 1.16379641 },
{ x: 3, y: -1.16379641 },
{ x: 4, y: 0.379641 },
{ x: 5, y: 0 },
{ x: 6, y: -15.16379641 },
{ x: 7, y: -111.16379641 }
]];
fixture.detectChanges();
expect(component.chartComponent.chartConfigs.length).toBe(0);
tick();
fixture.detectChanges();
const chartElement = fixture.debugElement.nativeElement.querySelector('nvd3');
expect(chartElement.hasChildNodes()).toBeTruthy(); // error: Cannot read property 'hasChildNodes' of null
expect(component.chartComponent.chartConfigs.length).toBe(1); // error: length is 0
}));
chart.component.html
<div *ngIf="chartConfigs.length" >
<nvd3 [chartConfig]="chartConfigs[0]" [data]="[chartDetails.data]"></nvd3>
</div>
出现错误是因为chartElement为null。我调试了代码,发现nvd3没有得到渲染请帮我解决这个问题。
注意:我尝试在spec.ts中使用setTimeOut,测试用例通过了,但我不想在spec文件中使用setTimeOut()。问题很可能与
setTimeOut
方法无关,因为在设置单元测试的情况下,它从未被调用
setTimeout
仅在chartDetails.data
已定义的情况下调用,但情况并非如此
作为解决方案的第一步,您可以尝试如下初始化组件:
it('shall render the chart', fakeAsync(() => {
component.chartDetails = {
data: [
{ x: 0, y: 3.160340011 },
{ x: 1, y: 5.16379641 },
{ x: 2, y: 1.16379641 },
{ x: 3, y: -1.16379641 },
{ x: 4, y: 0.379641 },
{ x: 5, y: 0 },
{ x: 6, y: -15.16379641 },
{ x: 7, y: -111.16379641 }
]
};
fixture.detectChanges();
...
}));