'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>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
