Mock document.getElemetById ('. Form'). GetContext ('2d') using sinon

I am using karma, mocha, chai, sinon and Angular mocks for my unit testing. In my $ scope.loadChart I am drawing a chart in a canvas tag. I am using http://www.chartjs.org/ for drawing diagrams.

Chartjs requires this piece of code, document.getElemetById ('# canvas'). getContext ('2d') . How do I do this in Sinon? My test is stuck at this line.

+3


source to share


2 answers


You can stub out document.getElementById

and return to it a canvas object that will be shaded and programmed to return a context object of your choice ...



//Create your fake canvas and context objects
var canvas = document.createElement('canvas');
var fakeContext = {}; //Replace this with whatever you want your fake context to be

//Have `canvas.getContext('2d')` return your fake context
sinon.stub(canvas, 'getContext');
canvas.getContext.withArgs('2d').returns(fakeContext);

//Have `document.getElementById('canvas')` return your canvas
sinon.stub(document, 'getElementById');
document.getElementById.withArgs('canvas').returns(canvas);

      

+4


source


You have to wrap this DOM access in a method. Then you can mock this method.

var DomAccess = function() {} 
DomAccess.prototype.get2dCanvas = function() {
    return document.getElementById('#canvas').getContext('2d');
}

var domAccess = new DomAccess();
var context = domAccess.get2dContext();

      



You can now mock this class in the usual way using sinon.

+1


source







All Articles