2014-09-28 182 views
2

我想如果某些的javascript(使用jQuery或任何其他框架)來測試應用到一定HTML代碼將在頁面上創建某些行爲。例如:有沒有辦法進行單元測試unobstrusive jQuery的場景

如果我有HTML(寫在一個測試爲Stub)

<div class="order"> 
    <div class="id">15</div> 
    <div class="client">John</div> 
</div> 

而且我已經包括JS文件(寫在測試中也):

jquery.js 
orders.js (the one I want to test) 

測試的主要部分(語法想象的)

part 1: 

    'client'.is 'hidden' 

part 2: 

    'order'.click 
    'client'.should_be visible 

我想測試通過才orders.js有這樣的代碼:

$(function(){ 
    $('.client').hide(); 
    $('.order').click(function(){ 
    $(this).children('.client').show(); 
    }); 
}); 

我想,我可以做這樣的事情與rspec的功能或黃瓜,但是否有任何更具體的框架這樣的測試?任何幫助,將不勝感激。

回答

1

至少有兩種解決方案。

首先是jasmine-jquery HTML fixtures。引用:

jasmine-jquery的Fixture模塊允許您加載HTML內容 以供您的測試使用。整體工作流程如下:

在myfixture.html文件:

<div id="my-fixture">some complex content here</div> 

內部測試:

loadFixtures('myfixture.html') 
$('#my-fixture').myTestedPlugin() 
expect($('#my-fixture')).to... 

而且,對於一個輔助方法爲您的測試創建HTML元素是 提供的:

sandbox([{attributeName: value[, attributeName: value, ...]}])

它創建了一個默認id="sandbox"空DIV元素。如果提供了 屬性的散列,則會爲此DIV標記設置它們。如果屬性的散列 包含id屬性,則它將覆蓋默認的 值。自定義屬性也可以設置。

而且還有jasmine-fixtures庫。引文:

比方說,你想要寫一些代碼,需要 中選擇元素,從使用jQuery的DOM茉莉花規格:

$('#toddler .hidden.toy input[name="toyName"][value="cuddle bunny"]') 

...

茉莉花燈具的詞綴方法可以代替:

beforeEach(function(){ 
    affix('#toddler .hidden.toy input[name="toyName"][value="cuddle bunny"]') 
}); 
相關問題