【问题标题】:Testing DOM manipulating in Jasmine test在 Jasmine 测试中测试 DOM 操作
【发布时间】:2011-12-02 02:39:52
【问题描述】:

我正在创建一个 js 小部件,第一部分是添加脚本宽度 javascript,如下所示(来自谷歌分析的示例):

(function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

如何用 jasmine 测试它(使用夹具?)?

【问题讨论】:

标签: javascript unit-testing jasmine


【解决方案1】:

为了在我的规范中设置 HTML 固定装置,我写了jasmine-fixture。有了它,你可以做这样的事情:

var $foo, $input;
beforeEach(function(){
  $foo = affix('.foo');
    # appends to the DOM <div class="foo"></div> 
  $input = $foo.affix('input[id="name"][value="Jim"]');
    # appends <input id="name" value="Jim"/> beneath the .foo div

而且 afterEach,它会在你之后清理。

对于 DOM 状态的预期,我使用jasmine-jquery。它提供了大量的匹配器,如下所示:

it('is named Jim', function(){
  expect($input).toHaveValue("Jim");
});

【讨论】:

    【解决方案2】:

    我想你可以执行你的操作,然后像这样检查第一个脚本标签上的 href:

    function addGA(){
        var ga = document.createElement('script'); 
        ga.type = 'text/javascript'; ga.async = true;
        ga.src = 
          ('https:' == document.location.protocol ? 'https://ssl' : 'http://www')
          + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; 
        s.parentNode.insertBefore(ga, s);
    };
    

    茉莉花规格:

     var href = 'http://www.google-analytics.com/ga.js';
     expect(document.getElementsByTagName('script')[0].href).not.toEqual(href);
     addGa();
     expect(document.getElementsByTagName('script')[0].href).toEqual(href);
    

    不过,我想听听更好的方法。用 Jasmine 检查 DOM 总是感觉有点 hacky。

    【讨论】:

      【解决方案3】:

      对于 Jasmine 的大量 DOM 测试,您可以使用 Jasmine Headless WebKit。

      【讨论】:

        猜你喜欢
        • 2013-04-16
        • 2017-10-19
        • 2013-09-22
        • 2016-09-14
        • 1970-01-01
        • 1970-01-01
        • 2010-11-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多