我正在使用玩笑/酶,并希望检查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
});
您的孩子函数基本上是一个渲染道具,而浅表则不会渲染它。不过,您可以通过将其调用为函数来触发渲染,例如
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);
});