2011-10-06 40 views
24

tôi là tạo ra một widget js và một phần đầu tiên là thêm kịch bản rộng javascript, một cái gì đó như thế này (ví dụ từ Google Analytics):Kiểm tra DOM thao tác trong thử nghiệm Jasmine

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

Làm thế nào để thử nghiệm nó với hoa nhài (sử dụng đồ đạc?)?

+0

có thể trùng lặp [cách kiểm tra đơn vị DOM thao tác (với hoa nhài)] (http://stackoverflow.com/questions/16163852/how-to-unit -test-dom-manipulation-with-jasmine) – Gajus

Trả lời

4

Tôi cho rằng bạn có thể thực hiện hành động của bạn, sau đó kiểm tra href trên thẻ script đầu tiên như vậy:

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

Jasmine spec:

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

Sẽ được quan tâm trong buổi điều trần một phương pháp tốt hơn, Tuy nhiên. Kiểm tra DOM với Jasmine luôn luôn cảm thấy một chút hacky.

23

Để thiết lập đồ đạc HTML trong thông số kỹ thuật của tôi, tôi đã viết jasmine-fixture. Với nó, bạn có thể làm những việc như sau:

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 

Và sau đó, nó sẽ dọn dẹp sau bạn.

Đối với kỳ vọng về trạng thái của DOM, tôi sử dụng jasmine-jquery. Nó cung cấp một tấn matchers như một trong những bên dưới:

it('is named Jim', function(){ 
    expect($input).toHaveValue("Jim"); 
}); 
Các vấn đề liên quan