Reputation: 534
Suppose that we have a React component Page that renders component Layout and passes down the element SidePanel as a property. How would we make assertions on the properties of SidePanel in Enzyme?
const Page = () => (
<Layout
contentLeft={
<SidePanel expanded={true} />
}
>
// ...
</Layout>
);
Since 'contentLeft' is strictly not a render prop, we cannot utilize Enzyme's renderProp functionality:
const wrapper = shallow(<Page />)
.find(Layout)
.renderProp("contentLeft")();
// TypeError: ShallowWrapper::renderProp(): expected prop "contentLeft" to contain a
// function, but it holds "object"
const expanded = wrapper.find(SidePanel).prop("expanded");
expect(expanded).toEqual(true);
... but isn't quite elegant
const contentLeft = shallow(<Page />)
.find(Layout)
.prop("contentLeft");
const ContentLeft = () => contentLeft;
const wrapper = shallow(<ContentLeft />);
const expanded = wrapper.find(SidePanel).prop("expanded");
expect(expanded).toEqual(true);
Is there an easier way?
Upvotes: 2
Views: 419
Reputation: 534
I've solved it in the end by implementing a helper 'shallowProperty':
// shallowProperty.tsx
const toComponent = (
element:
| React.ReactElement<any, string | React.JSXElementConstructor<unknown>>
| undefined
) => {
const Component = () => (element as unknown) as JSX.Element;
return <Component />;
};
const shallowProperty = (
element: ReactElement<any, string | JSXElementConstructor<any>> | undefined
) => shallow(toComponent(element));
// my.test.tsx
const contentLeft = shallowProperty(
shallow(<Page />)
.find(Layout)
.prop("contentLeft")
);
const expanded = contentLeft.prop("expanded");
expect(expanded).toEqual(true);
Upvotes: 1