2017-02-24 58 views
1

我的測試:爲什麼我的按鈕在我的測試中未定義?

describe('button component',() => { 
    it('should toggle off when clicked',() => { 
     let component; 
     component = ReactTestUtils.renderIntoDocument(<Search />); 
     let searchbtn = ReactTestUtils.findRenderedDOMComponentWithTag(component, 'button'); 
     ReactTestUtils.Simulate.click(searchbtn); 
     console.log(searchbtn, 'search button***'); //UNDEFINED 
     expect(searchbtn.calledOnce).to.equal(false); 
    }) 
    }); 

這是我的搜索組件:

render() { 
    return (
     <div className="search"> 
     <button className="searchButton" onClick={this.handleSearch}>{this.state.on ? 'ON' : 'OFF'}</button> 
     </div> 
    ); 
    } 

我需要刺探,或嘲笑呢?還是有更好的方法來測試反應中的按鈕?

回答

0

既然你已經加了enzyme標籤我會用enzyme回答。

可以通過淺渲染很容易測試 -

const searchWrapper = shallow(<Search />); 
const button = searchWrapper.find('button').first(); 

當模擬按鈕點擊事件通過onClick道具這是你的情況handleSearch將被稱爲提供onClick處理程序。

所以,如果你設置基於相應的基於狀態的改變UI的變化onClick函數調用一些國家可以進行比較或檢查是否更改是否正確的反映DOM。

,或者使用類似名稱的假方法

,如果你只是想檢查方法被調用或不 -

const onButtonClick = sinon.spy(); 
expect(onButtonClick.calledOnce).to.equal(false); 
button.setProps({ onClick:onButtonClick}); 
button.simulate('click'); 
expect(onButtonClick.calledOnce).to.equal(true); 
+0

你如何找到一個特定的按鈕?但葉爽很有道理 –

+0

@Theworm你可以使用酶中可用的選擇器(類似於CSS選擇器 - 通過id,類名稱,元素類型,道具),例如我已經使用const button = searchWrapper.find('button')。 (); – WitVault

+0

好酷。 .first()似乎很痛苦,如果你有很多按鈕,但我會看看文檔。謝謝:) –

相關問題