unit test raises error because of .getContext() is not implemented

My team is using create-react-app and we had previously addressed this problem by adding the npm package jest-canvas-mock. Now after upgrading to react-scripts 3.4.1, we also had to add a specific import to our src/setupTests.ts file:

import 'jest-canvas-mock';

You can create your own mock of the function in a jest setup script

HTMLCanvasElement.prototype.getContext = () => { 
  // return whatever getContext has to return
};

I had similar problem with my Jest tests, and solved it by installing jest-canvas-mock.


I've solved it by installing jest-canvas-mock

npm i --save-dev jest-canvas-mock

And adding this configuration on package.json

{
  "jest": {
    "setupFiles": [
      "jest-canvas-mock"
    ],
  }
}