Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

258
Visualizações
How to test custom file upload React component?

I have a React component to upload files. Below is part of the code that handles the file selection and once files are selected, it will display thumbnails.

I want to use RTL to test the file selection: clicking button which is EvidenceUploaderPanel, this opens the file selector input element, then choosing files.

This will also make the requests to upload the files as they are selected.

But I have no idea how to start.

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

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Have you thought about maybe using cypress for this? They have a nice built in function that does exactly what you want and the setup Is really easy.

I’d recommend you using the 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() method.

Good luck :)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda