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

2

7

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();
  });
Sirois answered 28/12, 2018 at 16:26 Comment(0)
S
28

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
}));
Sirois answered 28/12, 2018 at 16:45 Comment(4)
How to mock functions which are in options of Line chart. As per my requirement I have written custom functions and attached it to onHover and animation onProgress. How to mock those functions?As of now my code coverage is very low. Please help.Role
@TestMail I'm not sure, I suggest creating a new question and tag with chart.jsSirois
It didn't work for me.Nictitate
@Nictitate feel free to create a new question with your specific details and share the link here. I'm happy to help.Sirois
V
0

The answer of CWSites is not completely wrong but does not work in all test cases because with null as value no element is rendered with which you can test.

The following solution works for me for all tests in relation to react-chartjs-2.

jest.mock('react-chartjs-2', () => {
  const { forwardRef } = require('react');
  const Line = forwardRef((props, ref) => <div ref={ref} {...props}></div>);
  return {
    Line,
  };
});
Vedis answered 19/12, 2023 at 9:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.