I am trying to test a bunch of functions that asynchronously run after a user uploads a file. These functions are all within a React Component called UploadImageModal. These functions are triggered by this on change function:
const onChange = async () => {
try {
const file = document.querySelector('#upload-profile-img-dialog')
.files[0];
if (file) {
const fileData = {
mimeType: file.type,
base64: await getBase64(file),
file
};
await hasMinPicDimension(fileData);
setPicFile(fileData);
}
} catch (error_) {
setError(error_.message);
}
};
This on change function then calls this hasMinPicDimensions function:
const hasMinPicDimension = ({ mimeType, base64, file }) =>
new Promise((resolve, reject) => {
const image = new Image();
image.src = `data:${mimeType};base64,${base64}`;
image.addEventListener('load', () => {
if (!['image/gif', 'image/jpeg', 'image/png'].includes(mimeType)) {
return reject(new Error('Image is not a supported type'));
}
if (image.height >= 151 && image.width >= 151) {
return resolve({ mimeType, base64, file });
}
return reject(new Error('Image is too small'));
});
image.addEventListener('error', () => {
reject(new Error('File is not an image'));
});
});
And after that function resolves it's promise, the setPicFile, which is a react state change that changes a components src to have the data URI of the image. and here is the image upload input component:
<Input
id="upload-profile-img-dialog"
name="profileImage"
type="file"
accept="image/gif,image/jpeg,image/png"
onChange={onChange}
sx={{ visibility: 'hidden' }}
data-testid="fileinput"
/>
I have tried testing this function by just using Jest to simulate an image upload - but no matter what the functions above do not trigger because Jest does not wait for the promises to resolve.
Does anyone have any advice as to how I can do this with Jest? If I need to use enyzme as well, that will be fine.