简体   繁体   English

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

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

I have two components;我有两个组成部分; a page which consumes a file list from the child and displays a message if any of the files are not of a valid type.一个页面,它使用来自子级的文件列表,并在任何文件不是有效类型时显示一条消息。

The parent passes a function to the child via props so that they can communicate.父级通过 props 将函数传递给子级,以便他们可以进行通信。

If any of the files are invalid then I display a message to the user informing them.如果任何文件无效,那么我会向用户显示一条消息通知他们。

I am unsure as to how to test this in React with Jest as we are trying to test all the components in isolation but they have the callback function dependency to trigger the message.我不确定如何在 React 中使用 Jest 进行测试,因为我们正在尝试单独测试所有组件,但它们具有触发消息的回调函数依赖项。

Should I move the invalid file logic and message display to the child?我应该将无效的文件逻辑和消息显示移动到孩子吗? That way I increase the complexity of the component but make it easier to test?这样我会增加组件的复杂性,但更容易测试吗?

Parent Component父组件

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

Child component子组件

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