'react testing library: can't acquire context from the given item

I have this component, which uses react-chartjs-2 to render a Doughnut chart:

const CompliancyChart = ({data}): JSX.Element => {
...
   return (
     <ChartStyled>
          {chartPlugins && chartData && (
            <Doughnut
              aria-label="Compliancy Chart"
              data={chartData}
              options={chartOptions}
              plugins={chartPlugins}
            />
          )}
        </ChartStyled>
    );
};

And I have a test file for this component which has this assertion:

describe('Chart component', () => {
  afterEach(() => {
    cleanup();
  });

  test('should render without errors', async () => {
    render(<CompliancyChart data={mockCompliancyChartData} />, {});
    const compliancyChart = await screen.findByRole('img', {
      name: 'Compliancy Chart',
    });
    expect(compliancyChart).toBeDefined();
  });
});

This test is working fine, but I keep getting this error in the test console:

Failed to create chart: can't acquire context from the given item

The only solution I could find online is to use:

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

Which in this case my test fails, since I can't test against canvas inside the screen container: (https://github.com/reactchartjs/react-chartjs-2/issues/155#issuecomment-821322545)

How can I solve this issue?



Solution 1:[1]

Since Jest uses jsdom, there are some browser APIs that are not available on this environment. Its probably you are getting this error

Failed to create chart: can't acquire context from the given item

because HTMLCanvasElement.getContext() is not present.

You can get rid of that error by installing canvas as dev dependency. Jsdom includes support for using this library if it is included as a dependency in your project. See canvas-support

npm i canvas --save-dev

If you get an error related to ResizeObserver, in that case you can mock it and your test will run fine.

window.ResizeObserver = function () {
  return {
    observe: jest.fn(),
    unobserve: jest.fn(),
    disconnect: jest.fn(),
  };
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 lissettdm