我正在使用Teaspoon和Jasmine为我的Rails应用程序编写测试。在大多数情况下,我理解如何测试独立的js模块,但我不确定如何测试与JQuery的$(document).ready()
绑定到DOM就绪事件的模块。
理想情况下,我可以在需要JS文件之前设置一个fixture,但如果我不将require
作为第一个语句,那么它将被忽略。
人们通常如何测试这个?
我想做的事情如下:
cool.js:
$(document).ready(function() {
$(".stuff").click(stuffClickHandler);
}
cool_spec.js:
fixture.load("fixture_with_stuffs.html");
//= require cool
describe("on ready", function() {
it("should bind handlers to all stuffs", function() {
// test stuffs for handlers
});
});
但这不起作用,因为如果//= require
出现在任何东西之后,它似乎不会加载js。
即使我们像$(document).ready(initFunction)
那样让它变得极小,我们如何编写一个测试来确保initFunction
被调用而不会在require
之前嘲笑它?
我也有一些问题,我能想到的最好的只是定义一个函数来执行所有.ready()的东西,并从测试中调用它:
cool.js:
var onReady = function() {
$(".stuff").click(stuffClickHandler);
}
$(document).ready(function() {
onReady();
}
cool_spec.js:
//= require cool
fixture.load("fixture_with_stuffs.html");
onReady();
describe("on ready", function() {
it("should bind handlers to all stuffs", function() {
// test stuffs for handlers
});
});
你可以在你的最顶层包括你的cool.js,如下所示:
//= require cool.js