【问题标题】:How to test that a Child component renders based on the condition of the parent component's state?如何根据父组件的状态测试子组件是否呈现?
【发布时间】:2018-12-27 07:52:03
【问题描述】:

我的父组件根据状态 { conditionMet : true } 呈现一个 <Child1 /> 组件。
如何编写一个测试来检查子组件本身的呈现,而不是组件内字符串的呈现?我想避免使用setTimeout()

这是我如何构建测试的问题吗?或者,我是如何构建组件的? Jest / Enzyme 中是否存在阻止检查子组件是否已呈现的已知限制或错误?

反应:16.6.3 开玩笑:23.6.0 酶:3.7.0 Enzyme-adapter-react-16

ParentComponent 的 Jest 单元测试:

describe('ParentComponent', () => {
    test('renders Child1 component when conditionMet is true', () => { 

      const parentMount = mount(<ParentComponent />);

      const param1 = "expected value";
      const param2 = true;    
      parentMount.instance().checkCondition(param1, param2); // results in Parent's state 'conditionMet' === 'true'

      //This is not working - the length of the Child1 component is always 0
      expect(parentMount.find(Child1)).toHaveLength(1);

      //This alternate option passes, but it's not testing the rendering of the component!
      expect(parentMount.text()).toMatch('Expected string renders from Child1'); 

    });
  });

ParentComponent.js

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      conditionMet: false
    };
  }

  checkCondition = (param1, param2) => { 
  if (param1 === 'expected value' && param2 === true)
    {
       this.setState({conditionMet: true});
    } else {
       this.setState({conditionMet: false});
     }
     this.displayChildComponent();      
     }
  };

  displayChildComponent() {
    if (this.state.conditionMet) {
      return(
          <Child1 />
      )
    }
    else {
      return(
          <Child2 />
      )
    }
  }

  render() {
    return (
      <div className="parent-container">
        {this.displayChildComponent()}
      </div>
    );
  }
}

【问题讨论】:

    标签: javascript reactjs jestjs enzyme


    【解决方案1】:

    我猜这可能是一个漫长的解决方案。但它有效。

    发送一个 props 给 children,它是一个函数,当 child 被挂载时调用这个函数。

    安装为,

    <Clild1 sendConfirmation={this.receiveConfirmation.bind(this)} />
    

    在父母中:

    receiveConfirmation(e, rendered_child){ this.setState({rendered_child}) }
    

    在 Child1 中:

    componentDidMount(){this.props.sendConfirmation(1);}
    

    现在如果你可以检查 Parent 的状态,你可以随时检查 this.state.rendered_child 的值。

    【讨论】:

      猜你喜欢
      • 2020-05-19
      • 2023-03-18
      • 2020-11-30
      • 2016-07-19
      • 1970-01-01
      • 2019-06-07
      • 2021-01-12
      • 2022-06-13
      • 2019-12-23
      相关资源
      最近更新 更多