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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With