簡體   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