Search code examples
reactjschart.jsjestjsenzyme

Testing Chart.js with Jest/Enzyme - Failed to create chart: can't acquire context from the given item


My test passes just fine, however I get the following error.

  console.error node_modules/chart.js/src/core/core.controller.js:127
  Failed to create chart: can't acquire context from the given item

I've looked around and the closest answer I can find is mentioned here: https://github.com/chartjs/Chart.js/issues/3696 but it looks as if the error is an intentional way of failing gracefully without causing tests to fail.

I'm using Jest/Enzyme to write a test that checks which options are being passed to my chart component.

  it('xAxis set to false', () => {
    const wrapper = mount(<Chart xAxis='false' chart={parentState.chart} />);
    const BarChart = wrapper.find('Bar');

    console.log(BarChart.props().options);
    expect(BarChart.props().options.scales.xAxes[0].display).toEqual(false);

    wrapper.unmount();
  });

Solution

  • I always feel pretty silly when I spend a day researching my question prior to asking it, then I figure it out on my own 15 minutes later...

    Rather than deleting this I'm going to post the answer for anyone else that may have a similar issue. I realized that I'm using a wrapper for chart.js, react-chartjs-2 so I searched on their github and sure enough someone had already posted the exact answer to my question. https://github.com/jerairrest/react-chartjs-2/issues/155

    Adding the following mock to my setup-jest.js file resolved the console errors I was getting.

    jest.mock('react-chartjs-2', () => ({
      Bar: () => null
    }));