Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am writing tests using Jest for components that use canvas elements. I keep getting an error when I run my tests that looks like this.

Error: Not implemented: HTMLCanvasElement.prototype.getContext (without installing the canvas npm package) 

From my understanding Jest uses jsdom for its testing and that jsdom is compatible with canvas if you install the canvas or canvas-prebuilt packages.

I have tried installing each of these packages and neither of them have resolved the error. The only thing that I think could be going wrong is that jsdom cannot find the canvas or canvas-prebuilt packages. Does anyone know a way to fix this error or test to see if jsdom is finding the other packages? Thanks a lot!

like image 478
lpie88 Avatar asked Feb 16 '18 14:02

lpie88


2 Answers

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'; 
like image 153
PaulMest Avatar answered Sep 20 '22 18:09

PaulMest


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

HTMLCanvasElement.prototype.getContext = () => {    // return whatever getContext has to return }; 
like image 26
Red Mercury Avatar answered Sep 19 '22 18:09

Red Mercury