본문 바로가기
Front-End/React

[React | Jest] unit test raises error because of .getContext() is not implemented

by 흐암졸령 2022. 7. 20.
반응형

[ 문제점 ]

 jest를 사용하여 테스트 하는 과정에서 canvas element가 있었다. 이를 조작하는 메소드 .getContext()를 사용하는데 여기서 에러가 발생하였다. canvas를 테스트 하는 것은 아니기에 테스트는 성공하였지만, 하는 과정에 에러가 났다.

 

[ 시행착오 ]

 구글에 검색해보니 jest-canvas-mock을 설치, createElement 함수를 jest.fn()을 사용해서 조작하기 여러 방법을 찾았다. 그러나 jest-canvas-mock은 install 하니 .getContext()까지는 에러가 없이 되지만 undefiend가 반환이 되면서 이후 과정에서 다시 에러가 발생하였다.

 

 createElement를 조작하는 방식은 마찬가지로 .getContext() 까지는 작동되지만 다른 부분에 영향이 갔는지, 버튼 element fireEvent를 하는 부분에서 에러가 발생했다.

 

[ 해결방법 ]

 결국 canvas 라이브러리를 install 하여서 오류는 해결하였다.

npm install canvas

 

[ Reference ]

 

How to add <canvas> support to my tests in Jest?

In my Jest unit test I am rendering a component with a ColorPicker. The ColorPicker component creates a canvas object and 2d context but returns 'undefined' which throws an error "Cannot set property 'fillStyle' of undefined

www.querythreads.com

 

반응형

댓글