【问题标题】:Testing destructured Context consumer测试解构的上下文消费者
【发布时间】:2019-04-29 21:15:53
【问题描述】:

我正在尝试使用 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'.

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

【问题讨论】:

    标签: reactjs jestjs react-context


    【解决方案1】:

    感谢 stephenwil 在这里的回答,我能够弄清楚: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 })
      };
    });
    

    我的测试正在运行!

    【讨论】:

      猜你喜欢
      • 2019-05-06
      • 2013-10-07
      • 1970-01-01
      • 2019-02-24
      • 1970-01-01
      • 1970-01-01
      • 2021-05-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多