使用酶,如果它们是函数返回的结果,如何在组件中寻找子组件

问题描述 投票:0回答:1

我正在使用玩笑/酶,并希望检查React组件的存在子元素如果我具有子组件的功能

const children = () => (
    <>
      <div>...</div>
      <div>...</div>
    </>
) 
return <Component>{children}</Component>;

为什么我不能这样做

  test('Should render div', () => {
    wrapper = shallow(<MyComponent />);
    const component = wrapper.find(Component);
    expect(component.exists()).toBe(true);  //return true
    const children = wrapper.find('div')
    expect(children.exists()).toBe(false);  //return false
  });
reactjs enzyme jest
1个回答
0
投票

您的孩子函数基本上是一个渲染道具,而浅表则不会渲染它。不过,您可以通过将其调用为函数来触发渲染,例如

shallow(
  shallow(<MyComponent />)
    .find(Component)
    .prop('children')()
)

所以您的测试看起来像

test('Should render div', () => {
    wrapper = shallow(<MyComponent />);
    const component = wrapper.find(Component);
    expect(component.exists()).toBe(true);  //return true
    const renderProp = shallow(component.prop('children')());
    const children = renderProp.find('div');
    expect(children.exists()).toBe(true); 
  });
© www.soinside.com 2019 - 2024. All rights reserved.