单元测试 – 如何在React组件上测试支持更新
发布时间:2020-12-15 06:29:57 所属栏目:百科 来源:网络整理
导读:单元测试React组件支持更新的正确方法是什么? 这是我的测试夹具 describe('updating the value',function(){ var component; beforeEach(function(){ component = TestUtils.renderIntoDocument(MyComponent value={true} /); }); it('should update the st
|
单元测试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);
});
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
