首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何测试子组件根据父组件的状态进行渲染?

如何测试子组件根据父组件的状态进行渲染?
EN

Stack Overflow用户
提问于 2018-12-27 15:52:03
回答 1查看 621关注 0票数 0

我的父组件根据状态{ conditionMet : true }呈现一个<Child1 />组件。

如何编写一个测试来检查子组件本身的呈现,而不是组件内字符串的呈现?我想避免使用setTimeout()

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

React: 16.6.3 Jest: 23.6.0酶: 3.7.0酶-接头-react-16

ParentComponent的Jest单元测试

代码语言:javascript
复制
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

代码语言:javascript
复制
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>
    );
  }
}
EN

回答 1

Stack Overflow用户

发布于 2018-12-27 18:33:23

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

向孩子发送一个道具,这是一个函数,当孩子挂载时调用该函数。

挂载为,

代码语言:javascript
复制
<Clild1 sendConfirmation={this.receiveConfirmation.bind(this)} />

在parent中:

代码语言:javascript
复制
receiveConfirmation(e, rendered_child){ this.setState({rendered_child}) }

在Child1中:

代码语言:javascript
复制
componentDidMount(){this.props.sendConfirmation(1);}

现在,如果您可以检查Parent的状态,则可以始终检查this.state.rended_child的值。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53941580

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档