You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The issue with the current way of doing it, is that the change is not global; i.e. the mock canvas object is reset during regular usage by any component. This makes it kind of useless for unit tests.
The following works for me, I hope you can adapt something similar:
varmyHackedInCanvas;// Use one global canvas instance for all calls to createElement('canvas');functionreplaceCanvasContext(el){// The previous export}/** * Overrides document.createElement(), in order to supply a custom canvas element. * * In the canvas element, getContext() is overridden in order to supply a simple * mock object for the 2D context. For all other elements, the call functions unchanged. * * The override is only done if there is no 2D context already present. * This allows for normal running in a browser, and for node.js the usage of 'canvas'. * * @param {object} the current global window object. This can possibly come from module 'jsdom', * when running under node.js. */functionmockify(window){vard=window.document;varf=window.document.createElement;// Check if 2D context already present. That happens either when running in a browser,// or this is node.js with 'canvas' installed. varctx=d.createElement('canvas').getContext('2d');if(ctx!==null&&ctx!==undefined){//console.log('2D context is present, no need to override');return;}window.document.createElement=function(param){if(param==='canvas'){if(myHackedInCanvas===undefined){myHackedInCanvas=f.call(d,'canvas');replaceCanvasContext(myHackedInCanvas);}returnmyHackedInCanvas;}else{returnf.call(d,param);}};}module.exports=mockify;
This does change the object to pass in, so in a sense breaking. I personally do not care, but you may think different. Perhaps you know a better way.
The text was updated successfully, but these errors were encountered:
The issue with the current way of doing it, is that the change is not global; i.e. the mock canvas object is reset during regular usage by any component. This makes it kind of useless for unit tests.
The following works for me, I hope you can adapt something similar:
This does change the object to pass in, so in a sense breaking. I personally do not care, but you may think different. Perhaps you know a better way.
The text was updated successfully, but these errors were encountered: