使用React测试库模拟ANTD表单钩子

问题描述 投票:0回答:2

我想嘲笑 ANTD 的

const [form] = Form.useForm();

 const form= jest.mock('antd', () => {
        const originalModule = jest.requireActual('antd');
        return {
            Form: {
                ...originalModule.useForm,
                useForm: () => [{
                    scrollToField: jest.fn(),
                    getFieldInstance: jest.fn()
                }]
            },
        };
    });

使用上面的代码运行测试我得到

Cannot set properties of undefined (setting 'name')
TypeError: Cannot set properties of undefined (setting 'name')

问题:为什么我会收到此错误以及如何修复测试?

reactjs jestjs react-testing-library
2个回答
2
投票

我设法解决问题的方法是使用表单的实例来正确模拟它,如下所示:

 jest.mock("antd", () => {
  const antd = jest.requireActual("antd");
  const { Form } = antd;

  const { result } = renderHook(() => Form.useForm());

  return {
    ...antd,
    Form: {
      ...Form,
      useForm: () => [
        {
          ...result.current[0],
          scrollToField: jest.fn(),
          getFieldInstance: jest.fn()
        },
      ],
    },
  };
});

由于 antd 使用表单实例来进行操作,因此有必要模拟所有内容或提供一些实际的表单实例来使用。


0
投票
● Test suite failed to run

    ReferenceError: Cannot access 'react_1' before initialization

      31 |   const { Form } = antd;
      32 |
    > 33 |   const { result } = renderHook(() => Form.useForm());
         |                      ^
      34 |
      35 |   return {
      36 |     ...antd,
© www.soinside.com 2019 - 2024. All rights reserved.