简体   繁体   中英

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.

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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