[英]React - componentWillReceiveProps does not execute when component rendered in unit test
React的新手,如果這是一個無知的問題,請提前道歉。 我正在使用componentWillReceiveProps來執行渲染后的功能。 該函數作為道具傳遞。 試圖編寫一個單元測試以顯示傳遞的函數被調用,但是當我在測試中呈現組件時,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} />);
如文檔所述,未在初始渲染上調用componentWillReceiveProps
:
https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops
嘗試使用其他生命周期方法或在測試中重新渲染組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.