如何测试React组件的prop更新 [英] How to test a prop update on React component

查看:187
本文介绍了如何测试React组件的prop更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

单元测试React组件道具更新的正确方法是什么。

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

这是我的测试夹具;

describe('updating the value', function(){
        var component;
        beforeEach(function(){
            component = TestUtils.renderIntoDocument(<MyComponent value={true} />);
        });

        it('should update the state of the component when the value prop is changed', function(){
            // Act
            component.props.value = false;
            component.forceUpdate();
            // Assert
            expect(component.state.value).toBe(false);
        });
});

此工作正常且测试通过,但这会显示反应警告消息

This works fine and the test passes, however this displays a react warning message

'Warning: Dont set .props.value of the React component <exports />. Instead specify the correct value when initially creating the element or use React.cloneElement to make a new element with updated props.'

我想要测试的是属性的更新,而不是创建具有不同属性的元素的新实例。有没有更好的方法来进行此属性更新?

All i want to test is the update of a property, not to create a new instance of the element with a different property. Is there a better way to do this property update?

推荐答案

如果在同一个容器中重新呈现具有不同道具的元素节点,它将被更新而不是重新安装。请参见 React.render

If you re-render the element with different props in the same container node, it will be updated instead of re-mounted. See React.render.

在您的情况下,您应该直接使用 ReactDOM.render 而不是 TestUtils.renderIntoDocument 。后来的每次创建一个新的容器节点调用,因此也是一个新组件。

In your case, you should use ReactDOM.render directly instead of TestUtils.renderIntoDocument. The later creates a new container node every time it is called, and thus a new component too.

var node, component;
beforeEach(function(){
    node = document.createElement('div');
    component = ReactDOM.render(<MyComponent 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
    ReactDOM.render(<MyComponent value={false} />, node);
    // Assert that `component` has updated its state in response to a prop change
    expect(component.state.value).toBe(false);
});

这篇关于如何测试React组件的prop更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆