如何测试自定义文件上传 React 组件?

How to test custom file upload React component?

我有一个用于上传文件的 React 组件。下面是处理文件选择的部分代码,选择文件后,它将显示缩略图。

我想使用 RTL 测试文件选择:单击 EvidenceUploaderPanel 按钮,这将打开文件选择器输入元素,然后选择文件。

这也会在选择文件时发出上传文件的请求。

但是我不知道如何开始。

function UploadScreen({
  title,
  maxNumberOfUploadFiles = 3,
  acceptedFileTypes,
}: Props) {
  const [documents, setDocuments] = useState<FileObject[]>([]);


  const handleFileSelection = (files: FileList) => {

    const documentsWithThumbnails = Array.from(files).map((file) => {
      // here I also make a request to upload each file.
      return {
        file,
        thumbnailURL: URL.createObjectURL(file),
        name: file.name,
      };
    });
    setDocuments((currentDocuments) => [...currentDocuments, ...documentsWithThumbnails]);
  };

  const inputRef = useRef(
    (() => {
      const element = document.createElement('input');
      element.multiple = true;
      element.type = 'file';
      element.accept = acceptedFileTypes?.join(',') || IMAGE_MIME_TYPES.join(',');
      element.addEventListener('change', () => {
        if (element.files && documents.length + element.files.length < maxNumberOfUploadFiles) {
          handleFileSelection(element.files);
          element.value = '';
        }
      });

      return element;
    })(),
  );


  const handleOpenFileClicker = () => {
    inputRef.current.click();
  };

  return (
    <div>
      <h2 className="container">{title}</h2>
       {documents.length > 0 ? (
        <section>
          <div className="body-text">
           Add files
          </div>
          <div className="thumbnail-container">
            {documents.map((doc) => {
              return (
                <BaseThumbnail
                  src={doc?.thumbnailURL}
                  key={doc.name}
                  deleteAction={() => {
                    deleteDocument(doc.name);
                  }}
                />
              );
            })}
          </div>
          <Link onPress={handleOpenFileClicker}>
            Add photos
          </Link>
        </section>
      ) : (
        <section>
          <div className="text">
            Add files
          </div>
          <div className="upload-container" />
          <EvidenceUploaderPanel
            labelText="upload files"
            openFilePicker={handleOpenFileClicker}
          />
        </section>
       )}
    </div>
  );
}

您是否考虑过使用 cypress? 他们有一个很好的内置功能,可以完全满足您的需求,而且设置非常简单。

我建议您使用 cypress component testing for react, they have an entire page on their website’s docs explaining how to set it up. And than you can just mount the file selection component and use their cy.selectFile() 方法。

祝你好运:)