How to test a prop update on React component

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

    Here's a solution I've been using that uses ReactDOM.render but doesn't rely on the (deprecated) return value from the function. It uses the callback (3rd argument to ReactDOM.render) instead.

    Setup jsdom if not testing in the browser:

    var jsdom = require('jsdom').jsdom;
    var document = jsdom('
    '); global.document = document; global.window = doc.defaultView;

    Test using react-dom render with async callback:

    var node, component;
    beforeEach(function(done){
        node = document.getElementById('test-div')
        ReactDOM.render(, node, function() {
            component = this;
            done();
        });
    });
    
    it('should update the state of the component when the value prop is changed', function(done){
        // `component` will be updated instead of remounted
        ReactDOM.render(, node, function() {
            component = this;
            // Assert that `component` has updated its state in response to a prop change
            expect(component.state.value).toBe(false);
            done();
        });
    });
    

提交回复
热议问题