首页 > 解决方案 > 如何使用酶对作为属性传递的元素进行断言?

问题描述

问题

假设我们有一个 React 组件Page,它呈现组件Layout并将元素SidePanel作为属性向下传递。我们如何对 Enzyme 中SidePanel的属性做出断言?

const Page = () => (
  <Layout
    contentLeft={
      <SidePanel expanded={true} />
    }
  >
    // ...
  </Layout>
);

我试过的

由于 'contentLeft' 严格来说不是渲染道具,我们不能利用 Enzyme 的 renderProp 功能:

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

什么有效

...但不是很优雅

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

有没有更简单的方法?

标签: reactjstypescriptenzyme

解决方案


我最终通过实现一个助手“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);

推荐阅读