Rails 3 中使用jasmine 测试Javascript
虽然测试js代码很恶心;但是要测试,特别是写很多js的时候;
在一个项目中,使用jasmine来测试我们一个需要很多很多js代码的页面;对于那个页面,我都觉得都已经写了一个Js的UI了。。。。当初没有用现成的JS UI框架,真是失误啊~
Jasmine is a behavior-driven development framework for testing your JavaScript code. It does not depend on any other JavaScript frameworks. It does not require a DOM. And it has a clean, obvious syntax so that you can easily write tests.
这是jasmine的介绍;
项目链接:http://pivotal.github.com/jasmine/index.html
测试代码结构是:
describe("Jasmine", function() { it("makes testing JavaScript awesome!", function() { expect(yourCode).toBeLotsBetter(); });});
$ bundle install$ bundle exec jasmine init
rake jasmine
function matchFail_user(it){ $(it).next().val(''); var n = $(it).parent().next(); while(n.attr("class") == 'auto_clean'){ wipe_clean([n.children("input:first").attr('id')]); n = n.next(); }}
describe('matchFail_user',function(){ afterEach(function (){ $("#workspace").remove(); }); it('set project hidden empty and wipe clean current row', function() { $("body").append("<div id='workspace'></div>"); workspace = $("#workspace"); workspace.html("<tr><td><input id='log_entry_1_log_time'></input><input type='text' value='stud' id='projects_iterations_1'></input><input id='project_hidden' type='hidden' value='58'></input></td><td class='auto_clean'><input id='child' type='text' value='king' /></td></tr>"); bind_autocomplete('child', {}); project = $("#projects_iterations_1").get(); project_hidden = $("#projects_iterations_1").next(); spyOn(window,"wipe_clean"); matchFail_user(project) expect(project_hidden.val()).toEqual(""); expect(window.wipe_clean).toHaveBeenCalledWith([$(project).parent().next().children("input:first").attr('id')]); }); });
var Klass = function () {};Klass.staticMethod = function (arg) { return arg;};Klass.prototype.method = function (arg) { return arg;};Klass.prototype.methodWithCallback = function (callback) { return callback('foo');};...describe("spy behavior", function() { it('should spy on a static method of Klass', function() { spyOn(Klass, 'staticMethod');//创建一个监视Klass.staticMethod的监视器,理论上这个是不会有返回值的,因为被拦截了,它可以使用 spyOn(Klass, 'staticMethod').andReturn("result")的方法替它返回结果,也有类似的比如andCallThrough之类的方法来真正实现这个功能; Klass.staticMethod('foo argument'); expect(Klass.staticMethod).toHaveBeenCalledWith('foo argument'); }); it('should spy on an instance method of a Klass', function() { var obj = new Klass(); spyOn(obj, 'method'); obj.method('foo argument'); expect(obj.method).toHaveBeenCalledWith('foo argument'); var obj2 = new Klass(); spyOn(obj2, 'method'); expect(obj2.method).not.toHaveBeenCalled(); }); it('should spy on Klass#methodWithCallback', function() { var callback = jasmine.createSpy(); new Klass().methodWithCallback(callback); expect(callback).toHaveBeenCalledWith('foo'); });});