2011-10-06 37 views
24

我创建一个js小部件,第一部分是添加脚本宽的JavaScript,这样的事情(例如,从谷歌分析):测试DOM操作在茉莉花测试

(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); 
})(); 

如何茉莉花测试(使用灯具?)?

+0

可能重复的[如何单元测试DOM操作(茉莉花)](http://stackoverflow.com/questions/16163852/how-to-unit -test-dom-manipulation-with-jasmine) – Gajus

回答

4

我想你可以执行你的动作,然后检查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); 

是否有兴趣听一个更好的方法,虽然。用茉莉花检查DOM总是感觉有点不好意思。

23

为了在我的规格中设置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"); 
});