How to test a prop update on React component

前端 未结 8 532
鱼传尺愫
鱼传尺愫 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:39

    AirBnB's Enzyme library provides an elegant solution to this question.

    it provides a setProps method, that can be called on either a shallow or jsdom wrapper.

        it("Component should call componentWillReceiveProps on update", () => {
            const spy = sinon.spy(Component.prototype, "componentWillReceiveProps");
            const wrapper = shallow(<Component {...props} />);
    
            expect(spy.calledOnce).to.equal(false);
            wrapper.setProps({ prop: 2 });
            expect(spy.calledOnce).to.equal(true);
        });
    
    0 讨论(0)
  • 2020-12-14 06:41

    This is an older question, but in case anyone else stumbles upon this, the following setup has worked for me nicely:

    it('updates component on property update', () => {
        let TestParent = React.createClass({
            getInitialState() {
                return {value: true};
            },
            render() {
                return <MyComponent value={this.state.value}/>;
            }
        });
        component = TestUtils.renderIntoDocument(<TestParent/>);
        component.setState({value: false});
        // Verification code follows
    });
    

    This makes React run the usual component update.

    0 讨论(0)
提交回复
热议问题