我正在为我的Rails应用程序编写使用茶匙和茉莉的测试。我理解,在大多数情况下,如何测试独立的js模块,但我不确定如何去测试一个绑定到DOM准备事件的模块,如JQuery的$(document).ready()
。
理想情况下,我可以在需要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