Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 995
Renaud is Not Bill Gates Avatar asked Dec 07 '25 10:12

Renaud is Not Bill Gates


1 Answers

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(),
  };
};
like image 121
lissettdm Avatar answered Dec 09 '25 00:12

lissettdm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!