2014-12-02 49 views
2

我試圖寫有如下茉莉敲開特徵測試和我得到以下錯誤:如何重置淘汰賽綁定在茉莉花測試

錯誤:你不能多次申請綁定同一個元素。

describe("ThreeStepNavigationView",()=> { 
    var testSubject; 
    var SmallNavigationStates = ['ribbon','expanded']; 
    var ExtraSmallNavigationStates = ['collapsed','ribbon','expanded']; 
    beforeEach(()=> { 
     loadFixtures('SidebarAndSiteHeader.html'); 
     testSubject = new Mobile.Navigation.ThreeStepNavigation.View(); 
     ko.applyBindings(testSubject); 
    }); 
    describe('When user clicks on navigation toggle button',()=>{ 

    it('Should update state class name to the next state',()=>{ 
     var button = $('#MobileMainNavLink'); 
     var currentScreenSize = Mobile.Helpers.getScreenSize(); 

     button.click(); 

     var classValue = $("#sidebar-wrapper").attr('class'); 
     if (currentScreenSize == 'ExtraSmall') { 
      expect(classValue).toBe(ExtraSmallNavigationStates[1]); 
     } 
     if (currentScreenSize == 'Small') { 
      expect(classValue).toBe(SmallNavigationStates[1]); 
     } 

    }); 

}); 

我沒有嘗試重置ko,但結果是一樣的。

afterEach(()=>{ 
     ko.cleanNode($('#MobileMainNavLink')[0]); 
     ko.cleanNode($('#sidebar-wrapper')[0]); 
    }); 

基於ko文檔cleanNode是一個內部函數,不是API的一部分。

我使用KO 3.2和1.5茉莉

+0

貌似KO被綁定不止一次。我只能猜測這是在加載過程中或在視圖的實例化過程中發生的。嘗試註釋'ko.applyBindings(testSubject);'。 – Ben 2014-12-02 11:18:13

+0

...加上你的測試有點奇怪,因爲它在運行測試的時候會根據屏幕尺寸出現不同的斷言,這可能不是一個好主意(除非我錯過了某些東西)。 – Ben 2014-12-02 11:20:13

+0

嘗試過'removeNode',它與'cleanNode'類似(從DOM中刪除節點) – 2014-12-02 16:06:12

回答

0

你沒有明確地將你綁定到一個節點。我相信這將適用於您的document.body。這解釋了你的錯誤,因爲你沒有清潔身體。

ko.applyBindings(testSubject);

編號:http://knockoutjs.com/documentation/observables.html

In case you’re wondering what the parameters to ko.applyBindings do,

The first parameter says what view model object you want to use with the declarative bindings it activates

Optionally, you can pass a second parameter to define which part of the document you want to search for data-bind attributes. For example, ko.applyBindings(myViewModel, document.getElementById('someElementId')). This restricts the activation to the element with ID someElementId and its descendants, which is useful if you want to have multiple view models and associate each with a different region of the page.

有用的功能:

// Checks if Element has Already been Bound (Stops Errors Occuring if already bound as element can't be bound multiple times) 
var isBound = function (id) { 
    if (document.getElementById(id) != null) 
     return !!ko.dataFor(document.getElementById(id)); 
    else 
     return false; 
}; 

答:

testSubject = new Mobile.Navigation.ThreeStepNavigation.View(); 
if (isBound("parent-container")) 
    ko.cleanNode(document.getElementById('parent-container')); 
ko.applyBindings(testSubject, document.getElementById("parent-container"));