[Chartjs]-React testing library: can't acquire context from the given item

6👍

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(),
  };
};

Leave a comment