简体   繁体   中英

React - componentWillReceiveProps does not execute when component rendered in unit test

New to React, so apologize in advance if this is an ignorant question. I'm using componentWillReceiveProps to execute a function post-render. The function is passed in as a prop. Trying to write a unit test to show that the passed in function gets called, but componentWillReceiveProps does not seem to get called when I render the component in my test. It works when I run the app in the browser, but not in the test.

Here's the test:

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);
});

Here's the code being tested:

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

Even the log statement does not seem to be hit, and I'm not sure why. Googling has not yielded an answer.

Edit for the first answer - attempted to do a second render as follows, but still not having any luck:

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

componentWillReceiveProps is not called on the initial render, as stated in the docs:

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

Either try to use another lifecycle method or re-render the component in your test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM