I have been staring at this for days and I don't know where is the wrong part. I am a total newbie in using Jest (and React if that matters) so I'm trying to understand how it works. Okay, so basically here, with this line of code below, I would love to test the extension of the file input and if it is not in the desired extension, it will throw a window alert:
handleChangeFile = e => {
const file = e.target.value;
const filePath = e.target.value.split(/\\/g);
const fileName = filePath[filePath.length-1];
const ext = file.slice((file.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
const acceptedFormat = ['jpg', 'png', 'jpeg'];
if (acceptedFormat.includes(ext)) {
this.firestore
.storage
.ref(`justificatifs/${fileName}`)
.put(file)
.then(snapshot => snapshot.ref.getDownloadURL())
.then(url => {
this.fileUrl = url
this.fileName = fileName
})
} else {
e.target.value = "";
alert("Choose a jpg, jpeg, or png file");
}
}
and this is my test:
import { fireEvent, screen } from "@testing-library/dom"
import userEvent from '@testing-library/user-event'
import NewBillUI from "../views/NewBillUI.js"
import NewBill from "../containers/NewBill.js"
describe('When I am on NewBill Page', () => {
test('When I choose a file in a correct format to upload, the file should be loaded and handled', () => {
const html = NewBillUI();
document.body.innerHTML = html;
jest.spyOn(window, 'alert').mockImplementation(() => {});
const onNavigate = (pathname) => {
document.body.innerHTML = ROUTES({pathname})
}
const firestore = null;
const newBill = new NewBill({ document, onNavigate, firestore, localStorage: window.localStorage })
const input = screen.getByTestId('file');
const handleChangeFile = jest.fn(newBill.handleChangeFile);
input.addEventListener('change', handleChangeFile);
const fileTrue = new File(['testFile'], 'testFile.jpg', {type: 'image/jpg'});
userEvent.upload(input, fileTrue);
expect(handleChangeFile).toHaveBeenCalled();
expect(input.files[0]).toStrictEqual(fileTrue);
expect(input.files).toHaveLength(1);
expect(window.alert).not.toHaveBeenCalled();
})
}
However, this always throw a fail result:
expect(jest.fn()).not.toHaveBeenCalled()
Expected number of calls: 0
Received number of calls: 2
1: "Choose a jpg, jpeg, or png file"
2: "Choose a jpg, jpeg, or png file"
33 | expect(input.files[0]).toStrictEqual(fileTrue);
34 | expect(input.files).toHaveLength(1);
> 35 | expect(window.alert).not.toHaveBeenCalled();
| ^
36 | })
37 |
The alert even called twice, for that matter. I am not sure if my fault was in the base code itself, or in my wrong method to do the test (the mocking of window alert or the mocking of choosing the file, as these are the two I struggled to understand, or maybe something else). If anyone could lend their perspectives for a bit in this, I would be really grateful.
Thank you in advance!