【问题标题】:Testing DOM Ready with Teaspoon and Jasmine使用 Teaspoon 和 Jasmine 测试 DOM 就绪
【发布时间】:2015-08-02 00:25:35
【问题描述】:

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

理想情况下,我可以在需要 JS 文件之前设置一个夹具,但如果我不将 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 之前模拟它?

【问题讨论】:

    标签: javascript ruby-on-rails unit-testing jasmine teaspoon


    【解决方案1】:

    我也遇到了一些问题,我能想到的最好的方法就是定义一个函数来执行所有 .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
      });
    });
    

    【讨论】:

      【解决方案2】:

      您可以像这样在测试的最顶部包含您的cool.js:

      //= require cool.js
      

      【讨论】:

      • 原提问者说那不行,因为他想绑定东西到DOM,所以DOM需要在 Javascript被加载之前存在。跨度>
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-11
      • 1970-01-01
      • 2015-03-04
      • 1970-01-01
      • 2011-12-02
      • 1970-01-01
      相关资源
      最近更新 更多