繁体   English   中英

如何在 React 中测试从子组件提升到父组件的状态?

[英]How to test state that has been lifted up from child to parent component in React?

我有两个组成部分; 一个页面,它使用来自子级的文件列表,并在任何文件不是有效类型时显示一条消息。

父级通过 props 将函数传递给子级,以便他们可以进行通信。

如果任何文件无效,那么我会向用户显示一条消息通知他们。

我不确定如何在 React 中使用 Jest 进行测试,因为我们正在尝试单独测试所有组件,但它们具有触发消息的回调函数依赖项。

我应该将无效的文件逻辑和消息显示移动到孩子吗? 这样我会增加组件的复杂性,但更容易测试吗?

父组件

    const Parent = () => {
     const handleOnDocumentDrop = useCallback(
        (fileList): void => {
          if (invalid.length) {
            // I want to be able to assert that this is shown in Jest
            toast({
              position: 'top-right',
              title: 'title',
              description: 'description',
              status: 'error',
              duration:'5000',
              isClosable: true,
            });
          }
        },
        []
      );
      return (
    <Child onDocumentDrop={handleOnDocumentDrop} />
      );
    };

子组件

const Child = ({ onDocumentDrop }) => {
  const onDrop = (e) => {
    e.preventDefault();
    e.stopPropagation();
    if (e.dataTransfer.files) {
      onDocumentDrop(e.dataTransfer.files);
    }
  };
  return (
    <Flex
      onDrop={onDrop}
    >
    </Flex>
  );
};
const trigger = jest.fn();
const wrapper = render(<Child onDocumentDrop={trigger} />);

const images = //files to test

wrapper.find(addressTheDropzoneHere).simulate('drop', { dataTransfer: { files: images } });
expect(trigger).toBeCalledTimes(numberOfIncorrectFiles)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM