How to Convert ChartModule to Spectator for Easy Testing

Create a Manual Mock of PrimeNg's ChartModule for Tests

How to Convert ChartModule to Spectator for Easy Testing

Photo by Andrew Neel on Unsplash

Recently, we migrated some libraries to Jest and encountered issues with the tests we had created for a component that used the PrimeNg ChartModule (which, is a wrapper for ChartJS).

At first glance, we identified that the issue stemmed from Jest's lack of support for Canvas, MutationObserver, and other browser APIs necessary to run the tests (Karma uses a real browser to run the test, but Jest does not).

Finally, we realized that we had two options: either mock the browser APIs or mock the ChartModule. Since we were using Spectator for testing, we managed to do this easily (after much searching, test, and error).

Firstly, we created a mock to replace what we needed. In this case, since PrimeNG still uses modules, we created a component and a test module specifically for this purpose.

// Component containing chart.js in PrimeNG's ChartModule
    selector: 'p-chart',
    template: 'PrimeNg Chart - mocked component'
class MockUIChart {
    // Here we add all the inputs that we are using
    data: unknown;
    options: unknown;
    plugins: unknown;
// Module that imports and exports the component
    declarations: [MockUIChart],
    exports: [MockUIChart]
export class MockChartModule {}

In our test, we do the following:

describe('ComponentStandalone', () => {
    let spectator: Spectator<ComponentStandalone>;

    const createComponent = createComponentFactory({
        component: ComponentStandalone,
        overrideComponents: [
                    remove: { imports: [ChartModule] },
                    add: { imports: [MockChartModule] }

With this, we prevent the p-chart component from attempting to instantiate ChartJS in the ngAfterViewInit, which was the root cause of all the Jest warnings.

Do you have any experience with Jest, PrimeNG, or testing tools that you'd like to share? Leave your comments below!

Did you find this article valuable?

Support Arcadio Quintero by becoming a sponsor. Any amount is appreciated!