0

我正在尝试使用 Jest + Enzyme 测试一个组件,确保一个组件被呈现为我的消费者的孩子。当我这样做时,类似的测试有效:

    <FormContextConsumer>
      {({ ...props }) => (
        <Footer
          ...
        />
      )}
    </FormContextConsumer>

像这样模拟上下文:

jest.mock("../../context/FormContext", () => ({
  FormContextConsumer: props => props.children()
}));

并像这样测试它:

it(`should render a 'Footer' component inside the 'FormContextConsumer'`, () => {
  expect(
    shallowTestComponent()
      .find(FormContextConsumer)
      .dive()
      .find(Footer).length
  ).toBe(1);
});

但是当我像这样解构上下文道具时:

    <FormContextConsumer>
      {({ handleSubmit, handleReset }) => (
        <Drawer
          ...
        >
          {children}
        </BaseEntityDrawer>
      )}
    </FormContextConsumer>

并以此进行测试:

  it(`should always render 'Drawer' inside 'FormContextConsumer'`, () => {
    expect(
      shallowTestComponent()
        .find(FormContextConsumer)
        .dive()
        .find(Drawer).length
    ).toBe(1);
  });

我收到此错误:

TypeError: Cannot destructure property `handleSubmit` of 'undefined' or 'null'.

我假设它与我如何模拟模块有关,但我不清楚如何使其适应这种情况。我该如何处理?

4

1 回答 1

0

感谢斯蒂芬维尔在这里的回答,我能够弄清楚:https ://stackoverflow.com/a/51152120/5858391

我将我的模拟上下文更改为:

jest.mock("../../../forms/context/FormContext", () => {
  const handleSubmit = jest.fn();
  const handleReset = jest.fn();

  return {
    FormContextConsumer: props => props.children({ handleSubmit, handleReset })
  };
});

我的测试正在工作!

于 2018-11-29T20:37:18.927 回答