【发布时间】:2020-09-06 06:40:02
【问题描述】:
我正在用 jamsine 编写单元测试,我正在使用 nvd3 来显示图表。
chart.component.ts
export class ChartComponent implements OnInit {
chartConfigs = [];
@Input chartDetails;
ngOnInit() {
if(chartDetails.data) {
setTimeout(() => {
this.chartConfigs.push('1');
});
}
}
}
chart.component.spec.ts
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>
我收到以下错误:
TypeError: Cannot read property 'hasChildNodes' of null
错误即将到来,因为 chartElement 以 null 的形式出现。我调试了代码,发现 nvd3 没有被渲染。 请帮我解决这个问题。
注意:我尝试在 spec.ts 中使用 setTimeOut 并且测试用例通过了,但我不想在 spec 文件中使用 setTimeout()。
【问题讨论】:
标签: angular jasmine karma-jasmine