Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock document.getElemetById('.form').getContext('2d') using sinon

I'm using karma, mocha, chai, sinon and Angular mocks for my unit testing. In my $scope.loadChart, I'm drawing a chart in my canvas tag. I'm using http://www.chartjs.org/ to draw the charts.

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

like image 677
Norbs Knight Avatar asked May 26 '15 08:05

Norbs Knight


2 Answers

You could stub document.getElementById and have it return a canvas object that is stubbed and programmed to return a context object of your choosing...

//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);
like image 128
philipisapain Avatar answered Nov 13 '22 09:11

philipisapain


You should wrap that DOM access in a method. Then you can mock that 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 the usual way with sinon.

like image 1
Martin Avatar answered Nov 13 '22 10:11

Martin