I've been struggling over the past couple of weeks with unit testing a file upload react component with jest. Specifically, I'm trying to test whether or not the method onReadAsDataUrl is being called from FileReader in one of my methods. This is an example method I am testing:
loadFinalImage = async (file) => {
const reader = new FileReader();
reader.onloadend = () => {
this.setState({
imagePreviewUrl: reader.result,
validCard: true,
});
};
await reader.readAsDataURL(file);
}
This is how I am attempting to mock FileReader and test whether or not onReadAsDataUrl has been called:
it('is a valid image and reader.onReadAsDataUrl was called', () => {
const file = new Blob(['a'.repeat(1)], { type: 'image/png' });
wrapper = shallow(<ImageUpload />).dive();
const wrapperInstance = wrapper.instance();
const mockReader = jest.fn();
jest.spyOn('FileReader', () => jest.fn());
FileReader.mockImplementation(() => { return mockReader });
const onReadAsDataUrl = jest.spyOn(mockReader, 'readAsDataURL');
wrapperInstance.loadFinalImage(file);
expect(onReadAsDataUrl).toHaveBeenCalled();
});
After I run: yarn jest
, I get the following test failure:
Cannot spyOn on a primitive value; string given.
I assume I am getting this error because I am not importing FileReader
, but I am not exactly sure how I would import it or mock it because FileReader
is an interface. Here is an image of the test failure:
I am a bit of a noob with jest, reactjs, and web development, but would love to learn how to conquer this problem. Some resources I have looked at so far are: Unresolved Shopify Mock of FileReader, How to mock a new function in jest, and Mocking FileReader with jasmine.
Any help would be greatly appreciated! Thank you in advance.
jest.spyOn(object, methodName)
Have you tried creating a mock for FileReader in theglobal
and then doingjest.spyOn(global, 'FileReader')
instead? – Jackyefjest.spyOn('FileReader', () => jest.fn())
forjest.spyOn(global, 'FileReader')
and the error message changed to this line:FileReader.mockImplementation(() => { return mockReader })
. The new error message is:TypeError: _sys.default.mockImplementation is not a function
– airvine