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

梦想的初衷 提交于 2021-01-20 18:50:27

问题


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!


回答1:


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

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



回答2:


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';



回答3:


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




回答4:


Both answers above work. However, just wanted to add that in case of create-react-app, it doesn't support the 'setupFiles' required by jest conf in package.json for jest-canvas-mock.

I got around this by adding the import statement in each of the test files that were invoking the canvas element(in my case 3). Then, I moved the import statement to the setupTests.js file and removed that requirement as well.



来源:https://stackoverflow.com/questions/48828759/unit-test-raises-error-because-of-getcontext-is-not-implemented

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!