My tests fails for the following reason:
ReferenceError: Can’t find variable: moving_canvas_context in file
(line 5)
I understand the reason the test is failing. It doesn’t understand the variable since it is defined in a separate JavaScript file. However, it is declared globally and works in reality.
How do I write a jasmine test for this clear_canvas function?
JavaScript Canvas_Actions:
(function() {
window.Canvas_Actions = (function() {
function Canvas_Actions() {}
Canvas_Actions.prototype.clear_canvas = function() {
moving_canvas_context.clearRect(0, 0, moving_canvas.width, moving_canvas.height);
main_canvas_context.drawImage(window.background_image, 0, 0, main_canvas.width, main_canvas.height);
return window.canvas_objects = [];
};
return Canvas_Actions;
})();
}).call(this);
Jasmine Test for Canvas_Actions:
(function() {
describe('Canvas Actions', function() {
return describe('clear_canvas', function() {
return it('clears the canvases and deletes all objects', function() {
var actions;
jasmine.getFixtures().fixturesPath = "../spec/javascript/fixtures";
loadFixtures("canvas_fixture.html");
actions = new Canvas_Actions();
actions.clear_canvas();
return expect(canvas_objects).toEqual([]);
});
});
});
}).call(this);
Well, it also needs to be declared when the test runs. So you’re probably missing a reference to the script where it is defined in the testing fixture html.
Also, global variables are normally not a good idea, they tend to create difficult bugs. Since you’re already using jasmine as a testing framework, try to abstract the dependency on that global variable in something that you pass to your code under test. Then, use jasmine’s mocking abilities to test it.
If you remove the global references from
Canvas_Actions, it could look like this:You can mock the
canvasargument with jasmine and testCanvas_Actionsin isolation.As can be noted, this code might unearth a
Canvasclass, and you might find out thatclear_canvasbelongs in there. Use the tests to guide your design, one step at a time.