2011-10-06 60 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"); 
});