Luc
Luc

Reputation: 534

How to make assertions on element passed down as property with Enzyme?

The problem

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>
);

What I've tried

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);

What works

... 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

Answers (1)

Luc
Luc

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

Related Questions