2016-10-03 42 views
0

React的新功能,所以如果這是一個無知的問題,請提前道歉。我使用componentWillReceiveProps來執行一個函數post-render。該函數作爲道具傳入。試圖編寫一個單元測試以顯示傳入的函數被調用,但是當我在測試中渲染組件時,componentWillReceiveProps似乎不會被調用。它在瀏覽器中運行應用程序時有效,但不在測試中。React - componentWillReceiveProps在單元測試中呈現組件時不執行

這裏的測試:

it('should call function \'selectAll\' when isDefaultSelectAll is true and component is rendered.',()=> { 
    const selectAllMock = jest.genMockFunction(); 
    const isDefaultSelectAll = true; 
    component = TestUtils.renderIntoDocument(<MyComponent {isDefaultSelectAll, selectAllMock} />);; 
    expect(selectAllMock.mock.calls.length).toBe(1); 
}); 

這裏是正在測試的代碼:

componentWillReceiveProps(nextProps) { 
    console.log('GOT HERE'); 
    if (nextProps.isDefaultSelectAll === true) { 
     nextProps.selectAll(); 
    } 
} 

即使日誌聲明似乎並沒有被擊中,我不知道爲什麼。谷歌搜索沒有得出答案。

編輯的第一個答案 - 試圖做第二如下方式呈現,但仍然沒有任何運氣:

const isDefaultSelectAll = false; 
component = TestUtils.renderIntoDocument(<MyComponent {isDefaultSelectAll, selectAllMock} />); 
isDefaultSelectAll = true; 
component = TestUtils.renderIntoDocument(<MyComponent {isDefaultSelectAll, selectAllMock} />); 
+0

第二次渲染意味着再次強制渲染同一個組件。所以你必須在渲染組件後改變道具。不知道如何使用反應測試工具,但使用酶會像[this]一樣工作(http://airbnb.io/enzyme/docs/api/ShallowWrapper/setProps.html)。 –

回答

0

componentWillReceiveProps不叫初始渲染,如文檔指出:

https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops

要麼嘗試使用其他生命週期方法,要麼在測試中重新渲染組件。

+0

感謝您的及時響應,嘗試了這一點,但無濟於事,仍未受到打擊。對於代碼湯,不知道如何以更好的方式格式化它,但基本上只是在測試中對TestUtils.renderIntoDocument的第二次調用。 'const isDefaultSelectAll = false; component = TestUtils.renderIntoDocument(); isDefaultSelectAll = true; component = TestUtils.renderIntoDocument();' –