How to test a prop update on React component

前端 未结 8 567
鱼传尺愫
鱼传尺愫 2020-12-14 05:36

What is the correct way of unit testing a React component prop update.

Here is my test fixture;

describe(\'updating the value\', function(){
                 


        
8条回答
  •  执念已碎
    2020-12-14 06:17

    Both TestUtils.renderIntoDocument and ReactDOM.render uses the returned value from ReactDOM.render. According to React docs:

    ReactDOM.render() currently returns a reference to the root ReactComponent instance. However, using this return value is legacy and should be avoided because future versions of React may render components asynchronously in some cases. If you need a reference to the root ReactComponent instance, the preferred solution is to attach a callback ref to the root element

    What if we take this advise and do something like this:

    let component, node;
    
    const renderComponent = (props = {}) => {
      ReactDOM.render( component = r} {...props} />, node);
    }
    
    beforeEach(function(){
        node = document.createElement('div');
        renderComponent({value: true}, node); 
    });
    
    it('should update the state of the component when the value prop is changed', function(){
        // `component` will be updated instead of remounted
        renderComponent({value: false}, node); 
        // Assert that `component` has updated its state in response to a prop change
        expect(component.state.value).toBe(false);
    });
    

提交回复
热议问题