How to test Angular component that uses Chart.js

Georgi Parlakov
1 min readMay 22, 2022

TL;DR

Wrap the chart constructor in a function and provide that via an InjectionToken (or a service).

The working code is over at StackBlitz.

What’s the issue?

When using chart.js we need to instantiate a Chart instance like this this.chart = new Chart(ctx, options).

Ok that works, but what test can we write against that?

We can check if the chart constant is actually populated and of the type Chart. That’s pretty much it. But if we had some functionality tied to it, like do something interesting when user clicks on a point from the chart, there’s not a lot we can actually test as it stands:

- We can’t verify that the ctx and options are what we expect them to be.

- We can’t verify that callbacks on chart events behave as we’d like them to.

Details

The detailed article :

It walks through the solution 🪜step by step and provides a couple of bonuses. ⚠️Warning It’s behind a paywall.️ ⚠️

--

--

Georgi Parlakov

Angular and DotNet dev. RxJs explorer. Testing proponent. A dad. Educative.io course author. https://gparlakov.github.io/