【问题标题】:How to test angular component which has setTimeout inside ngOnInt using jasmine如何使用茉莉花测试在ngOnInt中具有setTimeout的角度组件
【发布时间】: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


    【解决方案1】:

    这个问题很可能与 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();
      ...
    })); 
    

    【讨论】:

      猜你喜欢
      • 2012-06-12
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 2016-06-14
      • 1970-01-01
      • 2017-08-07
      相关资源
      最近更新 更多