带有隐藏子组件的浅渲染

时间:2019-05-14 02:06:46

标签: javascript reactjs enzyme

我有MyComponent通过连接的redux发送请求,如果请求成功,则显示ChildComponent。这是一个摘要:

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

  ...

  sendRequest = (params) => {
    ...
    if (requestWasSuccessful) { // evaluates true
      this.setState({ successfulRequest: true }); 
    }
  }

  render() {
    const { successfulRequest } = this.state;
    console.log(successfulRequest); // true
    return (
      <div>
        {
          successfulRequest && (
            <ChildComponent title="Request successful" />
          )
        }
        <DifferentComponent />
      </div>
    );
  }
}

我有一个模拟请求的测试文件,并检查是否呈现ChildComponent

test('ChildComponent should pop up when request was successful', () => {
  const wrapper = shallow(<MyComponent store={mockStore}/>).dive();
  ... Some stubbing statements ...
  wrapper.instance().sendRequest(params);
  wrapper.update();
  expect(wrapper.find('DifferentComponent')).toHaveLength(1); // Succeeds
  expect(wrapper.find('ChildComponent')).toHaveLength(1); // Fails - received 0
};

由于带有条件语句的额外嵌套,看来ChildComponent不被视为MyComponent的顶级子组件。这是我从Google发现隐藏组件的唯一方法。

是否可以:

  • 强制ShallowWrapper中的MyComponent呈现ChildComponent;或
  • 确保ChildComponentMyComponent的顶级子组件吗?

0 个答案:

没有答案