【问题标题】:How to unit test statement 'chart.chart.update()' in jasmine?如何在茉莉花中对语句“chart.chart.update()”进行单元测试?
【发布时间】:2019-03-27 10:47:07
【问题描述】:

我有一个 Angular 4 应用程序,我正在使用 angular2-chartjs 在我的应用程序中绘制图表。

在组件中,我导入了以下内容:

import { ChartComponent } from 'angular2-chartjs';
import { ChartModule } from 'angular2-chartjs';

创建了图表属性:

@ViewChild(ChartComponent) chart: ChartComponent;

现在我将这个图表对象从组件传递给服务的方法:

this.chartService.updateChartWith(this.chart);

现在在图表服务中,我正在更新图表:

public updateChartWith(chart: ChartComponent) {
   /** Some code **/
    chart.chart.update();
}

图表完美运行。我想为 Jasmine 中的 updateChartWith() 方法编写单元测试。如何为 Jasmine 中的 chart.chart.update() 行代码编写单元测试?

【问题讨论】:

    标签: angular jasmine chart.js


    【解决方案1】:

    除非我遗漏了什么,否则我认为这很简单。您不想对其他人的代码进行单元测试(在本例中为 chart.js),因此您可能只想确定是否在图表服务中调用了 chart.chart.update()。我会为此设置一个间谍,如下所示:

    it('updateChartWith() should call chart.update()', () => {
        chartSpy = jasmine.createSpyObj({ update: null });
        chartMock = {chart: chartSpy};
        service.updateChartWith(chartMock);
        expect(chartSpy.update).toHaveBeenCalled();
    });
    

    【讨论】:

    • 它抛出这个错误 - TypeError: undefined is not an object (evalating 'chart.chart.options')
    • 那么您在代码中使用的图表服务中还有一个“选项”变量或方法?您最初的问题并不清楚。为了正确地模拟服务,您需要提供代码实际使用的所有变量的模拟。寻找所有这些额外的东西并将它们添加为间谍或模拟,正如我在 chart.chart.update() 中展示的那样。或者发布您的整个 updateChartWith() 函数,我会更新我的答案以寻求帮助。
    • 哦,是的,我模拟了图表选项并将其设置为 chartMock.chart.options 并且它有效 :) !!太好了.. 非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 1970-01-01
    • 2022-01-23
    • 2020-11-25
    • 2015-08-25
    • 2020-08-19
    相关资源
    最近更新 更多