4

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?

DR39
  • 363
  • 1
  • 16

1 Answers1

3

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();
});
dmcgrandle
  • 4,904
  • 1
  • 14
  • 34
  • It throws this error - TypeError: undefined is not an object (evaluating 'chart.chart.options') – DR39 Oct 26 '18 at 07:54
  • So there is also an 'options' variable or method in the chart service which you are using in your code? That was not clear from your original question. In order to properly mock a service, you need to provide a mock of all the variables your code actually makes use of. Look for all those additional things and add them as spies or mocks, as I showed with chart.chart.update(). Or post your entire **updateChartWith()** function and I'll update my answer to help. – dmcgrandle Oct 26 '18 at 14:59
  • Oh Yes, I mocked the chart options and set it to chartMock.chart.options and it works :) !! Great.. Thanks a ton! – DR39 Oct 29 '18 at 04:44