单元测试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。
原文链接:https://www.f2er.com/react/301683.html在你的情况下,你应该直接使用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); });