How to unit test statement 'chart.chart.update()' in jasmine?

Viewed 2430

I have a Angular 4 app and I am using angular2-chartjs to plot charts in my application.

In the component, I have imported following:

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

Created a chart property:

@ViewChild(ChartComponent) chart: ChartComponent;

Now I pass this chart object to a method of a service from the component:

this.chartService.updateChartWith(this.chart);

Now in chart service, I am updating the chart:

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

Chart works perfectly. I want to write unit test for updateChartWith() method in Jasmine. How to write a unit test for chart.chart.update() line of code in Jasmine?

1 Answers

Unless I am missing something, I think this is pretty straightforward. You don't want to unit test someone else's code (in this case chart.js), so you might simply want to determine if chart.chart.update() is being called within chart service. I would set up a spy for this, something like the following:

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