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