我的测试失败的原因如下:
ReferenceError: Can’t find variable: moving_canvas_context in file
(line 5)
我理解测试失败的原因.它不理解变量,因为它是在单独的javascript文件中定义的.然而,它在全球宣布并且在现实中起作用.
如何为此clear_canvas函数编写茉莉花测试?
JavaScript Canvas_actions:
(function() { window.Canvas_Actions = (function() { function Canvas_Actions() {} Canvas_Actions.prototype.clear_canvas = function() { moving_canvas_context.clearRect(0,moving_canvas.width,moving_canvas.height); main_canvas_context.drawImage(window.background_image,main_canvas.width,main_canvas.height); return window.canvas_objects = []; }; return Canvas_Actions; })(); }).call(this);
Canvas_actions的Jasmine测试:
(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);
解决方法
it is declared globally and works in reality
好吧,它还需要在测试运行时声明.所以你可能错过了对测试夹具html中定义的脚本的引用.
此外,全局变量通常不是一个好主意,它们往往会产生困难的错误.由于您已经在使用jasmine作为测试框架,因此尝试在传递给测试代码的内容中抽象出对该全局变量的依赖性.然后,使用jasmine的模拟能力来测试它.
如果从Canvas_Actions中删除全局引用,它可能如下所示:
var Canvas_Actions = function(canvas) { this.canvas = canvas; } Canvas_Actions.prototype.clear_canvas = function(background_image) { var canvas = this.canvas; canvas.getContext().clearRect(0,canvas.width,canvas.height); canvas.getContext().drawImage(background_image,canvas.height); canvas.clearObjects(); };
您可以使用jasmine模拟canvas参数并单独测试Canvas_Actions.
可以注意到,这段代码可能会发现一个Canvas类,你可能会发现clear_canvas属于那里.使用测试来指导您的设计,一步一步.