单元测试 – 如何在React组件上测试支持更新

单元测试React组件支持更新的正确方法是什么?

这是我的测试夹具

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

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

'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.'

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

如果您在同一个容器节点中重新呈现不同道具的元素,则会更新而不是重新安装。见 React.render

在你的情况下,你应该直接使用ReactDOM.render而不是TestUtils.renderIntodocument。后来creates a new container node every time it is called,因此也是一个新的组件。

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和Vue一样的,核心思想玩的就是组件...
前言: 前段时间学习完react后,刚好就接到公司一个react项目...
前言: 最近收到组长通知我们项目组后面新开的项目准备统一技...
react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...