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

前端之家收集整理的这篇文章主要介绍了单元测试 – 如何在React组件上测试支持更新前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
单元测试React组件支持更新的正确方法是什么?

这是我的测试夹具

  1. describe('updating the value',function(){
  2. var component;
  3. beforeEach(function(){
  4. component = TestUtils.renderIntoDocument(<MyComponent value={true} />);
  5. });
  6.  
  7. it('should update the state of the component when the value prop is changed',function(){
  8. // Act
  9. component.props.value = false;
  10. component.forceUpdate();
  11. // Assert
  12. expect(component.state.value).toBe(false);
  13. });
  14. });

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

  1. '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,因此也是一个新的组件。

  1. var node,component;
  2. beforeEach(function(){
  3. node = document.createElement('div');
  4. component = ReactDOM.render(<MyComponent value={true} />,node);
  5. });
  6.  
  7. it('should update the state of the component when the value prop is changed',function(){
  8. // `component` will be updated instead of remounted
  9. ReactDOM.render(<MyComponent value={false} />,node);
  10. // Assert that `component` has updated its state in response to a prop change
  11. expect(component.state.value).toBe(false);
  12. });

猜你在找的React相关文章