3

我正在为我的 Rails 应用程序使用 Teaspoon 和 Jasmine 编写测试。在大多数情况下,我了解如何测试独立的 js 模块,但我不确定如何测试绑定到 DOM 就绪事件的模块,例如 JQuery 的$(document).ready().

理想情况下,我可以在需要 JS 文件之前设置一个固定装置,但如果我不把它require作为第一条语句,那么它就会被忽略。

通常如何进行测试?

我本来想做类似的事情:

酷.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?

4

2 回答 2

0

我对此也有一些问题,我能想到的最好的方法就是定义一个函数来执行所有 .ready() 东西,并从测试中调用它:

酷.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
  });
});
于 2019-03-30T02:14:19.663 回答
-2

您可以在测试的最顶部包含您的cool.js,如下所示:

//= require cool.js
于 2016-05-23T16:29:42.870 回答