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


in jest unit test rendering component colorpicker. colorpicker component creates canvas object , 2d context returns 'undefined' throws error "cannot set property 'fillstyle' of undefined"

if (typeof document == 'undefined') return null; // dont render on server var canvas = document.createelement('canvas');  canvas.width = canvas.height = size * 2; var ctx = canvas.getcontext('2d'); // returns 'undefined' ctx.fillstyle = c1; // "cannot set property 'fillstyle' of undefined" 

i'm having troubles figuring out why can't 2d context. maybe there issue test config?

"jest": {   "scriptpreprocessor": "<rootdir>/node_modules/babel-jest",   "unmockedmodulepathpatterns": [     "<rootdir>/node_modules/react",     "<rootdir>/node_modules/react-dom",     "<rootdir>/node_modules/react-addons-test-utils",     "<rootdir>/node_modules/react-tools"   ],   "modulefileextensions": [     "jsx",     "js",     "json",     "es6"   ],   "testfileextensions": [     "jsx"   ],   "collectcoverage": true } 

it's because test doesn't run in real browser. jest uses jsdom mocking necessary parts of dom able run tests in node, avoiding style calculation , rendering browser do. cool because makes tests fast.

on other hand, if need browser apis in components, it's more difficult in browser. luckily, jsdom has support canvas. have configure it:

jsdom includes support using canvas package extend <canvas> elements canvas api. make work, need include canvas dependency in project, peer of jsdom. if jsdom can find canvas package, use it, if it's not present, <canvas> elements behave <div>s.

alternatively, replace jest browser-based test runner karma. jest pretty buggy anyway.


Comments