2016-05-13 63 views
-1

試圖使用React的測試實用程序(https://facebook.github.io/react/docs/test-utils.html)來測試我的組件。反應 - 業主Ownee單元測試

我們擁有Owner和Ownee。

業主呈現:

<Ownee> 
    <div class="inner"> 
     <div class="moreInner" /> 
    </div> 
</Ownee> 

我的測試就像是這樣的:

var comp = TestUtils.renderIntoDocument(<Owner />); 
var innerClass = TestUtils.findRenderedDOMComponentWithClass(comp, "inner"); 
expect(innterClass).to.not.be.null; 

理想的情況下,這應該很好地工作。但實際上,它輸出:「沒有找到完全匹配(找到:0)」。

所以,如果我刪除上述<Ownee></Ownee>所以它就像:

<div class="inner"> 
     <div class="moreInner" /> 
    </div> 

它正常工作,但我不能用這個(必須給予Ownee元太)。

Ownee呈現類似這樣:

<div class="inner"> 
    {this.props.children} 
</div> 

如何使用TestUtils來得到期望的結果(即測試工作,並通過類查找DIV)有什麼建議?

謝謝!

+1

使用'className' ** **不類 – ajmajmajma

+0

正在做的,錯誤類型的簡化代碼。 –

+0

如果ownee呈現className內部,爲什麼還要手動將它添加到ownee標籤之間?你能否只顯示ownee和owner的渲染()是否被修改? – ajmajmajma

回答

0

所以問題不是老闆/老闆。最後,我正在使用React-Bootstrap的模式對話框(作爲Ownee)。所以發生了什麼事情是測試會渲染組件,但它會被放在不同的組件樹上。

要解決這個問題,我也跟着以前問一個問題: Testing a React Modal component

具體來說,user1778856的答案。

var stubModal =() => { 
    var createElement = React.createElement; 
    modalStub = sinon.stub(React, 'createElement', function (elem: any) { 
     return elem === ModalDialog ? 
      React.DOM.div.apply(this, [].slice.call(arguments, 1)) : 
      createElement.apply(this, arguments); 
    }); 
    return modalStub; 
}; 
var stubModalRestore =() => { 
    if (modalStub) { 
     modalStub.restore(); 
     modalStub = undefined; 
    } else { 
     console.error('Cannot restore nonexistent modalStub'); 
    } 
}; 

before(() => { stubModal(); }); 
after(() => { stubModalRestore(); }); 

其他鏈接: Unit testing React Bootstrap modal dialog